med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! Minimal 24-bit PNG writer (filter None + zlib stored deflate).

use std::path::Path;

use crate::error::{Med64Error, Result};

/// Write a top-down BGR image as an RGB PNG.
pub fn write_bgr_png(path: impl AsRef<Path>, w: u32, h: u32, bgr: &[u8]) -> Result<()> {
    let mut rgb = vec![0u8; bgr.len()];
    for chunk in bgr.chunks_exact(3).zip(rgb.chunks_exact_mut(3)) {
        let (src, dst) = chunk;
        dst[0] = src[2];
        dst[1] = src[1];
        dst[2] = src[0];
    }
    write_rgb_png(path, w, h, &rgb)
}

/// Write a top-down packed RGB PNG (`w * h * 3` bytes).
pub fn write_rgb_png(path: impl AsRef<Path>, w: u32, h: u32, rgb: &[u8]) -> Result<()> {
    let path = path.as_ref();
    let mut raw = Vec::with_capacity(((w * 3 + 1) * h) as usize);
    for row in 0..h {
        raw.push(0);
        let start = (row * w * 3) as usize;
        raw.extend_from_slice(&rgb[start..start + (w * 3) as usize]);
    }
    let mut ihdr = Vec::with_capacity(13);
    ihdr.extend_from_slice(&w.to_be_bytes());
    ihdr.extend_from_slice(&h.to_be_bytes());
    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
    let mut buf = Vec::from(&b"\x89PNG\r\n\x1a\n"[..]);
    png_chunk(&mut buf, b"IHDR", &ihdr);
    png_chunk(&mut buf, b"IDAT", &zlib_store(&raw));
    png_chunk(&mut buf, b"IEND", &[]);
    std::fs::write(path, buf)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Heatmap PNG: `values` length `rows * cols`, mapped blue→red.
pub fn write_heatmap_png(
    path: impl AsRef<Path>,
    cols: u32,
    rows: u32,
    values: &[f64],
    cell_px: u32,
) -> Result<()> {
    let cell = cell_px.max(1);
    let w = cols * cell;
    let h = rows * cell;
    let min = values.iter().copied().fold(f64::INFINITY, f64::min);
    let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let span = (max - min).abs().max(1e-12);
    let mut rgb = vec![240u8; (w * h * 3) as usize];
    for r in 0..rows {
        for c in 0..cols {
            let idx = (r * cols + c) as usize;
            let t =
                if idx < values.len() { ((values[idx] - min) / span).clamp(0.0, 1.0) } else { 0.0 };
            let color =
                [(255.0 * t) as u8, (40.0 + 80.0 * (1.0 - t)) as u8, (255.0 * (1.0 - t)) as u8];
            for dy in 0..cell {
                for dx in 0..cell {
                    let x = c * cell + dx;
                    let y = r * cell + dy;
                    let p = ((y * w + x) * 3) as usize;
                    rgb[p] = color[0];
                    rgb[p + 1] = color[1];
                    rgb[p + 2] = color[2];
                }
            }
        }
    }
    write_rgb_png(path, w, h, &rgb)
}

fn png_chunk(out: &mut Vec<u8>, ty: &[u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(ty);
    out.extend_from_slice(data);
    let mut crc_src = Vec::with_capacity(4 + data.len());
    crc_src.extend_from_slice(ty);
    crc_src.extend_from_slice(data);
    out.extend_from_slice(&png_crc32(&crc_src).to_be_bytes());
}

fn zlib_store(raw: &[u8]) -> Vec<u8> {
    let mut out = vec![0x78, 0x01];
    if raw.is_empty() {
        out.push(1);
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0xffffu16.to_le_bytes());
    } else {
        let mut i = 0;
        while i < raw.len() {
            let len = (raw.len() - i).min(65535);
            let last = i + len == raw.len();
            out.push(u8::from(last));
            let n = len as u16;
            out.extend_from_slice(&n.to_le_bytes());
            out.extend_from_slice(&(!n).to_le_bytes());
            out.extend_from_slice(&raw[i..i + len]);
            i += len;
        }
    }
    out.extend_from_slice(&adler32(raw).to_be_bytes());
    out
}

fn png_crc32(data: &[u8]) -> u32 {
    let mut crc = 0xffff_ffffu32;
    for &b in data {
        crc ^= u32::from(b);
        for _ in 0..8 {
            crc = if crc & 1 != 0 { (crc >> 1) ^ 0xedb8_8320 } else { crc >> 1 };
        }
    }
    !crc
}

fn adler32(data: &[u8]) -> u32 {
    let mut a = 1u32;
    let mut b = 0u32;
    for &byte in data {
        a = (a + u32::from(byte)) % 65521;
        b = (b + a) % 65521;
    }
    (b << 16) | a
}