use std::path::{Path, PathBuf};
use crate::analysis::AnalysisReport;
use crate::error::{Med64Error, Result};
pub(crate) fn write_asdr_raster_combined_svg(
report: &AnalysisReport,
path: &Path,
w: u32,
h: u32,
) -> Result<()> {
use crate::svg::{
render_line_svg, render_raster_svg, write_svg_file, SvgChartOptions, SvgSeries,
};
let half = (h / 2).max(120);
let asdr: Vec<(f64, f64)> =
report.asdr.points.iter().map(|p| (p.time_ms, p.smoothed_hz)).collect();
let asdr_opts = SvgChartOptions {
width: w,
height: half,
title: "ASDR".into(),
xlabel: "Time (ms)".into(),
ylabel: "Rate (Hz)".into(),
..Default::default()
};
let asdr_svg = render_line_svg(
&[SvgSeries { label: "ASDR".into(), points: asdr, color: "#2563eb".into(), fill: false }],
&asdr_opts,
);
let channels = raster_channels(report);
let mut by_ch: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
for spike in report.spikes.spikes.iter().take(8000) {
by_ch.entry(spike.channel).or_default().push(spike.within_trace_time_ms);
}
let rows: Vec<(usize, Vec<f64>)> =
channels.iter().map(|&ch| (ch, by_ch.remove(&ch).unwrap_or_default())).collect();
let t_max = report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(1.0_f64, f64::max);
let raster_opts = SvgChartOptions {
width: w,
height: half,
title: "Spike raster".into(),
xlabel: "Time (ms)".into(),
ylabel: "Channel".into(),
..Default::default()
};
let raster_svg = render_raster_svg(&rows, &raster_opts, 0.0, t_max);
let body = format!(
r##"<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">
<title>ASDR + Raster</title>
<svg x="0" y="0" width="{w}" height="{half}">{inner_asdr}</svg>
<svg x="0" y="{half}" width="{w}" height="{half}">{inner_raster}</svg>
</svg>
"##,
inner_asdr = strip_outer_svg(&asdr_svg),
inner_raster = strip_outer_svg(&raster_svg),
);
write_svg_file(path, &body)
}
pub(crate) fn strip_outer_svg(doc: &str) -> String {
let trimmed = doc.trim();
let start = trimmed.find('>').map(|i| i + 1).unwrap_or(0);
let end = trimmed.rfind("</svg>").unwrap_or(trimmed.len());
trimmed[start..end].to_string()
}
pub(crate) fn write_named_line_snapshots_sized(
series: &[(f64, f64)],
dir: &Path,
stem: &str,
suffix: &str,
title: &str,
xlab: &str,
ylab: &str,
color: &str,
w: u32,
h: u32,
formats: &[&str],
) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
if formats.contains(&"svg") {
let p = dir.join(format!("{stem}_{suffix}.svg"));
write_line_svg(series, &p, w, h, color, title, xlab, ylab)?;
out.push(p);
}
if formats.contains(&"eps") {
let p = dir.join(format!("{stem}_{suffix}.eps"));
write_line_eps(series, &p, w, h, title, xlab, ylab)?;
out.push(p);
}
if formats.contains(&"bmp") {
let p = dir.join(format!("{stem}_{suffix}.bmp"));
write_line_bmp(series, &p, w, h.saturating_sub(40).max(120))?;
out.push(p);
}
if formats.contains(&"png") {
let p = dir.join(format!("{stem}_{suffix}.png"));
write_line_png(series, &p, w, h.saturating_sub(40).max(120))?;
out.push(p);
}
Ok(out)
}
#[cfg(feature = "correlation")]
pub(crate) fn write_synchrony_bar_svg(
rows: &[crate::analysis::ChannelSynchrony],
path: &Path,
w: u32,
h: u32,
) -> Result<()> {
use crate::svg::{write_bar_svg, SvgChartOptions};
let bars: Vec<(String, f64)> = rows
.iter()
.take(64)
.map(|r| (format!("{}-{}", r.channel_a + 1, r.channel_b + 1), r.synchrony_index))
.collect();
let opts = SvgChartOptions {
width: w,
height: h,
title: "Synchrony index".into(),
xlabel: "Channel pair".into(),
ylabel: "Index".into(),
margin_bottom: 56.0,
..Default::default()
};
write_bar_svg(&bars, &opts, path)
}
#[cfg(feature = "correlation")]
pub(crate) fn write_synchrony_bar_png(
rows: &[crate::analysis::ChannelSynchrony],
path: &Path,
w: u32,
h: u32,
) -> Result<()> {
let n = rows.len().max(1);
let bar_w = (w as f64 - 20.0) / n as f64;
let max_y = rows.iter().map(|r| r.synchrony_index).fold(1e-9_f64, f64::max);
let mut pixels = vec![248u8; (w * h * 3) as usize];
for (i, row) in rows.iter().enumerate().take(64) {
let bh = ((row.synchrony_index / max_y) * (h as f64 - 10.0)).round() as i32;
let x0 = (10.0 + i as f64 * bar_w).round() as i32;
let x1 = (x0 as f64 + bar_w * 0.8).round() as i32;
let y1 = h as i32 - 5;
let y0 = (y1 - bh).max(0);
for y in y0..y1 {
for x in x0..x1 {
if x >= 0 && y >= 0 && (x as u32) < w && (y as u32) < h {
let idx = ((y as u32 * w + x as u32) * 3) as usize;
pixels[idx] = 0xb2;
pixels[idx + 1] = 0x91;
pixels[idx + 2] = 0x08;
}
}
}
}
write_png24(path, w, h, &pixels)
}
pub(crate) fn write_named_line_snapshots(
series: &[(f64, f64)],
dir: &Path,
stem: &str,
suffix: &str,
title: &str,
xlabel: &str,
ylabel: &str,
color: &str,
) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
let svg = dir.join(format!("{stem}_{suffix}.svg"));
write_line_svg(series, &svg, 800, 280, color, title, xlabel, ylabel)?;
out.push(svg);
let eps = dir.join(format!("{stem}_{suffix}.eps"));
write_line_eps(series, &eps, 800, 280, title, xlabel, ylabel)?;
out.push(eps);
let bmp = dir.join(format!("{stem}_{suffix}.bmp"));
write_line_bmp(series, &bmp, 800, 240)?;
out.push(bmp);
let png = dir.join(format!("{stem}_{suffix}.png"));
write_line_png(series, &png, 800, 240)?;
out.push(png);
Ok(out)
}
pub(crate) fn aggregate_frequency_series(report: &AnalysisReport) -> Vec<(f64, f64)> {
use std::collections::BTreeMap;
let mut by_t: BTreeMap<i64, (f64, usize)> = BTreeMap::new();
for bin in &report.frequency_bins {
let key = (bin.start_ms * 10.0).round() as i64;
let e = by_t.entry(key).or_insert((0.0, 0));
e.0 += bin.rate_hz;
e.1 += 1;
}
by_t.into_iter()
.map(|(k, (sum, n))| (k as f64 / 10.0, if n > 0 { sum / n as f64 } else { 0.0 }))
.collect()
}
pub(crate) fn channels64_traces(report: &AnalysisReport) -> Vec<(usize, Vec<(f64, f64)>)> {
let interval = report.header.interval_ms().max(1e-9);
let mut traces: Vec<(usize, Vec<(f64, f64)>)> = Vec::new();
if !report.filtered_by_channel.is_empty() {
for (&ch, samples) in &report.filtered_by_channel {
let step = (samples.len() / 200).max(1);
let series: Vec<(f64, f64)> = samples
.iter()
.enumerate()
.step_by(step)
.map(|(i, &mv)| (i as f64 * interval, mv))
.collect();
traces.push((ch, series));
}
} else {
use std::collections::BTreeMap;
let mut by_ch: BTreeMap<usize, Vec<(f64, f64)>> = BTreeMap::new();
for s in &report.filtered_preview {
by_ch.entry(s.channel).or_default().push((s.time_ms, s.millivolts));
}
traces = by_ch.into_iter().collect();
}
traces.sort_by_key(|(ch, _)| *ch);
traces
}
pub(crate) fn write_channels64_svg(
report: &AnalysisReport,
path: &Path,
w: u32,
h: u32,
) -> Result<()> {
use crate::svg::{downsample_lttb, escape_xml, write_svg_file, SvgChartOptions};
let traces = channels64_traces(report);
let cols = 8usize;
let rows = 8usize;
let cell_w = w as f64 / cols as f64;
let cell_h = h as f64 / rows as f64;
let title = escape_xml("64-channel filtered waveforms");
let mut body = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">
<rect width="100%" height="100%" fill="#f8fafc"/>
<text x="{cx:.1}" y="18" text-anchor="middle" font-family="Helvetica Neue,Helvetica,Arial,sans-serif" font-size="14" fill="#0f172a">{title}</text>
"##,
cx = w as f64 / 2.0
);
let max_pts = SvgChartOptions::default().max_points.unwrap_or(400);
for (ch, series) in &traces {
let row = ch / cols;
let col = ch % cols;
if row >= rows {
continue;
}
let ox = col as f64 * cell_w + 4.0;
let oy = row as f64 * cell_h + 22.0;
let pw = cell_w - 8.0;
let ph = cell_h - 28.0;
body.push_str(&format!(
r##" <rect x="{ox:.1}" y="{oy:.1}" width="{pw:.1}" height="{ph:.1}" fill="#fff" stroke="#e2e8f0"/>
<text x="{lx:.1}" y="{ly:.1}" font-family="Helvetica Neue,Helvetica,Arial,sans-serif" font-size="9" fill="#64748b">Ch{ch}</text>
"##,
lx = ox + 2.0,
ly = oy - 2.0,
ch = ch + 1
));
if series.len() < 2 {
continue;
}
let series = downsample_lttb(series, max_pts.clamp(32, 200));
let min_x = series[0].0;
let max_x = series.last().map(|s| s.0).unwrap_or(1.0).max(min_x + 1.0);
let min_y = series.iter().map(|(_, y)| *y).fold(f64::INFINITY, f64::min);
let max_y = series.iter().map(|(_, y)| *y).fold(f64::NEG_INFINITY, f64::max);
let span_y = (max_y - min_y).abs().max(1e-9);
let mut d = String::new();
for (i, &(x, y)) in series.iter().enumerate() {
let px = ox + (x - min_x) / (max_x - min_x) * pw;
let py = oy + ph - (y - min_y) / span_y * ph;
if i == 0 {
d.push_str(&format!("M{px:.1} {py:.1}"));
} else {
d.push_str(&format!("L{px:.1} {py:.1}"));
}
}
body.push_str(&format!(
r##" <path d="{d}" fill="none" stroke="#2563eb" stroke-width="1"/>
"##
));
}
body.push_str("</svg>");
write_svg_file(path, &body)
}
pub(crate) fn write_channels64_png(
report: &AnalysisReport,
path: &Path,
w: u32,
h: u32,
) -> Result<()> {
let traces = channels64_traces(report);
let cols = 8usize;
let rows = 8usize;
let cell_w = w as f64 / cols as f64;
let cell_h = h as f64 / rows as f64;
let mut pixels = vec![248u8; (w * h * 3) as usize];
for (ch, series) in &traces {
let row = ch / cols;
let col = ch % cols;
if row >= rows || series.len() < 2 {
continue;
}
let ox = col as f64 * cell_w + 4.0;
let oy = row as f64 * cell_h + 4.0;
let pw = cell_w - 8.0;
let ph = cell_h - 8.0;
let min_x = series[0].0;
let max_x = series.last().map(|s| s.0).unwrap_or(1.0).max(min_x + 1.0);
let min_y = series.iter().map(|(_, y)| *y).fold(f64::INFINITY, f64::min);
let max_y = series.iter().map(|(_, y)| *y).fold(f64::NEG_INFINITY, f64::max);
let span_y = (max_y - min_y).abs().max(1e-9);
let to_px = |x: f64, y: f64| -> (i32, i32) {
let px = (ox + (x - min_x) / (max_x - min_x) * pw).round() as i32;
let py = (oy + ph - (y - min_y) / span_y * ph).round() as i32;
(px, py)
};
for win in series.windows(2) {
let (x0, y0) = to_px(win[0].0, win[0].1);
let (x1, y1) = to_px(win[1].0, win[1].1);
draw_line_bgr(&mut pixels, w, h, x0, y0, x1, y1, [0xeb, 0x63, 0x25]);
}
}
write_png24(path, w, h, &pixels)
}
pub(crate) fn series_bounds(series: &[(f64, f64)]) -> (f64, f64, f64) {
let min_x = series.iter().map(|(x, _)| *x).fold(f64::INFINITY, f64::min);
let max_x = series.iter().map(|(x, _)| *x).fold(f64::NEG_INFINITY, f64::max);
let max_y = series.iter().map(|(_, y)| *y).fold(1.0_f64, f64::max).max(1e-9);
let min_x = if min_x.is_finite() { min_x } else { 0.0 };
let max_x = if max_x.is_finite() { max_x } else { 1.0 };
(min_x, max_x, max_y)
}
pub(crate) fn write_line_svg(
series: &[(f64, f64)],
path: &Path,
w: u32,
h: u32,
color: &str,
title: &str,
xlabel: &str,
ylabel: &str,
) -> Result<()> {
use crate::svg::{write_line_svg as write_chart, SvgChartOptions, SvgSeries};
let opts = SvgChartOptions {
width: w,
height: h,
title: title.into(),
xlabel: xlabel.into(),
ylabel: ylabel.into(),
..Default::default()
};
write_chart(
&[SvgSeries {
label: title.into(),
points: series.to_vec(),
color: color.into(),
fill: false,
}],
&opts,
path,
)
}
pub(crate) fn write_line_eps(
series: &[(f64, f64)],
path: &Path,
w: u32,
h: u32,
title: &str,
xlabel: &str,
ylabel: &str,
) -> Result<()> {
let (min_x, max_x, max_y) = series_bounds(series);
let span_x = (max_x - min_x).abs().max(1.0);
let left = 56.0;
let right = 16.0;
let top = 36.0;
let bottom = 40.0;
let pw = w as f64 - left - right;
let ph = h as f64 - top - bottom;
let mut body = String::new();
body.push_str("%!PS-Adobe-3.0 EPSF-3.0\n");
body.push_str(&format!("%%BoundingBox: 0 0 {w} {h}\n"));
body.push_str("%%Title: ");
body.push_str(title);
body.push('\n');
body.push_str("/Helvetica findfont 14 scalefont setfont\n");
body.push_str(&format!(
"{} {} moveto ({}) dup stringwidth pop 2 div neg 0 rmoveto show\n",
w as f64 / 2.0,
h as f64 - 22.0,
title.replace('(', "[").replace(')', "]")
));
body.push_str("0.4 0.45 0.53 setrgbcolor\n1.2 setlinewidth\n");
body.push_str(&format!(
"{left} {} moveto {left} {} lineto {} {} lineto stroke\n",
h as f64 - top - ph,
h as f64 - top,
left + pw,
h as f64 - top - ph
));
body.push_str("0.15 0.39 0.92 setrgbcolor\n1.5 setlinewidth\n");
if let Some(&(x0, y0)) = series.first() {
let px = left + (x0 - min_x) / span_x * pw;
let py = h as f64 - top - (y0 / max_y * ph);
body.push_str(&format!("{px:.2} {py:.2} moveto\n"));
for &(x, y) in series.iter().skip(1) {
let px = left + (x - min_x) / span_x * pw;
let py = h as f64 - top - (y / max_y * ph);
body.push_str(&format!("{px:.2} {py:.2} lineto\n"));
}
body.push_str("stroke\n");
}
body.push_str("/Helvetica findfont 11 scalefont setfont\n0.2 0.25 0.33 setrgbcolor\n");
body.push_str(&format!(
"{} 12 moveto ({}) dup stringwidth pop 2 div neg 0 rmoveto show\n",
w as f64 / 2.0,
xlabel.replace('(', "[").replace(')', "]")
));
body.push_str(&format!(
"gsave 14 {} translate -90 rotate 0 0 moveto ({}) show grestore\n",
h as f64 / 2.0,
ylabel.replace('(', "[").replace(')', "]")
));
body.push_str("showpage\n");
let _ = (right, bottom);
std::fs::write(path, body)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub(crate) fn raster_channels(report: &AnalysisReport) -> Vec<usize> {
let mut chs: Vec<usize> = report.spikes.spikes.iter().map(|s| s.channel).collect();
chs.sort_unstable();
chs.dedup();
if chs.is_empty() {
chs = report.header.active_channel_indices();
}
chs
}
pub(crate) fn write_raster_svg(report: &AnalysisReport, path: &Path, w: u32, h: u32) -> Result<()> {
use crate::svg::{write_raster_svg as write_chart, SvgChartOptions};
let channels = raster_channels(report);
let mut by_ch: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
for spike in &report.spikes.spikes {
by_ch.entry(spike.channel).or_default().push(spike.within_trace_time_ms);
}
let rows: Vec<(usize, Vec<f64>)> =
channels.iter().map(|&ch| (ch, by_ch.remove(&ch).unwrap_or_default())).collect();
let max_t = report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(1.0_f64, f64::max);
let opts = SvgChartOptions {
width: w,
height: h,
title: "Spike raster".into(),
xlabel: "Time (ms)".into(),
ylabel: "Channel".into(),
..Default::default()
};
write_chart(&rows, &opts, 0.0, max_t, path)
}
pub(crate) fn write_raster_eps(report: &AnalysisReport, path: &Path, w: u32, h: u32) -> Result<()> {
let channels = raster_channels(report);
let max_t = report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(1.0_f64, f64::max);
let left = 48.0;
let top = 28.0;
let bottom = 28.0;
let right = 12.0;
let pw = w as f64 - left - right;
let ph = h as f64 - top - bottom;
let n = channels.len().max(1) as f64;
let mut body = String::new();
body.push_str("%!PS-Adobe-3.0 EPSF-3.0\n");
body.push_str(&format!("%%BoundingBox: 0 0 {w} {h}\n"));
body.push_str("%%Title: Spike raster\n");
body.push_str("0.1 0.1 0.14 setrgbcolor\n0.8 setlinewidth\n");
for spike in &report.spikes.spikes {
let Some(row) = channels.iter().position(|&c| c == spike.channel) else {
continue;
};
let x = left + (spike.within_trace_time_ms / max_t) * pw;
let y = h as f64 - top - (row as f64 + 0.5) / n * ph;
body.push_str(&format!(
"{x:.2} {y0:.2} moveto {x:.2} {y1:.2} lineto stroke\n",
y0 = y - 3.0,
y1 = y + 3.0
));
}
let _ = (bottom, right);
body.push_str("showpage\n");
std::fs::write(path, body)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub(crate) fn write_raster_bmp(report: &AnalysisReport, path: &Path, w: u32, h: u32) -> Result<()> {
let channels = raster_channels(report);
let max_t = report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(1.0_f64, f64::max);
let mut pixels = vec![255u8; (w * h * 3) as usize];
let n = channels.len().max(1) as f64;
for spike in &report.spikes.spikes {
let Some(row) = channels.iter().position(|&c| c == spike.channel) else {
continue;
};
let x = ((spike.within_trace_time_ms / max_t) * (w as f64 - 1.0)).round() as i32;
let y = (((row as f64 + 0.5) / n) * (h as f64 - 1.0)).round() as i32;
for dy in -2..=2 {
let yy = y + dy;
if x >= 0 && x < w as i32 && yy >= 0 && yy < h as i32 {
let idx = ((yy as u32 * w + x as u32) * 3) as usize;
pixels[idx] = 0x0f;
pixels[idx + 1] = 0x17;
pixels[idx + 2] = 0x2a;
}
}
}
write_bmp24(path, w, h, &pixels)
}
pub(crate) fn write_png24(path: &Path, w: u32, h: u32, bgr: &[u8]) -> Result<()> {
crate::png::write_bgr_png(path, w, h, bgr)
}
pub(crate) fn write_raster_png(report: &AnalysisReport, path: &Path, w: u32, h: u32) -> Result<()> {
write_png24(path, w, h, &raster_chart_pixels(report, w, h))
}
pub(crate) fn raster_chart_pixels(report: &AnalysisReport, w: u32, h: u32) -> Vec<u8> {
let channels = raster_channels(report);
let max_t = report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(1.0_f64, f64::max);
let mut pixels = vec![255u8; (w * h * 3) as usize];
let n = channels.len().max(1) as f64;
for spike in &report.spikes.spikes {
let Some(row) = channels.iter().position(|&c| c == spike.channel) else {
continue;
};
let x = ((spike.within_trace_time_ms / max_t) * (w as f64 - 1.0)).round() as i32;
let y = (((row as f64 + 0.5) / n) * (h as f64 - 1.0)).round() as i32;
for dy in -2..=2 {
let yy = y + dy;
if x >= 0 && x < w as i32 && yy >= 0 && yy < h as i32 {
let idx = ((yy as u32 * w + x as u32) * 3) as usize;
pixels[idx] = 0x0f;
pixels[idx + 1] = 0x17;
pixels[idx + 2] = 0x2a;
}
}
}
pixels
}
pub(crate) fn write_line_bmp(series: &[(f64, f64)], path: &Path, w: u32, h: u32) -> Result<()> {
write_bmp24(path, w, h, &line_chart_pixels(series, w, h))
}
pub(crate) fn write_line_png(series: &[(f64, f64)], path: &Path, w: u32, h: u32) -> Result<()> {
write_png24(path, w, h, &line_chart_pixels(series, w, h))
}
pub(crate) fn line_chart_pixels_public(series: &[(f64, f64)], w: u32, h: u32) -> Vec<u8> {
line_chart_pixels(series, w, h)
}
pub(crate) fn line_chart_pixels(series: &[(f64, f64)], w: u32, h: u32) -> Vec<u8> {
let mut pixels = vec![255u8; (w * h * 3) as usize]; if series.len() >= 2 {
let min_x = series.iter().map(|(x, _)| *x).fold(f64::INFINITY, f64::min);
let max_x = series.iter().map(|(x, _)| *x).fold(f64::NEG_INFINITY, f64::max);
let max_y = series.iter().map(|(_, y)| *y).fold(1.0_f64, f64::max).max(1e-9);
let span_x = (max_x - min_x).abs().max(1.0);
let to_px = |x: f64, y: f64| -> (i32, i32) {
let px = ((x - min_x) / span_x * (w as f64 - 1.0)).round() as i32;
let py = (h as f64 - 1.0 - (y / max_y * (h as f64 - 1.0))).round() as i32;
(px, py)
};
for win in series.windows(2) {
let (x0, y0) = to_px(win[0].0, win[0].1);
let (x1, y1) = to_px(win[1].0, win[1].1);
draw_line_bgr(&mut pixels, w, h, x0, y0, x1, y1, [0xeb, 0x63, 0x25]);
}
}
pixels
}
pub(crate) fn draw_line_bgr(
pixels: &mut [u8],
w: u32,
h: u32,
mut x0: i32,
mut y0: i32,
x1: i32,
y1: i32,
bgr: [u8; 3],
) {
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
if x0 >= 0 && y0 >= 0 && (x0 as u32) < w && (y0 as u32) < h {
let i = ((y0 as u32 * w + x0 as u32) * 3) as usize;
pixels[i] = bgr[0];
pixels[i + 1] = bgr[1];
pixels[i + 2] = bgr[2];
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
err += dy;
x0 += sx;
}
if e2 <= dx {
err += dx;
y0 += sy;
}
}
}
pub(crate) fn write_bmp24(path: &Path, w: u32, h: u32, bgr: &[u8]) -> Result<()> {
let row_stride = (w * 3).div_ceil(4) * 4;
let pixel_size = row_stride * h;
let file_size = 54 + pixel_size;
let mut buf = Vec::with_capacity(file_size as usize);
buf.extend_from_slice(b"BM");
buf.extend_from_slice(&file_size.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
buf.extend_from_slice(&54u32.to_le_bytes());
buf.extend_from_slice(&40u32.to_le_bytes());
buf.extend_from_slice(&(w as i32).to_le_bytes());
buf.extend_from_slice(&(h as i32).to_le_bytes()); buf.extend_from_slice(&1u16.to_le_bytes());
buf.extend_from_slice(&24u16.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
buf.extend_from_slice(&pixel_size.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
buf.extend_from_slice(&0u32.to_le_bytes());
let pad = vec![0u8; (row_stride - w * 3) as usize];
for row in (0..h).rev() {
let start = (row * w * 3) as usize;
let end = start + (w * 3) as usize;
buf.extend_from_slice(&bgr[start..end]);
buf.extend_from_slice(&pad);
}
std::fs::write(path, buf)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
#[cfg(test)]
mod png_tests {
use super::*;
#[test]
fn png24_has_signature_and_ihdr() {
let dir = std::env::temp_dir().join(format!("med64-png-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("tiny.png");
let pixels = vec![0u8, 0, 255, 0, 255, 0, 255, 0, 0, 0, 0, 0];
write_png24(&path, 2, 2, &pixels).unwrap();
let bytes = std::fs::read(&path).unwrap();
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
assert!(bytes.windows(4).any(|w| w == b"IHDR"));
let _ = std::fs::remove_file(&path);
}
}