// SPDX-License-Identifier: MIT //! Output for people: a labelled palette, PNG frames and WAV audio (frontend side). //! //! The board produces colour-register values (hue << 4 | luma), never RGB //! (docs/start-here.md "Output"). Colours differ per console and per television //! ([AHRM] 6.3 "A word on colors"), so a palette is a frontend choice and says //! where it comes from. //! //! A transcription of a5200-python's `media.py` (at cf82d44). Rust-forced differences: //! Python's `round` (ties to even) is `round_ties_even`; the PNG's pixel data is compressed //! by flate2 at level 6 (Python's zlib: the image is the same, the compressed bytes may not //! be); `AudioTap` cannot hold the board, so `poll` is handed the POKEY and GTIA's CONSOL //! lines it reads, and the tap takes the cycle rate at construction; `samples` holds the //! little-endian 16-bit samples as bytes, as Python's bytearray does. use std::io::Write; use std::path::Path; use flate2::write::ZlibEncoder; use flate2::Compression; use pokey::POKEY; /// A computed NTSC palette, labelled: YIQ with hue 1 at the colour burst's /// "gold" phase and 24 degree steps per hue, luma in 16 equal steps, hue 0 grey /// ([AHRM] 6.3 describes the encoding; the numbers here are a choice, not a /// measurement). HYPOTHESIS for every number (33-degree offset, 24-degree /// step, saturation 0.22, linear luma): a frontend palette, outside the /// specification; a capture of a console's composite output would replace it. pub fn ntsc_palette() -> Vec<[u8; 3]> { let mut colours = Vec::with_capacity(256); for value in 0..256u32 { let (hue, luma) = (value >> 4, value & 0x0F); let y = luma as f64 / 15.0; let (i, q); if hue == 0 { i = 0.0; q = 0.0; } else { let angle = (180.0 - 24.0 * (hue as f64 - 1.0) + 33.0).to_radians(); let sat = 0.22; i = sat * angle.cos(); q = sat * angle.sin(); } let r = y + 0.956 * i + 0.621 * q; let g = y - 0.272 * i - 0.647 * q; let b = y - 1.106 * i + 1.703 * q; let channel = |c: f64| (c * 255.0).round_ties_even().clamp(0.0, 255.0) as u8; colours.push([channel(r), channel(g), channel(b)]); } colours } pub const PALETTE_LABEL: &str = "computed NTSC YIQ, 24-degree hue steps (a frontend choice; see media.rs)"; /// Write a frame of colour-register values as an RGB PNG (pixels doubled vertically). pub fn write_png( path: &Path, frame: &[u8], width: usize, height: usize, palette: Option<&[[u8; 3]]>, ) -> std::io::Result<()> { std::fs::write(path, png_bytes(frame, width, height, palette)) } /// The PNG `write_png` writes, as bytes. pub fn png_bytes( frame: &[u8], width: usize, height: usize, palette: Option<&[[u8; 3]]>, ) -> Vec { let computed; let palette = match palette { Some(p) => p, None => { computed = ntsc_palette(); &computed } }; let mut rows = Vec::with_capacity(height * 2 * (width * 3 + 1)); for y in 0..height { let mut line = Vec::with_capacity(width * 3); for &v in &frame[y * width..(y + 1) * width] { line.extend_from_slice(&palette[v as usize]); } rows.push(0); rows.extend_from_slice(&line); rows.push(0); rows.extend_from_slice(&line); } fn chunk(kind: &[u8], data: &[u8]) -> Vec { let mut out = (data.len() as u32).to_be_bytes().to_vec(); out.extend_from_slice(kind); out.extend_from_slice(data); let mut crc = crc32fast::Hasher::new(); crc.update(kind); crc.update(data); out.extend_from_slice(&crc.finalize().to_be_bytes()); out } let mut header = Vec::new(); header.extend_from_slice(&(width as u32).to_be_bytes()); header.extend_from_slice(&((height * 2) as u32).to_be_bytes()); header.extend_from_slice(&[8, 2, 0, 0, 0]); let mut encoder = ZlibEncoder::new(Vec::new(), Compression::new(6)); encoder.write_all(&rows).unwrap(); let compressed = encoder.finish().unwrap(); let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); png.extend(chunk(b"IHDR", &header)); png.extend(chunk(b"IDAT", &compressed)); png.extend(chunk(b"IEND", b"")); png } /// Samples POKEY's mix and GTIA's speaker bit (CONSOL bit 3) into 16-bit mono. /// /// pokey-python's `mix()` is a labelled fit of the chip's output curve; the /// speaker bit is added as a fixed step ([BUCH]: CONSOL bit 3 is the speaker). /// The level is read every `step` machine cycles and averaged over each /// output sample: a box filter, not a model of the console's audio circuit. /// /// HYPOTHESIS: the 0.8 / 0.2 weights of POKEY and the speaker (a scope /// capture of the console's audio output with each source alone would set /// them); the speaker bit itself is DOC ([BUCH]). Gameplay envelopes against /// Atari800 (OBSERVED): r = 0.73-0.92 on pokey-python 6ed1ffa (validation.md /// milestone 4). #[derive(Clone, Debug)] pub struct AudioTap { pub rate: u32, pub step: i64, pub per_sample: f64, pub samples: Vec, pub _acc: f64, pub _n: u64, pub _next: i64, pub _edge: f64, pub _since: f64, } impl AudioTap { /// `AudioTap(board, rate, step)`: `cycle_hz` is `board.machine.cycle_hz`. pub fn new(cycle_hz: f64, rate: u32, step: i64) -> Self { let per_sample = cycle_hz / rate as f64; AudioTap { rate, step, per_sample, samples: Vec::new(), _acc: 0.0, _n: 0, _next: 0, _edge: per_sample, _since: 0.0, } } /// Call once per machine cycle (the board does, when a tap is attached). pub fn poll(&mut self, pokey: &POKEY, consol_out: u8) { self._next -= 1; if self._next > 0 { return; } self._next = self.step; let mut level = pokey.mix() * 0.8; if consol_out & 8 != 0 { level += 0.2; } self._acc += level; self._n += 1; self._since += self.step as f64; if self._since >= self._edge { self._since -= self._edge; let value = if self._n != 0 { self._acc / self._n as f64 } else { 0.0 }; self._acc = 0.0; self._n = 0; // Silence (mix 0, speaker off) is sample 0; full scale is 1.0. let sample = ((value * 32767.0).trunc() as i64).clamp(-32768, 32767) as i16; self.samples.extend_from_slice(&sample.to_le_bytes()); } } pub fn write(&self, path: &Path) -> std::io::Result<()> { let data = &self.samples; let mut out = Vec::with_capacity(44 + data.len()); out.extend_from_slice(b"RIFF"); out.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); out.extend_from_slice(b"WAVEfmt "); out.extend_from_slice(&16u32.to_le_bytes()); out.extend_from_slice(&1u16.to_le_bytes()); // PCM out.extend_from_slice(&1u16.to_le_bytes()); // mono out.extend_from_slice(&self.rate.to_le_bytes()); out.extend_from_slice(&(self.rate * 2).to_le_bytes()); out.extend_from_slice(&2u16.to_le_bytes()); out.extend_from_slice(&16u16.to_le_bytes()); out.extend_from_slice(b"data"); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(data); std::fs::write(path, out) } }