Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(verify): video and audio marker codecs with robustness tests
Richie McIlroy097c819731a7
diff --git a/Cargo.lock b/Cargo.lockindex f059b7eff..62aee8779 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2150,6 +2150,30 @@ dependencies = ["zbus",]+[[package]]+name = "cap-verify"+version = "0.1.0"+dependencies = [+ "anyhow",+ "cap-editor",+ "cap-export",+ "cap-media-info",+ "cap-project",+ "cap-recording",+ "cap-rendering",+ "cap-timestamp",+ "ffmpeg-next",+ "flume",+ "futures",+ "relative-path",+ "rustfft",+ "serde",+ "serde_json",+ "tempfile",+ "tokio",+ "workspace-hack",+]+[[package]]name = "cap-video-decode"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 8a9be0ffb..ec6d96553 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -109,6 +109,11 @@ opt-level = 2[profile.dev.package.cap-audio]opt-level = 2+# The verification suite decodes markers from every output pixel it reads;+# unoptimised it spends minutes in its own loops.+[profile.dev.package.cap-verify]+opt-level = 3+# Optimize for smaller binary size[profile.release]panic = "unwind"diff --git a/crates/verify/Cargo.toml b/crates/verify/Cargo.tomlnew file mode 100644index 000000000..63bbd780a--- /dev/null+++ b/crates/verify/Cargo.toml@@ -0,0 +1,31 @@+[package]+name = "cap-verify"+version = "0.1.0"+edition = "2024"+publish = false++[lints]+workspace = true++[dependencies]+cap-media-info = { path = "../media-info" }+cap-project = { path = "../project" }+cap-recording = { path = "../recording" }+cap-timestamp = { path = "../timestamp" }++anyhow = { workspace = true }+ffmpeg = { workspace = true }+flume = { workspace = true }+futures = { workspace = true }+relative-path = "1.9.3"+rustfft = "6.4.1"+serde = { workspace = true }+serde_json = "1"+tokio = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+cap-editor = { path = "../editor" }+cap-export = { path = "../export" }+cap-rendering = { path = "../rendering" }+tempfile = "3"diff --git a/crates/verify/src/audio_code.rs b/crates/verify/src/audio_code.rsnew file mode 100644index 000000000..3a1aacc28--- /dev/null+++ b/crates/verify/src/audio_code.rs@@ -0,0 +1,427 @@+//! Audio markers.+//!+//! A marker is a 20 ms linear chirp (the sync symbol, located to a fraction+//! of a sample by cross-correlation) followed by 20 FSK bits of 5 ms each: a+//! 12-bit marker index and a CRC-8. Each source (microphone, system audio,+//! media track) has its own chirp direction/band and its own pair of bit+//! tones, so markers from different sources can be located independently in+//! a mix. The chirp start is the marker's reference position.++use rustfft::{FftPlanner, num_complex::Complex32};+use serde::{Deserialize, Serialize};++pub const CHIRP_SECS: f64 = 0.020;+pub const BIT_SECS: f64 = 0.005;+pub const INDEX_BITS: u32 = 12;+const CRC_BITS: u32 = 8;+const PAYLOAD_BITS: u32 = INDEX_BITS + CRC_BITS;+pub const MARKER_SECS: f64 = CHIRP_SECS + PAYLOAD_BITS as f64 * BIT_SECS;+pub const MAX_AUDIO_INDEX: u32 = (1 << INDEX_BITS) - 1;+pub const DEFAULT_AMPLITUDE: f32 = 0.3;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum AudioSource {+ Mic,+ System,+ Media,+}++struct SourceParams {+ chirp_from: f64,+ chirp_to: f64,+ bit_zero: f64,+ bit_one: f64,+}++impl AudioSource {+ pub const ALL: [AudioSource; 3] = [AudioSource::Mic, AudioSource::System, AudioSource::Media];++ fn params(self) -> SourceParams {+ match self {+ AudioSource::Mic => SourceParams {+ chirp_from: 600.0,+ chirp_to: 3600.0,+ bit_zero: 1000.0,+ bit_one: 1600.0,+ },+ AudioSource::System => SourceParams {+ chirp_from: 3600.0,+ chirp_to: 600.0,+ bit_zero: 2200.0,+ bit_one: 2800.0,+ },+ AudioSource::Media => SourceParams {+ chirp_from: 1200.0,+ chirp_to: 4800.0,+ bit_zero: 3400.0,+ bit_one: 4000.0,+ },+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ AudioSource::Mic => "mic",+ AudioSource::System => "system",+ AudioSource::Media => "media",+ }+ }++ /// Phase of this source's markers as a fraction of the schedule period,+ /// so sources recorded together never overlap.+ fn schedule_phase_secs(self) -> f64 {+ match self {+ AudioSource::Mic => 0.0,+ AudioSource::System => 1.0 / 3.0,+ AudioSource::Media => 2.0 / 3.0,+ }+ }+}++fn crc8(value: u32) -> u8 {+ let mut crc: u8 = 0;+ for byte in value.to_le_bytes().iter().take(2) {+ crc ^= byte;+ for _ in 0..8 {+ crc = if crc & 0x80 != 0 {+ (crc << 1) ^ 0x07+ } else {+ crc << 1+ };+ }+ }+ crc+}++fn payload_bits(index: u32) -> u32 {+ index | (u32::from(crc8(index)) << INDEX_BITS)+}++fn hann(i: usize, n: usize) -> f64 {+ if n <= 1 {+ return 1.0;+ }+ 0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / (n - 1) as f64).cos()+}++/// Short raised-cosine fade at both ends of a symbol to avoid clicks.+fn edge_taper(i: usize, n: usize, ramp: usize) -> f64 {+ let ramp = ramp.min(n / 2).max(1);+ if i < ramp {+ 0.5 - 0.5 * (std::f64::consts::PI * i as f64 / ramp as f64).cos()+ } else if i >= n - ramp {+ let k = n - 1 - i;+ 0.5 - 0.5 * (std::f64::consts::PI * k as f64 / ramp as f64).cos()+ } else {+ 1.0+ }+}++fn chirp(source: AudioSource, sample_rate: u32) -> Vec<f32> {+ let p = source.params();+ let n = (CHIRP_SECS * f64::from(sample_rate)).round() as usize;+ let rate = f64::from(sample_rate);+ let k = (p.chirp_to - p.chirp_from) / CHIRP_SECS;+ let ramp = (0.002 * rate) as usize;+ (0..n)+ .map(|i| {+ let t = i as f64 / rate;+ let phase = 2.0 * std::f64::consts::PI * (p.chirp_from * t + 0.5 * k * t * t);+ (phase.sin() * edge_taper(i, n, ramp)) as f32+ })+ .collect()+}++/// Marker waveform at unit amplitude, starting with the chirp.+pub fn marker_waveform(source: AudioSource, index: u32, sample_rate: u32) -> Vec<f32> {+ assert!(+ index <= MAX_AUDIO_INDEX,+ "audio marker index {index} too large"+ );+ let p = source.params();+ let rate = f64::from(sample_rate);+ let mut out = chirp(source, sample_rate);+ let bits = payload_bits(index);+ let chirp_len = out.len();+ let ramp = (0.0008 * rate) as usize;+ for bit in 0..PAYLOAD_BITS {+ let start = chirp_len + (f64::from(bit) * BIT_SECS * rate).round() as usize;+ let end = chirp_len + (f64::from(bit + 1) * BIT_SECS * rate).round() as usize;+ let freq = if bits >> bit & 1 == 1 {+ p.bit_one+ } else {+ p.bit_zero+ };+ out.resize(end, 0.0);+ let n = end - start;+ for (i, sample) in out[start..end].iter_mut().enumerate() {+ let t = (start + i) as f64 / rate;+ *sample =+ ((2.0 * std::f64::consts::PI * freq * t).sin() * edge_taper(i, n, ramp)) as f32;+ }+ }+ out+}++#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct MarkerPlacement {+ pub index: u32,+ /// Chirp start, in seconds from the start of the source track.+ pub time_secs: f64,+}++/// Deterministic marker schedule: one marker per `period_secs`, offset by a+/// per-source phase and a small per-index jitter so a whole-period shift can+/// never alias to a zero error.+pub fn standard_schedule(+ source: AudioSource,+ start_secs: f64,+ duration_secs: f64,+ period_secs: f64,+) -> Vec<MarkerPlacement> {+ let mut out = Vec::new();+ let mut index = 0u32;+ loop {+ let jitter = (u64::from(index).wrapping_mul(2_654_435_761) % 97) as f64 / 97.0+ * (period_secs / 3.0 - MARKER_SECS).max(0.0);+ let t = start_secs+ + source.schedule_phase_secs() * period_secs+ + f64::from(index) * period_secs+ + jitter;+ if t + MARKER_SECS > start_secs + duration_secs || index > MAX_AUDIO_INDEX {+ break;+ }+ out.push(MarkerPlacement {+ index,+ time_secs: t,+ });+ index += 1;+ }+ out+}++/// Mixes markers into `out` (mono) at `amplitude`. Placement times are in+/// seconds from sample 0 of `out`.+pub fn render_markers(+ out: &mut [f32],+ sample_rate: u32,+ source: AudioSource,+ placements: &[MarkerPlacement],+ amplitude: f32,+) {+ for placement in placements {+ let start = (placement.time_secs * f64::from(sample_rate)).round() as isize;+ let wave = marker_waveform(source, placement.index, sample_rate);+ for (i, v) in wave.iter().enumerate() {+ let at = start + i as isize;+ if at >= 0+ && let Some(sample) = out.get_mut(at as usize)+ {+ *sample += v * amplitude;+ }+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct LocatedMarker {+ pub source: AudioSource,+ /// `None` when the chirp was found but the payload did not decode.+ pub index: Option<u32>,+ /// Chirp start in seconds from the first analysed sample.+ pub time_secs: f64,+ /// Estimated amplitude relative to a unit-amplitude marker.+ pub gain: f64,+ /// Normalised correlation of the chirp (1.0 = exact shape).+ pub correlation: f64,+}++const MIN_CORRELATION: f64 = 0.55;++/// Finds every marker of `source` in a mono signal.+pub fn locate_markers(+ samples: &[f32],+ sample_rate: u32,+ source: AudioSource,+) -> Vec<LocatedMarker> {+ let template = chirp(source, sample_rate);+ let m = template.len();+ if samples.len() < m || m == 0 {+ return Vec::new();+ }+ let corr = cross_correlate(samples, &template);+ let template_energy: f64 = template.iter().map(|v| f64::from(*v).powi(2)).sum();+ let mut prefix = Vec::with_capacity(samples.len() + 1);+ prefix.push(0.0f64);+ for v in samples {+ let last = *prefix.last().unwrap_or(&0.0);+ prefix.push(last + f64::from(*v).powi(2));+ }+ let lags = samples.len() - m + 1;+ let norm = |lag: usize| -> f64 {+ let energy = prefix[lag + m] - prefix[lag];+ if energy <= 1e-12 {+ 0.0+ } else {+ corr[lag] / (energy * template_energy).sqrt()+ }+ };+ let suppress = (MARKER_SECS * 0.8 * f64::from(sample_rate)) as usize;+ let mut out = Vec::new();+ let mut lag = 0;+ while lag < lags {+ let c = norm(lag);+ if c < MIN_CORRELATION {+ lag += 1;+ continue;+ }+ // Take the best peak in the neighbourhood.+ let end = (lag + suppress).min(lags);+ let (best, best_c) = (lag..end)+ .map(|l| (l, norm(l)))+ .fold((lag, c), |acc, x| if x.1 > acc.1 { x } else { acc });+ let refined = refine_peak(&corr, best);+ let gain = corr[best] / template_energy;+ let time_secs = refined / f64::from(sample_rate);+ let index = decode_payload(samples, sample_rate, source, refined);+ out.push(LocatedMarker {+ source,+ index,+ time_secs,+ gain,+ correlation: best_c,+ });+ lag = best + suppress;+ }+ out+}++fn refine_peak(corr: &[f64], at: usize) -> f64 {+ if at == 0 || at + 1 >= corr.len() {+ return at as f64;+ }+ let (a, b, c) = (corr[at - 1], corr[at], corr[at + 1]);+ let denom = a - 2.0 * b + c;+ if denom.abs() < 1e-12 {+ return at as f64;+ }+ at as f64 + (0.5 * (a - c) / denom).clamp(-0.5, 0.5)+}++fn goertzel_power(samples: &[f32], start: usize, len: usize, rate: f64, freq: f64) -> f64 {+ let w = 2.0 * std::f64::consts::PI * freq / rate;+ let coeff = 2.0 * w.cos();+ let (mut s1, mut s2) = (0.0f64, 0.0f64);+ for i in 0..len {+ let x = f64::from(samples[start + i]) * hann(i, len);+ let s = x + coeff * s1 - s2;+ s2 = s1;+ s1 = s;+ }+ s1 * s1 + s2 * s2 - coeff * s1 * s2+}++fn decode_payload(+ samples: &[f32],+ sample_rate: u32,+ source: AudioSource,+ chirp_start: f64,+) -> Option<u32> {+ let p = source.params();+ let rate = f64::from(sample_rate);+ let chirp_len = (CHIRP_SECS * rate).round();+ let mut bits = 0u32;+ for bit in 0..PAYLOAD_BITS {+ let start = chirp_start + chirp_len + (f64::from(bit) * BIT_SECS * rate);+ let len = (BIT_SECS * rate).round() as usize;+ // Analyse the middle 80% of the bit to skip the transitions.+ let guard = len / 10;+ let start = start.round() as isize + guard as isize;+ let len = len - 2 * guard;+ if start < 0 || start as usize + len > samples.len() {+ return None;+ }+ let zero = goertzel_power(samples, start as usize, len, rate, p.bit_zero);+ let one = goertzel_power(samples, start as usize, len, rate, p.bit_one);+ let (hi, lo) = if one > zero { (one, zero) } else { (zero, one) };+ if hi < lo * 4.0 {+ return None;+ }+ if one > zero {+ bits |= 1 << bit;+ }+ }+ let index = bits & MAX_AUDIO_INDEX;+ (payload_bits(index) == bits).then_some(index)+}++fn cross_correlate(signal: &[f32], template: &[f32]) -> Vec<f64> {+ let n = signal.len() + template.len();+ let size = n.next_power_of_two();+ let mut planner = FftPlanner::<f32>::new();+ let fft = planner.plan_fft_forward(size);+ let ifft = planner.plan_fft_inverse(size);+ let mut a: Vec<Complex32> = signal+ .iter()+ .map(|&v| Complex32::new(v, 0.0))+ .chain(std::iter::repeat(Complex32::new(0.0, 0.0)))+ .take(size)+ .collect();+ let mut b: Vec<Complex32> = template+ .iter()+ .map(|&v| Complex32::new(v, 0.0))+ .chain(std::iter::repeat(Complex32::new(0.0, 0.0)))+ .take(size)+ .collect();+ fft.process(&mut a);+ fft.process(&mut b);+ for (x, y) in a.iter_mut().zip(&b) {+ *x *= y.conj();+ }+ ifft.process(&mut a);+ let scale = 1.0 / size as f64;+ a.iter()+ .take(signal.len())+ .map(|c| f64::from(c.re) * scale)+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn locates_markers_of_each_source_in_a_mix() {+ let rate = 48_000;+ let secs = 6.0;+ let mut mix = vec![0.0f32; (secs * f64::from(rate)) as usize];+ let mut expected = Vec::new();+ for source in AudioSource::ALL {+ let schedule = standard_schedule(source, 0.1, secs - 0.2, 0.5);+ render_markers(&mut mix, rate, source, &schedule, 0.2);+ expected.push((source, schedule));+ }+ for (source, schedule) in expected {+ let found = locate_markers(&mix, rate, source);+ assert_eq!(found.len(), schedule.len(), "{source:?}");+ for (f, e) in found.iter().zip(&schedule) {+ assert_eq!(f.index, Some(e.index));+ assert!((f.time_secs - e.time_secs).abs() < 1.0 / f64::from(rate));+ assert!((f.gain - 0.2).abs() < 0.03, "gain {}", f.gain);+ }+ }+ }++ #[test]+ fn crc_rejects_flipped_payloads() {+ for index in [0, 1, 77, MAX_AUDIO_INDEX] {+ let bits = payload_bits(index);+ for b in 0..PAYLOAD_BITS {+ let flipped = bits ^ (1 << b);+ let i = flipped & MAX_AUDIO_INDEX;+ assert_ne!(payload_bits(i), flipped);+ }+ }+ }+}diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rsnew file mode 100644index 000000000..af3492ae9--- /dev/null+++ b/crates/verify/src/lib.rs@@ -0,0 +1,7 @@+//! Engine verification suite: marker codecs, fixture generation, a reference+//! timeline model and oracle checkers. See `crates/verify/README.md`.++pub mod audio_code;+pub mod media;+pub mod oracle;+pub mod video_code;diff --git a/crates/verify/src/media.rs b/crates/verify/src/media.rsnew file mode 100644index 000000000..82022ed7e--- /dev/null+++ b/crates/verify/src/media.rs@@ -0,0 +1,586 @@+//! Thin FFmpeg helpers used to write fixtures and read outputs. These are+//! test tools: simple, sequential and independent of the product's decoders.++use std::path::Path;++use anyhow::{Context, anyhow, bail};+use ffmpeg::{+ ChannelLayout, Dictionary, Rational,+ codec::{self, Flags as CodecFlags},+ format::{self, Pixel, Sample, sample::Type as SampleType},+ frame,+ media::Type,+ software::{resampling, scaling},+};++use crate::video_code::{PackedFrame, PixelOrder, PixelSource, Yuv420Frame};++pub fn init() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ ffmpeg::init().expect("ffmpeg init");+ ffmpeg::util::log::set_level(ffmpeg::util::log::Level::Error);+ });+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VideoCodec {+ H264,+ Hevc,+}++#[derive(Clone, Debug)]+pub struct VideoWriterConfig {+ pub width: u32,+ pub height: u32,+ /// Nominal frame rate written to the stream (the track's `r_frame_rate`).+ pub fps: u32,+ pub codec: VideoCodec,+ /// Distance between keyframes, in frames.+ pub gop: u32,+ pub b_frames: u32,+ /// Target bitrate in bits per second; `None` uses constant quality.+ pub bitrate: Option<u64>,+ /// Stream time base denominator (ticks per second).+ pub time_base: i32,+}++impl VideoWriterConfig {+ pub fn new(width: u32, height: u32, fps: u32) -> Self {+ Self {+ width,+ height,+ fps,+ codec: VideoCodec::H264,+ gop: fps,+ b_frames: 0,+ bitrate: None,+ time_base: 90_000,+ }+ }+}++fn find_video_encoder(codec: VideoCodec) -> anyhow::Result<ffmpeg::Codec> {+ let names: &[&str] = match codec {+ VideoCodec::H264 => &["libx264", "h264_videotoolbox", "h264_mf"],+ // The bundled FFmpeg's libx265 crashes inside avcodec after a few+ // frames, so HEVC uses the platform hardware encoders the product+ // itself uses (VideoToolbox, Media Foundation).+ VideoCodec::Hevc => &["hevc_videotoolbox", "hevc_mf"],+ };+ if let Ok(name) = std::env::var("CAP_VERIFY_FORCE_ENCODER") {+ return ffmpeg::encoder::find_by_name(&name).ok_or_else(|| anyhow!("no {name}"));+ }+ names+ .iter()+ .find_map(|name| ffmpeg::encoder::find_by_name(name))+ .ok_or_else(|| anyhow!("no encoder available for {codec:?}"))+}++/// Writes an MP4 (or MOV) with exactly the presentation timestamps given.+pub struct VideoWriter {+ output: format::context::Output,+ encoder: ffmpeg::encoder::Video,+ scaler: scaling::Context,+ yuv: frame::Video,+ rgba: frame::Video,+ encoder_time_base: Rational,+ stream_time_base: Rational,+ last_pts: Option<i64>,+ frames: u64,+}++impl VideoWriter {+ pub fn create(path: &Path, config: &VideoWriterConfig) -> anyhow::Result<Self> {+ init();+ let codec = find_video_encoder(config.codec)?;+ let mut output = format::output(&path).with_context(|| format!("open {path:?}"))?;+ let global_header = output+ .format()+ .flags()+ .contains(format::Flags::GLOBAL_HEADER);+ let time_base = Rational::new(1, config.time_base);+ let mut ctx = codec::context::Context::new_with_codec(codec);+ if codec.name() == "libx264" {+ ctx.set_threading(codec::threading::Config::count(1));+ }+ let mut enc = ctx.encoder().video()?;+ enc.set_width(config.width);+ enc.set_height(config.height);+ enc.set_format(Pixel::YUV420P);+ enc.set_time_base(time_base);+ enc.set_frame_rate(Some(Rational::new(config.fps as i32, 1)));+ enc.set_gop(config.gop);+ enc.set_max_b_frames(config.b_frames as usize);+ if let Some(bitrate) = config.bitrate {+ enc.set_bit_rate(bitrate as usize);+ }+ if global_header {+ enc.set_flags(CodecFlags::GLOBAL_HEADER);+ }+ let mut options = Dictionary::new();+ if codec.name() == "libx264" {+ options.set("preset", "ultrafast");+ options.set("x264-params", "scenecut=0:open-gop=0");+ if config.bitrate.is_none() {+ options.set("crf", "23");+ }+ }+ let encoder = enc.open_as_with(codec, options)?;+ let stream_time_base = {+ let mut stream = output.add_stream(codec)?;+ stream.set_parameters(&encoder);+ stream.set_time_base(time_base);+ stream.set_rate(Rational::new(config.fps as i32, 1));+ stream.time_base()+ };+ output.write_header()?;+ let stream_time_base = output+ .stream(0)+ .map(|s| s.time_base())+ .unwrap_or(stream_time_base);+ let scaler = scaling::Context::get(+ Pixel::RGBA,+ config.width,+ config.height,+ Pixel::YUV420P,+ config.width,+ config.height,+ scaling::Flags::BILINEAR,+ )?;+ Ok(Self {+ output,+ encoder,+ scaler,+ yuv: frame::Video::new(Pixel::YUV420P, config.width, config.height),+ rgba: frame::Video::new(Pixel::RGBA, config.width, config.height),+ encoder_time_base: time_base,+ stream_time_base,+ last_pts: None,+ frames: 0,+ })+ }++ /// Queues one RGBA picture (tightly packed) presented at `pts_secs`.+ pub fn write_rgba(&mut self, rgba: &[u8], pts_secs: f64) -> anyhow::Result<()> {+ let width = self.rgba.width() as usize;+ let height = self.rgba.height() as usize;+ let stride = self.rgba.stride(0);+ let dst = self.rgba.data_mut(0);+ for y in 0..height {+ dst[y * stride..y * stride + width * 4]+ .copy_from_slice(&rgba[y * width * 4..(y + 1) * width * 4]);+ }+ let mut yuv = frame::Video::new(Pixel::YUV420P, self.yuv.width(), self.yuv.height());+ self.scaler.run(&self.rgba, &mut yuv)?;+ let pts = (pts_secs * f64::from(self.encoder_time_base.denominator())+ / f64::from(self.encoder_time_base.numerator()))+ .round() as i64;+ if self.last_pts.is_some_and(|last| pts <= last) {+ bail!("non-increasing pts {pts_secs}");+ }+ self.last_pts = Some(pts);+ yuv.set_pts(Some(pts));+ self.encoder.send_frame(&yuv)?;+ self.frames += 1;+ self.drain()+ }++ fn drain(&mut self) -> anyhow::Result<()> {+ let mut packet = ffmpeg::Packet::empty();+ while self.encoder.receive_packet(&mut packet).is_ok() {+ packet.set_stream(0);+ packet.rescale_ts(self.encoder_time_base, self.stream_time_base);+ packet.write_interleaved(&mut self.output)?;+ }+ Ok(())+ }++ pub fn finish(mut self) -> anyhow::Result<u64> {+ self.encoder.send_eof()?;+ self.drain()?;+ self.output.write_trailer()?;+ Ok(self.frames)+ }+}++/// A decoded picture in a layout the marker reader understands.+pub struct Picture {+ pub frame: frame::Video,+ pub pts_secs: f64,+}++impl Picture {+ pub fn view(&self) -> PictureView<'_> {+ PictureView::new(&self.frame)+ }+}++pub enum PictureView<'a> {+ Yuv(Yuv420Frame<'a>),+ Packed(PackedFrame<'a>),+}++impl<'a> PictureView<'a> {+ pub fn new(frame: &'a frame::Video) -> Self {+ let width = frame.width() as usize;+ let height = frame.height() as usize;+ match frame.format() {+ Pixel::NV12 => PictureView::Yuv(Yuv420Frame {+ width,+ height,+ y: frame.data(0),+ y_stride: frame.stride(0),+ u: frame.data(1),+ u_stride: frame.stride(1),+ v: None,+ }),+ Pixel::RGBA | Pixel::BGRA => PictureView::Packed(PackedFrame {+ data: frame.data(0),+ width,+ height,+ stride: frame.stride(0),+ order: if frame.format() == Pixel::RGBA {+ PixelOrder::Rgba+ } else {+ PixelOrder::Bgra+ },+ }),+ _ => PictureView::Yuv(Yuv420Frame {+ width,+ height,+ y: frame.data(0),+ y_stride: frame.stride(0),+ u: frame.data(1),+ u_stride: frame.stride(1),+ v: Some((frame.data(2), frame.stride(2))),+ }),+ }+ }+}++impl PixelSource for PictureView<'_> {+ fn width(&self) -> usize {+ match self {+ PictureView::Yuv(f) => f.width(),+ PictureView::Packed(f) => f.width(),+ }+ }++ fn height(&self) -> usize {+ match self {+ PictureView::Yuv(f) => f.height(),+ PictureView::Packed(f) => f.height(),+ }+ }++ fn luma(&self, x: usize, y: usize) -> f64 {+ match self {+ PictureView::Yuv(f) => f.luma(x, y),+ PictureView::Packed(f) => f.luma(x, y),+ }+ }++ fn chroma(&self, x: usize, y: usize) -> (f64, f64) {+ match self {+ PictureView::Yuv(f) => f.chroma(x, y),+ PictureView::Packed(f) => f.chroma(x, y),+ }+ }+}++fn readable_format(format: Pixel) -> bool {+ matches!(+ format,+ Pixel::YUV420P | Pixel::YUVJ420P | Pixel::NV12 | Pixel::RGBA | Pixel::BGRA+ )+}++/// Decodes every picture of the best video stream in presentation order.+pub fn decode_video(path: &Path, mut on_picture: impl FnMut(Picture)) -> anyhow::Result<()> {+ init();+ let mut input = format::input(&path).with_context(|| format!("open {path:?}"))?;+ let stream = input+ .streams()+ .best(Type::Video)+ .ok_or_else(|| anyhow!("{path:?} has no video stream"))?;+ let index = stream.index();+ let time_base = stream.time_base();+ let mut decoder = codec::context::Context::from_parameters(stream.parameters())?+ .decoder()+ .video()?;+ let mut scaler: Option<scaling::Context> = None;+ let mut emit = |decoded: &frame::Video, scaler: &mut Option<scaling::Context>| {+ let pts = decoded.timestamp().or(decoded.pts()).unwrap_or(0);+ let pts_secs =+ pts as f64 * f64::from(time_base.numerator()) / f64::from(time_base.denominator());+ let frame = if readable_format(decoded.format()) {+ decoded.clone()+ } else {+ let s = scaler.get_or_insert_with(|| {+ scaling::Context::get(+ decoded.format(),+ decoded.width(),+ decoded.height(),+ Pixel::YUV420P,+ decoded.width(),+ decoded.height(),+ scaling::Flags::POINT,+ )+ .expect("scaler")+ });+ let mut out = frame::Video::empty();+ s.run(decoded, &mut out).expect("convert picture");+ out+ };+ on_picture(Picture { frame, pts_secs });+ };+ let mut decoded = frame::Video::empty();+ for (stream, packet) in input.packets() {+ if stream.index() != index {+ continue;+ }+ decoder.send_packet(&packet)?;+ while decoder.receive_frame(&mut decoded).is_ok() {+ emit(&decoded, &mut scaler);+ }+ }+ decoder.send_eof()?;+ while decoder.receive_frame(&mut decoded).is_ok() {+ emit(&decoded, &mut scaler);+ }+ Ok(())+}++/// Packet presentation times of the best video stream, sorted.+pub fn video_packet_times(path: &Path) -> anyhow::Result<Vec<f64>> {+ init();+ let mut input = format::input(&path).with_context(|| format!("open {path:?}"))?;+ let stream = input+ .streams()+ .best(Type::Video)+ .ok_or_else(|| anyhow!("{path:?} has no video stream"))?;+ let index = stream.index();+ let tb = stream.time_base();+ let mut times: Vec<f64> = input+ .packets()+ .filter(|(s, _)| s.index() == index)+ .filter_map(|(_, p)| p.pts())+ .map(|pts| pts as f64 * f64::from(tb.numerator()) / f64::from(tb.denominator()))+ .collect();+ times.sort_by(f64::total_cmp);+ Ok(times)+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AudioCodec {+ Aac,+ Opus,+ Flac,+}++/// Writes mono or multichannel f32 audio (channels given separately).+pub fn write_audio(+ path: &Path,+ channels: &[Vec<f32>],+ sample_rate: u32,+ codec: AudioCodec,+ bitrate: usize,+) -> anyhow::Result<()> {+ init();+ let codec_name = match codec {+ AudioCodec::Aac => "aac",+ AudioCodec::Opus => "libopus",+ AudioCodec::Flac => "flac",+ };+ let encoder_codec =+ ffmpeg::encoder::find_by_name(codec_name).ok_or_else(|| anyhow!("no {codec_name}"))?;+ let layout = ChannelLayout::default(channels.len() as i32);+ let mut output = format::output(&path)?;+ let global_header = output+ .format()+ .flags()+ .contains(format::Flags::GLOBAL_HEADER);+ let mut enc = codec::context::Context::new_with_codec(encoder_codec)+ .encoder()+ .audio()?;+ let sample_format = encoder_codec+ .audio()+ .ok()+ .and_then(|a| a.formats().and_then(|mut f| f.next()))+ .unwrap_or(Sample::F32(SampleType::Planar));+ enc.set_rate(sample_rate as i32);+ enc.set_channel_layout(layout);+ enc.set_format(sample_format);+ enc.set_bit_rate(bitrate);+ enc.set_time_base(Rational::new(1, sample_rate as i32));+ if global_header {+ enc.set_flags(CodecFlags::GLOBAL_HEADER);+ }+ let mut encoder = enc.open_as(encoder_codec)?;+ {+ let mut stream = output.add_stream(encoder_codec)?;+ stream.set_parameters(&encoder);+ stream.set_time_base(Rational::new(1, sample_rate as i32));+ }+ output.write_header()?;+ let stream_tb = output.stream(0).map(|s| s.time_base()).unwrap();+ let frame_size = match encoder.frame_size() {+ 0 => 1024,+ n => n as usize,+ };+ let mut resampler = resampling::Context::get(+ Sample::F32(SampleType::Planar),+ layout,+ sample_rate,+ sample_format,+ layout,+ sample_rate,+ )?;+ let total = channels.first().map_or(0, Vec::len);+ let mut pos = 0;+ let mut packet = ffmpeg::Packet::empty();+ let enc_tb = Rational::new(1, sample_rate as i32);+ let mut drain = |encoder: &mut ffmpeg::encoder::Audio,+ output: &mut format::context::Output|+ -> anyhow::Result<()> {+ while encoder.receive_packet(&mut packet).is_ok() {+ packet.set_stream(0);+ packet.rescale_ts(enc_tb, stream_tb);+ packet.write_interleaved(output)?;+ }+ Ok(())+ };+ while pos < total {+ let n = frame_size.min(total - pos);+ let mut planar = frame::Audio::new(Sample::F32(SampleType::Planar), n, layout);+ planar.set_rate(sample_rate);+ for (ch, data) in channels.iter().enumerate() {+ let plane: &mut [f32] = planar.plane_mut(ch);+ plane[..n].copy_from_slice(&data[pos..pos + n]);+ }+ let mut converted = frame::Audio::empty();+ resampler.run(&planar, &mut converted)?;+ converted.set_pts(Some(pos as i64));+ converted.set_rate(sample_rate);+ encoder.send_frame(&converted)?;+ drain(&mut encoder, &mut output)?;+ pos += n;+ }+ encoder.send_eof()?;+ drain(&mut encoder, &mut output)?;+ output.write_trailer()?;+ Ok(())+}++pub struct DecodedAudio {+ pub sample_rate: u32,+ /// One vector per channel.+ pub channels: Vec<Vec<f32>>,+ /// Presentation time of the first decoded sample, in seconds.+ pub start_secs: f64,+}++impl DecodedAudio {+ pub fn mono(&self) -> Vec<f32> {+ let n = self.channels.iter().map(Vec::len).min().unwrap_or(0);+ let count = self.channels.len().max(1) as f32;+ (0..n)+ .map(|i| self.channels.iter().map(|c| c[i]).sum::<f32>() / count)+ .collect()+ }+}++/// Decodes the best audio stream (optionally resampled) to planar f32.+pub fn decode_audio(path: &Path, out_rate: Option<u32>) -> anyhow::Result<DecodedAudio> {+ init();+ let mut input = format::input(&path).with_context(|| format!("open {path:?}"))?;+ let stream = input+ .streams()+ .best(Type::Audio)+ .ok_or_else(|| anyhow!("{path:?} has no audio stream"))?;+ let index = stream.index();+ let tb = stream.time_base();+ // The container start time already accounts for encoder priming that the+ // decoder strips (Opus pre-skip, AAC edit lists); the first frame's pts+ // does not always.+ let container_start = (stream.start_time() != ffmpeg::ffi::AV_NOPTS_VALUE).then(|| {+ stream.start_time() as f64 * f64::from(tb.numerator()) / f64::from(tb.denominator())+ });+ let mut decoder = codec::context::Context::from_parameters(stream.parameters())?+ .decoder()+ .audio()?;+ let mut resampler: Option<resampling::Context> = None;+ let mut channels: Vec<Vec<f32>> = Vec::new();+ let mut start_secs = None;+ let mut rate = 0;+ let mut handle = |decoded: &frame::Audio,+ resampler: &mut Option<resampling::Context>|+ -> anyhow::Result<()> {+ if start_secs.is_none() {+ let pts = decoded.pts().or(decoded.timestamp()).unwrap_or(0);+ start_secs = Some(pts as f64 * f64::from(tb.numerator()) / f64::from(tb.denominator()));+ }+ let target_rate = out_rate.unwrap_or(decoded.rate());+ rate = target_rate;+ let layout = if decoded.channel_layout().is_empty() {+ ChannelLayout::default(decoded.channels() as i32)+ } else {+ decoded.channel_layout()+ };+ let r = match resampler {+ Some(r) => r,+ None => resampler.insert(resampling::Context::get(+ decoded.format(),+ layout,+ decoded.rate(),+ Sample::F32(SampleType::Planar),+ layout,+ target_rate,+ )?),+ };+ let mut out = frame::Audio::empty();+ let mut input = decoded.clone();+ input.set_channel_layout(layout);+ r.run(&input, &mut out)?;+ append_planar(&mut channels, &out);+ Ok(())+ };+ let mut decoded = frame::Audio::empty();+ for (s, packet) in input.packets() {+ if s.index() != index {+ continue;+ }+ decoder.send_packet(&packet)?;+ while decoder.receive_frame(&mut decoded).is_ok() {+ handle(&decoded, &mut resampler)?;+ }+ }+ decoder.send_eof()?;+ while decoder.receive_frame(&mut decoded).is_ok() {+ handle(&decoded, &mut resampler)?;+ }+ if let Some(r) = resampler.as_mut() {+ let mut out = frame::Audio::empty();+ while r.flush(&mut out).is_ok() && out.samples() > 0 {+ append_planar(&mut channels, &out);+ }+ }+ Ok(DecodedAudio {+ sample_rate: rate,+ channels,+ start_secs: container_start.or(start_secs).unwrap_or(0.0),+ })+}++fn append_planar(channels: &mut Vec<Vec<f32>>, out: &frame::Audio) {+ let n = out.samples();+ let count = out.channels() as usize;+ if channels.len() < count {+ channels.resize(count, Vec::new());+ }+ for (ch, data) in channels.iter_mut().enumerate().take(count) {+ let plane: &[f32] = out.plane(ch);+ data.extend_from_slice(&plane[..n]);+ }+}diff --git a/crates/verify/src/oracle.rs b/crates/verify/src/oracle.rsnew file mode 100644index 000000000..93b0e5d9e--- /dev/null+++ b/crates/verify/src/oracle.rs@@ -0,0 +1,295 @@+//! Compares decoded markers against the reference model's expectations.++use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++use crate::video_code::{Readout, StreamKind};++/// What one output frame must show for one stream.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(tag = "expect", rename_all = "lowercase")]+pub enum StreamExpectation {+ /// The stream must show one of `allowed` (the first is canonical; more+ /// than one only when the product's documented rule is ambiguous, e.g. a+ /// request within float rounding of a frame boundary).+ Frame { segment: u8, allowed: Vec<u32> },+ /// The stream must not be visible.+ Absent,+ /// Not checked (blends such as transitions), with the reason.+ Unchecked { reason: String },+}++impl StreamExpectation {+ pub fn frame(segment: u8, index: u32) -> Self {+ StreamExpectation::Frame {+ segment,+ allowed: vec![index],+ }+ }++ pub fn canonical(&self) -> Option<(u8, u32)> {+ match self {+ StreamExpectation::Frame { segment, allowed } => {+ allowed.first().map(|&i| (*segment, i))+ }+ _ => None,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum MismatchKind {+ /// An older source frame than the model's.+ Stale,+ /// A source frame from the future.+ Ahead,+ /// A frame from a different recording segment.+ WrongSegment,+ /// The stream is visible but its code is damaged.+ Unreadable,+ /// The stream should be visible and is not.+ Missing,+ /// The stream should be hidden and is visible.+ Unexpected,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Mismatch {+ pub output_frame: u32,+ pub time_secs: f64,+ pub kind: MismatchKind,+ pub expected: Option<(u8, u32)>,+ pub observed: Option<(u8, u32)>,+ /// observed - expected, in source frames, for stale/ahead.+ pub delta: Option<i64>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub detail: Option<String>,+}++#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct StreamReport {+ pub stream: Option<StreamKind>,+ pub checked: u32,+ pub unchecked: u32,+ pub stale: u32,+ pub ahead: u32,+ pub wrong_segment: u32,+ pub unreadable: u32,+ pub missing: u32,+ pub unexpected: u32,+ pub max_ahead: i64,+ pub max_stale: i64,+ /// Source frames the model shows that never appeared.+ pub skipped_source_frames: Vec<u32>,+ /// Source frames shown on more output frames than the model says.+ pub repeated_source_frames: Vec<u32>,+ pub mismatches: Vec<Mismatch>,+}++impl StreamReport {+ pub fn failures(&self) -> u32 {+ self.stale+ + self.ahead+ + self.wrong_segment+ + self.unreadable+ + self.missing+ + self.unexpected+ }++ pub fn passed(&self) -> bool {+ self.failures() == 0+ }++ pub fn summary(&self) -> String {+ let name = self.stream.map_or("stream", StreamKind::name);+ if self.passed() {+ return format!("{name}: {} frames correct", self.checked);+ }+ let mut parts = Vec::new();+ for (label, n) in [+ ("stale", self.stale),+ ("ahead", self.ahead),+ ("wrong segment", self.wrong_segment),+ ("unreadable", self.unreadable),+ ("missing", self.missing),+ ("unexpected", self.unexpected),+ ] {+ if n > 0 {+ parts.push(format!("{n} {label}"));+ }+ }+ let mut text = format!(+ "{name}: {} of {} frames wrong ({})",+ self.failures(),+ self.checked,+ parts.join(", ")+ );+ if self.max_ahead > 0 {+ text.push_str(&format!(", up to {} source frames ahead", self.max_ahead));+ }+ if self.max_stale > 0 {+ text.push_str(&format!(", up to {} stale", self.max_stale));+ }+ if let Some(first) = self.mismatches.first() {+ text.push_str(&format!(+ "; first at output frame {} ({:.3}s): expected {:?}, got {:?}",+ first.output_frame, first.time_secs, first.expected, first.observed+ ));+ }+ text+ }+}++/// Checks one stream of a sequence of output frames. `observed[i]` is the+/// readout of output frame `frame_numbers[i]` (defaults to i).+pub fn check_stream(+ stream: StreamKind,+ expectations: &[StreamExpectation],+ observed: &[Readout],+ fps: u32,+) -> StreamReport {+ let frames: Vec<u32> = (0..observed.len() as u32).collect();+ check_stream_at(stream, expectations, observed, &frames, fps)+}++pub fn check_stream_at(+ stream: StreamKind,+ expectations: &[StreamExpectation],+ observed: &[Readout],+ frame_numbers: &[u32],+ fps: u32,+) -> StreamReport {+ let mut report = StreamReport {+ stream: Some(stream),+ ..Default::default()+ };+ let mut expected_counts: BTreeMap<(u8, u32), u32> = BTreeMap::new();+ let mut observed_counts: BTreeMap<(u8, u32), u32> = BTreeMap::new();+ for ((expectation, readout), &frame) in expectations.iter().zip(observed).zip(frame_numbers) {+ let time_secs = f64::from(frame) / f64::from(fps);+ let push = |report: &mut StreamReport,+ kind: MismatchKind,+ observed: Option<(u8, u32)>,+ delta: Option<i64>,+ detail: Option<String>| {+ report.mismatches.push(Mismatch {+ output_frame: frame,+ time_secs,+ kind,+ expected: expectation.canonical(),+ observed,+ delta,+ detail,+ });+ };+ match expectation {+ StreamExpectation::Unchecked { .. } => {+ report.unchecked += 1;+ continue;+ }+ StreamExpectation::Absent => {+ report.checked += 1;+ match readout {+ Readout::Absent => {}+ Readout::Marker { marker, .. } => {+ report.unexpected += 1;+ push(+ &mut report,+ MismatchKind::Unexpected,+ Some((marker.segment, marker.index)),+ None,+ None,+ );+ }+ Readout::Unreadable { reason } => {+ report.unexpected += 1;+ push(+ &mut report,+ MismatchKind::Unexpected,+ None,+ None,+ Some(reason.clone()),+ );+ }+ }+ }+ StreamExpectation::Frame { segment, allowed } => {+ report.checked += 1;+ let canonical = (*segment, allowed[0]);+ *expected_counts.entry(canonical).or_default() += 1;+ match readout {+ Readout::Absent => {+ report.missing += 1;+ push(&mut report, MismatchKind::Missing, None, None, None);+ }+ Readout::Unreadable { reason } => {+ report.unreadable += 1;+ push(+ &mut report,+ MismatchKind::Unreadable,+ None,+ None,+ Some(reason.clone()),+ );+ }+ Readout::Marker { marker, .. } => {+ let got = (marker.segment, marker.index);+ if marker.segment != *segment {+ *observed_counts.entry(got).or_default() += 1;+ report.wrong_segment += 1;+ push(+ &mut report,+ MismatchKind::WrongSegment,+ Some(got),+ None,+ None,+ );+ } else if allowed.contains(&marker.index) {+ *observed_counts.entry(canonical).or_default() += 1;+ } else {+ *observed_counts.entry(got).or_default() += 1;+ let lo = *allowed.iter().min().unwrap_or(&0);+ let hi = *allowed.iter().max().unwrap_or(&0);+ if marker.index < lo {+ let delta = i64::from(marker.index) - i64::from(lo);+ report.stale += 1;+ report.max_stale = report.max_stale.max(-delta);+ push(+ &mut report,+ MismatchKind::Stale,+ Some(got),+ Some(delta),+ None,+ );+ } else {+ let delta = i64::from(marker.index) - i64::from(hi);+ report.ahead += 1;+ report.max_ahead = report.max_ahead.max(delta);+ push(+ &mut report,+ MismatchKind::Ahead,+ Some(got),+ Some(delta),+ None,+ );+ }+ }+ }+ }+ }+ }+ }+ report.skipped_source_frames = expected_counts+ .iter()+ .filter(|(key, _)| !observed_counts.contains_key(key))+ .map(|((_, index), _)| *index)+ .collect();+ report.repeated_source_frames = observed_counts+ .iter()+ .filter(|(key, n)| **n > expected_counts.get(key).copied().unwrap_or(0))+ .map(|((_, index), _)| *index)+ .collect();+ report+}diff --git a/crates/verify/src/video_code.rs b/crates/verify/src/video_code.rsnew file mode 100644index 000000000..751ab410e--- /dev/null+++ b/crates/verify/src/video_code.rs@@ -0,0 +1,743 @@+//! Video frame markers.+//!+//! Every synthetic source frame is filled with its stream's key colour and+//! carries an 8x8 block code in its centre: a ring of 28 alternating pilot+//! cells (which give the local black and white levels and lock the geometry)+//! around 36 data cells holding a 16-bit frame index, a 4-bit tag (stream kind+//! and recording segment) and a CRC-16 of both.+//!+//! The reader does not need to know where the renderer put the stream: it+//! finds the stream's key-coloured region, derives the code square from the+//! region's centre and height (centre crops, rounded corners, circular camera+//! bubbles and padding all preserve both), refines the geometry against the+//! pilot ring and only then reads the data cells. A cell whose level is not+//! clearly black or white, a pilot that disagrees, or a CRC mismatch makes the+//! frame unreadable rather than wrong: a decoded index is either right or the+//! frame is reported as damaged.++use serde::{Deserialize, Serialize};++pub const GRID: usize = 8;+#[cfg(test)]+const DATA_CELLS: usize = (GRID - 2) * (GRID - 2);+const INDEX_BITS: u32 = 16;+const TAG_BITS: u32 = 4;+const PAYLOAD_BITS: u32 = INDEX_BITS + TAG_BITS;+const WHITENING: u64 = 0x9_A5C3_5E71;+pub const MAX_INDEX: u32 = (1 << INDEX_BITS) - 1;+pub const MAX_SEGMENT: u8 = 3;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum StreamKind {+ Screen,+ Camera,+}++impl StreamKind {+ pub const ALL: [StreamKind; 2] = [StreamKind::Screen, StreamKind::Camera];++ pub fn key_rgb(self) -> [u8; 3] {+ match self {+ StreamKind::Screen => [32, 96, 224],+ StreamKind::Camera => [224, 64, 128],+ }+ }++ /// Side of the code square as a fraction of the frame height. The camera+ /// code is larger because the bubble is small, and stays inside the+ /// inscribed circle of the centre square (half diagonal 0.42 < 0.5).+ pub fn code_side_fraction(self) -> f64 {+ match self {+ StreamKind::Screen => 0.5,+ StreamKind::Camera => 0.6,+ }+ }++ fn tag(self) -> u8 {+ match self {+ StreamKind::Screen => 0,+ StreamKind::Camera => 1,+ }+ }++ fn from_tag(tag: u8) -> Option<Self> {+ match tag {+ 0 => Some(StreamKind::Screen),+ 1 => Some(StreamKind::Camera),+ _ => None,+ }+ }++ fn key_chroma(self) -> (f64, f64) {+ let [r, g, b] = self.key_rgb();+ let (_, cb, cr) = rgb_to_ycbcr(r, g, b);+ (cb, cr)+ }++ pub fn name(self) -> &'static str {+ match self {+ StreamKind::Screen => "screen",+ StreamKind::Camera => "camera",+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct FrameMarker {+ pub kind: StreamKind,+ pub segment: u8,+ pub index: u32,+}++impl FrameMarker {+ pub fn new(kind: StreamKind, segment: u8, index: u32) -> Self {+ assert!(+ index <= MAX_INDEX,+ "frame index {index} exceeds {MAX_INDEX}"+ );+ assert!(+ segment <= MAX_SEGMENT,+ "segment {segment} exceeds {MAX_SEGMENT}"+ );+ Self {+ kind,+ segment,+ index,+ }+ }++ fn payload(self) -> u32 {+ let tag = u32::from(self.kind.tag() | (self.segment << 2));+ self.index | (tag << INDEX_BITS)+ }++ fn bits(self) -> u64 {+ let payload = self.payload();+ let crc = crc16(&payload.to_le_bytes()[..3]);+ (u64::from(payload) | (u64::from(crc) << PAYLOAD_BITS)) ^ WHITENING+ }++ fn from_bits(bits: u64) -> Option<Self> {+ let bits = bits ^ WHITENING;+ let payload = (bits & ((1 << PAYLOAD_BITS) - 1)) as u32;+ let crc = (bits >> PAYLOAD_BITS) as u16;+ if crc16(&payload.to_le_bytes()[..3]) != crc {+ return None;+ }+ let tag = (payload >> INDEX_BITS) as u8;+ Some(Self {+ kind: StreamKind::from_tag(tag & 0b11)?,+ segment: tag >> 2,+ index: payload & MAX_INDEX,+ })+ }+}++pub(crate) fn crc16(bytes: &[u8]) -> u16 {+ let mut crc: u16 = 0xFFFF;+ for &byte in bytes {+ crc ^= u16::from(byte) << 8;+ for _ in 0..8 {+ crc = if crc & 0x8000 != 0 {+ (crc << 1) ^ 0x1021+ } else {+ crc << 1+ };+ }+ }+ crc+}++fn pilot_is_white(row: usize, col: usize) -> bool {+ (row + col) % 2 == 1+}++fn is_pilot(row: usize, col: usize) -> bool {+ row == 0 || col == 0 || row == GRID - 1 || col == GRID - 1+}++fn data_bit_index(row: usize, col: usize) -> usize {+ (row - 1) * (GRID - 2) + (col - 1)+}++fn cell_is_white(bits: u64, row: usize, col: usize) -> bool {+ if is_pilot(row, col) {+ pilot_is_white(row, col)+ } else {+ bits >> data_bit_index(row, col) & 1 == 1+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PixelOrder {+ Rgba,+ Bgra,+}++/// Square code geometry in pixel space.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CodeGeometry {+ pub x0: f64,+ pub y0: f64,+ pub side: f64,+}++impl CodeGeometry {+ pub fn for_frame(kind: StreamKind, width: usize, height: usize) -> Self {+ let side = (kind.code_side_fraction() * height as f64)+ .min(width as f64)+ .floor();+ Self {+ x0: ((width as f64 - side) / 2.0).floor(),+ y0: ((height as f64 - side) / 2.0).floor(),+ side,+ }+ }++ fn cell_center(&self, row: usize, col: usize) -> (f64, f64) {+ let cell = self.side / GRID as f64;+ (+ self.x0 + (col as f64 + 0.5) * cell,+ self.y0 + (row as f64 + 0.5) * cell,+ )+ }+}++/// Draws a full marker frame (key colour background plus the code) into a+/// packed 4-byte-per-pixel buffer.+pub fn draw_marker(+ marker: FrameMarker,+ data: &mut [u8],+ width: usize,+ height: usize,+ stride: usize,+ order: PixelOrder,+) {+ let [kr, kg, kb] = marker.kind.key_rgb();+ let key = match order {+ PixelOrder::Rgba => [kr, kg, kb, 255],+ PixelOrder::Bgra => [kb, kg, kr, 255],+ };+ let geometry = CodeGeometry::for_frame(marker.kind, width, height);+ let bits = marker.bits();+ let cell = geometry.side / GRID as f64;+ for y in 0..height {+ let row = &mut data[y * stride..y * stride + width * 4];+ let fy = y as f64 + 0.5 - geometry.y0;+ let code_row = (fy >= 0.0 && fy < geometry.side).then(|| (fy / cell) as usize);+ for (x, px) in row.chunks_exact_mut(4).enumerate() {+ let fx = x as f64 + 0.5 - geometry.x0;+ let value = match code_row {+ Some(r) if fx >= 0.0 && fx < geometry.side => {+ let c = ((fx / cell) as usize).min(GRID - 1);+ let r = r.min(GRID - 1);+ Some(if cell_is_white(bits, r, c) { 255 } else { 0 })+ }+ _ => None,+ };+ match value {+ Some(v) => px.copy_from_slice(&[v, v, v, 255]),+ None => px.copy_from_slice(&key),+ }+ }+ }+}++/// Allocates and draws an RGBA marker frame.+pub fn marker_rgba(marker: FrameMarker, width: usize, height: usize) -> Vec<u8> {+ let mut data = vec![0u8; width * height * 4];+ draw_marker(+ marker,+ &mut data,+ width,+ height,+ width * 4,+ PixelOrder::Rgba,+ );+ data+}++pub fn rgb_to_ycbcr(r: u8, g: u8, b: u8) -> (f64, f64, f64) {+ let (r, g, b) = (f64::from(r), f64::from(g), f64::from(b));+ (+ 0.299 * r + 0.587 * g + 0.114 * b,+ -0.168_736 * r - 0.331_264 * g + 0.5 * b,+ 0.5 * r - 0.418_688 * g - 0.081_312 * b,+ )+}++/// Read access to a decoded picture in luma + centred chroma.+pub trait PixelSource {+ fn width(&self) -> usize;+ fn height(&self) -> usize;+ fn luma(&self, x: usize, y: usize) -> f64;+ /// (Cb - 128, Cr - 128) at the pixel.+ fn chroma(&self, x: usize, y: usize) -> (f64, f64);+}++pub struct PackedFrame<'a> {+ pub data: &'a [u8],+ pub width: usize,+ pub height: usize,+ pub stride: usize,+ pub order: PixelOrder,+}++impl PackedFrame<'_> {+ fn rgb(&self, x: usize, y: usize) -> (u8, u8, u8) {+ let i = y * self.stride + x * 4;+ let px = &self.data[i..i + 3];+ match self.order {+ PixelOrder::Rgba => (px[0], px[1], px[2]),+ PixelOrder::Bgra => (px[2], px[1], px[0]),+ }+ }+}++impl PixelSource for PackedFrame<'_> {+ fn width(&self) -> usize {+ self.width+ }++ fn height(&self) -> usize {+ self.height+ }++ fn luma(&self, x: usize, y: usize) -> f64 {+ let (r, g, b) = self.rgb(x, y);+ rgb_to_ycbcr(r, g, b).0+ }++ fn chroma(&self, x: usize, y: usize) -> (f64, f64) {+ let (r, g, b) = self.rgb(x, y);+ let (_, cb, cr) = rgb_to_ycbcr(r, g, b);+ (cb, cr)+ }+}++/// Planar 4:2:0 picture (YUV420P), or semi-planar NV12 when `v` is `None`+/// and `u` holds interleaved CbCr.+pub struct Yuv420Frame<'a> {+ pub width: usize,+ pub height: usize,+ pub y: &'a [u8],+ pub y_stride: usize,+ pub u: &'a [u8],+ pub u_stride: usize,+ pub v: Option<(&'a [u8], usize)>,+}++impl PixelSource for Yuv420Frame<'_> {+ fn width(&self) -> usize {+ self.width+ }++ fn height(&self) -> usize {+ self.height+ }++ fn luma(&self, x: usize, y: usize) -> f64 {+ f64::from(self.y[y * self.y_stride + x])+ }++ fn chroma(&self, x: usize, y: usize) -> (f64, f64) {+ let (cx, cy) = (x / 2, y / 2);+ let (cb, cr) = match self.v {+ Some((v, v_stride)) => (self.u[cy * self.u_stride + cx], v[cy * v_stride + cx]),+ None => {+ let i = cy * self.u_stride + cx * 2;+ (self.u[i], self.u[i + 1])+ }+ };+ (f64::from(cb) - 128.0, f64::from(cr) - 128.0)+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(tag = "state", rename_all = "lowercase")]+pub enum Readout {+ /// No region of this stream's key colour is visible.+ Absent,+ /// The stream is visible but its code could not be read reliably.+ Unreadable { reason: String },+ Marker {+ marker: FrameMarker,+ /// Worst data-cell distance from the black/white threshold, as a+ /// fraction of the pilot contrast (0.5 = perfect).+ margin: f64,+ mirrored: bool,+ },+}++impl Readout {+ pub fn marker(&self) -> Option<FrameMarker> {+ match self {+ Readout::Marker { marker, .. } => Some(*marker),+ _ => None,+ }+ }+}++#[derive(Clone, Copy, Debug)]+pub struct Region {+ pub x0: f64,+ pub y0: f64,+ pub x1: f64,+ pub y1: f64,+}++const KEY_CHROMA_TOLERANCE: f64 = 38.0;+const KEY_MIN_CHROMA: f64 = 36.0;++fn is_key(chroma: (f64, f64), key: (f64, f64)) -> bool {+ let magnitude = chroma.0.hypot(chroma.1);+ if magnitude < KEY_MIN_CHROMA {+ return false;+ }+ // Limited-range video scales chroma by 224/255; compare against both.+ let full = (chroma.0 - key.0).hypot(chroma.1 - key.1);+ let limited = (chroma.0 - key.0 * 0.878).hypot(chroma.1 - key.1 * 0.878);+ full.min(limited) < KEY_CHROMA_TOLERANCE+}++/// Bounding box of the stream's key-coloured region.+pub fn locate_region(img: &impl PixelSource, kind: StreamKind) -> Option<Region> {+ let (w, h) = (img.width(), img.height());+ if w < 8 || h < 8 {+ return None;+ }+ let step = (w.min(h) / 240).max(1);+ let key = kind.key_chroma();+ let cols = w.div_ceil(step);+ let rows = h.div_ceil(step);+ let mut row_counts = vec![0usize; rows];+ let mut col_counts = vec![0usize; cols];+ for (ry, row_count) in row_counts.iter_mut().enumerate() {+ let y = ry * step;+ for (cx, col_count) in col_counts.iter_mut().enumerate() {+ if is_key(img.chroma(cx * step, y), key) {+ *row_count += 1;+ *col_count += 1;+ }+ }+ }+ let total: usize = row_counts.iter().sum();+ if total < 12 {+ return None;+ }+ let extent = |counts: &[usize]| -> Option<(usize, usize)> {+ let max = *counts.iter().max()?;+ let threshold = (max / 10).max(2);+ let first = counts.iter().position(|&c| c >= threshold)?;+ let last = counts.iter().rposition(|&c| c >= threshold)?;+ Some((first, last))+ };+ let (r0, r1) = extent(&row_counts)?;+ let (c0, c1) = extent(&col_counts)?;+ let refine = |coarse: usize, dir: isize, horizontal: bool| -> f64 {+ // Walk outward from the coarse edge at full resolution along the+ // centre line of the region to find the exact key boundary.+ let (lo, hi) = if horizontal { (0, w) } else { (0, h) };+ let mid_other = if horizontal {+ ((r0 + r1) * step / 2).min(h - 1)+ } else {+ ((c0 + c1) * step / 2).min(w - 1)+ };+ let probe = |p: usize| {+ let (x, y) = if horizontal {+ (p, mid_other)+ } else {+ (mid_other, p)+ };+ is_key(img.chroma(x, y), key)+ };+ let mut p = (coarse * step).clamp(lo, hi - 1) as isize;+ let limit = (2 * step) as isize + 2;+ let mut moved = 0;+ while moved < limit {+ let next = p + dir;+ if next < lo as isize || next >= hi as isize || !probe(next as usize) {+ break;+ }+ p = next;+ moved += 1;+ }+ if dir < 0 { p as f64 } else { p as f64 + 1.0 }+ };+ // Rows/columns through the centre may cross the code (no key colour),+ // so refine horizontal edges on the region's top band instead when the+ // centre line misses; the coarse value is kept when refinement fails.+ let x0 = refine(c0, -1, true).min((c0 * step) as f64);+ let x1 = refine(c1, 1, true).max((c1 * step + 1) as f64);+ let y0 = refine(r0, -1, false).min((r0 * step) as f64);+ let y1 = refine(r1, 1, false).max((r1 * step + 1) as f64);+ Some(Region { x0, y0, x1, y1 })+}++struct CellSample {+ levels: [[f64; GRID]; GRID],+}++fn sample_cells(img: &impl PixelSource, geometry: &CodeGeometry) -> Option<CellSample> {+ let (w, h) = (img.width() as f64, img.height() as f64);+ let cell = geometry.side / GRID as f64;+ let mut levels = [[0.0; GRID]; GRID];+ let offsets = [-0.22, 0.0, 0.22];+ for (row, row_levels) in levels.iter_mut().enumerate() {+ for (col, level) in row_levels.iter_mut().enumerate() {+ let (cx, cy) = geometry.cell_center(row, col);+ let mut sum = 0.0;+ let mut n = 0.0;+ for oy in offsets {+ for ox in offsets {+ let x = cx + ox * cell;+ let y = cy + oy * cell;+ if x < 0.0 || y < 0.0 || x >= w || y >= h {+ return None;+ }+ sum += img.luma(x as usize, y as usize);+ n += 1.0;+ }+ }+ *level = sum / n;+ }+ }+ Some(CellSample { levels })+}++struct PilotFit {+ black: f64,+ white: f64,+ margin: f64,+}++fn pilot_fit(sample: &CellSample) -> PilotFit {+ let mut black_sum = 0.0;+ let mut white_sum = 0.0;+ let mut black_max = f64::MIN;+ let mut white_min = f64::MAX;+ let mut nb = 0.0;+ let mut nw = 0.0;+ for (row, row_levels) in sample.levels.iter().enumerate() {+ for (col, &v) in row_levels.iter().enumerate() {+ if !is_pilot(row, col) {+ continue;+ }+ if pilot_is_white(row, col) {+ white_sum += v;+ nw += 1.0;+ white_min = white_min.min(v);+ } else {+ black_sum += v;+ nb += 1.0;+ black_max = black_max.max(v);+ }+ }+ }+ PilotFit {+ black: black_sum / nb,+ white: white_sum / nw,+ margin: white_min - black_max,+ }+}++const MIN_CONTRAST: f64 = 48.0;+const MIN_CELL_MARGIN: f64 = 0.18;++/// Reads the code of one stream from a picture, locating it by key colour.+pub fn read_stream(img: &impl PixelSource, kind: StreamKind) -> Readout {+ let Some(region) = locate_region(img, kind) else {+ return Readout::Absent;+ };+ let height = region.y1 - region.y0;+ let width = region.x1 - region.x0;+ let side = kind.code_side_fraction() * height;+ let side = side.min(width);+ if side < 12.0 {+ return Readout::Unreadable {+ reason: format!("{} region too small ({width:.0}x{height:.0})", kind.name()),+ };+ }+ let cx = (region.x0 + region.x1) / 2.0;+ let cy = (region.y0 + region.y1) / 2.0;+ read_code_near(img, kind, cx, cy, side)+}++/// Reads a code whose square is approximately centred at (cx, cy) with the+/// given side, refining position and scale against the pilot ring.+pub fn read_code_near(+ img: &impl PixelSource,+ kind: StreamKind,+ cx: f64,+ cy: f64,+ side: f64,+) -> Readout {+ let cell = side / GRID as f64;+ let shift_step = (cell / 6.0).max(0.5);+ let mut best: Option<(PilotFit, CellSample, CodeGeometry)> = None;+ for scale in [1.0, 0.97, 1.03, 0.94, 1.06] {+ for dy in -2..=2 {+ for dx in -2..=2 {+ let s = side * scale;+ let geometry = CodeGeometry {+ x0: cx - s / 2.0 + f64::from(dx) * shift_step,+ y0: cy - s / 2.0 + f64::from(dy) * shift_step,+ side: s,+ };+ let Some(sample) = sample_cells(img, &geometry) else {+ continue;+ };+ let fit = pilot_fit(&sample);+ if best.as_ref().is_none_or(|(b, _, _)| fit.margin > b.margin) {+ best = Some((fit, sample, geometry));+ }+ }+ }+ }+ let Some((fit, sample, _geometry)) = best else {+ return Readout::Unreadable {+ reason: "code square falls outside the picture".into(),+ };+ };+ let contrast = fit.white - fit.black;+ if contrast < MIN_CONTRAST {+ return Readout::Unreadable {+ reason: format!("pilot contrast {contrast:.0} too low"),+ };+ }+ if fit.margin < contrast * 0.3 {+ return Readout::Unreadable {+ reason: format!(+ "pilot ring not resolved (margin {:.2})",+ fit.margin / contrast+ ),+ };+ }+ let threshold = (fit.white + fit.black) / 2.0;+ let mut worst = f64::MAX;+ let mut bits = 0u64;+ let mut mirrored_bits = 0u64;+ for (row, row_levels) in sample.levels.iter().enumerate() {+ for (col, &v) in row_levels.iter().enumerate() {+ if is_pilot(row, col) {+ continue;+ }+ worst = worst.min((v - threshold).abs() / contrast);+ if v > threshold {+ bits |= 1 << data_bit_index(row, col);+ mirrored_bits |= 1 << data_bit_index(row, GRID - 1 - col);+ }+ }+ }+ if worst < MIN_CELL_MARGIN {+ return Readout::Unreadable {+ reason: format!("ambiguous data cell (margin {worst:.2})"),+ };+ }+ for (candidate, mirrored) in [(bits, false), (mirrored_bits, true)] {+ if let Some(marker) = FrameMarker::from_bits(candidate) {+ if marker.kind != kind {+ return Readout::Unreadable {+ reason: format!(+ "{} region carries a {} code",+ kind.name(),+ marker.kind.name()+ ),+ };+ }+ return Readout::Marker {+ marker,+ margin: worst,+ mirrored,+ };+ }+ }+ Readout::Unreadable {+ reason: "checksum mismatch".into(),+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct FrameReadout {+ pub screen: Readout,+ pub camera: Readout,+}++impl FrameReadout {+ pub fn get(&self, kind: StreamKind) -> &Readout {+ match kind {+ StreamKind::Screen => &self.screen,+ StreamKind::Camera => &self.camera,+ }+ }+}++pub fn read_frame(img: &impl PixelSource) -> FrameReadout {+ FrameReadout {+ screen: read_stream(img, StreamKind::Screen),+ camera: read_stream(img, StreamKind::Camera),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn packed(data: &[u8], w: usize, h: usize) -> PackedFrame<'_> {+ PackedFrame {+ data,+ width: w,+ height: h,+ stride: w * 4,+ order: PixelOrder::Rgba,+ }+ }++ #[test]+ fn bits_round_trip_for_every_tag() {+ for kind in StreamKind::ALL {+ for segment in 0..=MAX_SEGMENT {+ for index in [0, 1, 2, 255, 256, 4095, 30_000, MAX_INDEX] {+ let marker = FrameMarker::new(kind, segment, index);+ assert_eq!(FrameMarker::from_bits(marker.bits()), Some(marker));+ }+ }+ }+ }++ #[test]+ fn single_and_double_bit_errors_never_decode_as_another_marker() {+ let marker = FrameMarker::new(StreamKind::Screen, 0, 1234);+ let bits = marker.bits();+ for i in 0..DATA_CELLS {+ assert_eq!(FrameMarker::from_bits(bits ^ (1 << i)), None);+ for j in i + 1..DATA_CELLS {+ assert_eq!(FrameMarker::from_bits(bits ^ (1 << i) ^ (1 << j)), None);+ }+ }+ }++ #[test]+ fn clean_frames_decode_at_many_sizes() {+ for (w, h) in [(320, 180), (640, 360), (1280, 720), (100, 100), (64, 48)] {+ for kind in StreamKind::ALL {+ for index in [0, 7, 1000, MAX_INDEX] {+ let marker = FrameMarker::new(kind, 2, index);+ let data = marker_rgba(marker, w, h);+ let readout = read_stream(&packed(&data, w, h), kind);+ assert_eq!(readout.marker(), Some(marker), "{w}x{h} {readout:?}");+ }+ }+ }+ }++ #[test]+ fn other_stream_reads_absent() {+ let data = marker_rgba(FrameMarker::new(StreamKind::Screen, 0, 5), 320, 180);+ assert_eq!(+ read_stream(&packed(&data, 320, 180), StreamKind::Camera),+ Readout::Absent+ );+ }+}diff --git a/crates/verify/tests/codec.rs b/crates/verify/tests/codec.rsnew file mode 100644index 000000000..a9b0bb9c4--- /dev/null+++ b/crates/verify/tests/codec.rs@@ -0,0 +1,356 @@+//! Marker codec robustness: the video code must survive lossy encoding,+//! scaling, compositing and blur, and the audio markers must be located to+//! well under a millisecond after lossy encoding and resampling.++use cap_verify::{+ audio_code::{self, AudioSource},+ media::{self, AudioCodec, VideoCodec, VideoWriter, VideoWriterConfig},+ oracle::{self, StreamExpectation},+ video_code::{self, FrameMarker, PackedFrame, PixelOrder, Readout, StreamKind},+};++struct Rgba {+ data: Vec<u8>,+ w: usize,+ h: usize,+}++impl Rgba {+ fn new(w: usize, h: usize, rgb: [u8; 3]) -> Self {+ let mut data = vec![255u8; w * h * 4];+ for px in data.chunks_exact_mut(4) {+ px[..3].copy_from_slice(&rgb);+ }+ Self { data, w, h }+ }++ fn view(&self) -> PackedFrame<'_> {+ PackedFrame {+ data: &self.data,+ width: self.w,+ height: self.h,+ stride: self.w * 4,+ order: PixelOrder::Rgba,+ }+ }++ fn get(&self, x: usize, y: usize) -> [u8; 4] {+ let i = (y * self.w + x) * 4;+ [+ self.data[i],+ self.data[i + 1],+ self.data[i + 2],+ self.data[i + 3],+ ]+ }++ /// Bilinear resample of a source rectangle into a new image.+ fn crop_scale(&self, sx: f64, sy: f64, sw: f64, sh: f64, w: usize, h: usize) -> Rgba {+ let mut out = Rgba::new(w, h, [0, 0, 0]);+ for y in 0..h {+ for x in 0..w {+ let fx = sx + (x as f64 + 0.5) * sw / w as f64 - 0.5;+ let fy = sy + (y as f64 + 0.5) * sh / h as f64 - 0.5;+ let x0 = fx.floor().clamp(0.0, (self.w - 1) as f64) as usize;+ let y0 = fy.floor().clamp(0.0, (self.h - 1) as f64) as usize;+ let x1 = (x0 + 1).min(self.w - 1);+ let y1 = (y0 + 1).min(self.h - 1);+ let ax = (fx - x0 as f64).clamp(0.0, 1.0);+ let ay = (fy - y0 as f64).clamp(0.0, 1.0);+ let i = (y * w + x) * 4;+ for c in 0..3 {+ let v = |px: [u8; 4]| f64::from(px[c]);+ let top = v(self.get(x0, y0)) * (1.0 - ax) + v(self.get(x1, y0)) * ax;+ let bottom = v(self.get(x0, y1)) * (1.0 - ax) + v(self.get(x1, y1)) * ax;+ out.data[i + c] = (top * (1.0 - ay) + bottom * ay).round() as u8;+ }+ }+ }+ out+ }++ /// Pastes `src` at (x, y) through a rounded-rectangle mask of radius `r`+ /// (r = half the side gives a circle), anti-aliased over one pixel.+ fn paste_rounded(&mut self, src: &Rgba, ox: usize, oy: usize, r: f64) {+ for y in 0..src.h {+ for x in 0..src.w {+ let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);+ let cx = px.clamp(r, src.w as f64 - r);+ let cy = py.clamp(r, src.h as f64 - r);+ let d = (px - cx).hypot(py - cy) - r;+ let alpha = (0.5 - d).clamp(0.0, 1.0);+ let (tx, ty) = (ox + x, oy + y);+ if tx >= self.w || ty >= self.h || alpha == 0.0 {+ continue;+ }+ let i = (ty * self.w + tx) * 4;+ let j = (y * src.w + x) * 4;+ for c in 0..3 {+ let blended = f64::from(self.data[i + c]) * (1.0 - alpha)+ + f64::from(src.data[j + c]) * alpha;+ self.data[i + c] = blended.round() as u8;+ }+ }+ }+ }++ fn box_blur(&self) -> Rgba {+ let mut out = Rgba::new(self.w, self.h, [0, 0, 0]);+ for y in 0..self.h {+ for x in 0..self.w {+ for c in 0..3 {+ let mut sum = 0u32;+ let mut n = 0u32;+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let xx = x as i32 + dx;+ let yy = y as i32 + dy;+ if xx >= 0+ && yy >= 0+ && (xx as usize) < self.w+ && (yy as usize) < self.h+ {+ sum += u32::from(self.get(xx as usize, yy as usize)[c]);+ n += 1;+ }+ }+ }+ out.data[(y * self.w + x) * 4 + c] = (sum / n) as u8;+ }+ }+ }+ out+ }+}++fn marker_frame(marker: FrameMarker, w: usize, h: usize) -> Rgba {+ Rgba {+ data: video_code::marker_rgba(marker, w, h),+ w,+ h,+ }+}++/// A composited editor-like output: background, padded screen with rounded+/// corners, circular camera bubble bottom right.+fn composite(screen: u32, camera: u32, out_w: usize, out_h: usize, blur: bool) -> Rgba {+ let screen_src = marker_frame(FrameMarker::new(StreamKind::Screen, 0, screen), 1280, 720);+ let camera_src = marker_frame(FrameMarker::new(StreamKind::Camera, 0, camera), 640, 360);+ let mut out = Rgba::new(out_w, out_h, [60, 60, 60]);+ let pad = out_w as f64 * 0.06;+ let sw = out_w as f64 - 2.0 * pad;+ let sh = sw * 9.0 / 16.0;+ let screen_img = screen_src.crop_scale(0.0, 0.0, 1280.0, 720.0, sw as usize, sh as usize);+ let sy = ((out_h as f64 - sh) / 2.0).max(0.0);+ out.paste_rounded(&screen_img, pad as usize, sy as usize, sw * 0.03);+ let bubble = (out_h as f64 * 0.3).round() as usize;+ let camera_img = camera_src.crop_scale(140.0, 0.0, 360.0, 360.0, bubble, bubble);+ let bx = out_w - bubble - (out_w as f64 * 0.03) as usize;+ let by = out_h - bubble - (out_h as f64 * 0.04) as usize;+ out.paste_rounded(&camera_img, bx, by, bubble as f64 / 2.0);+ if blur { out.box_blur() } else { out }+}++fn encode_decode(+ frames: &[Rgba],+ codec: VideoCodec,+ bitrate: u64,+ dir: &std::path::Path,+) -> Option<Vec<media::Picture>> {+ let (w, h) = (frames[0].w as u32, frames[0].h as u32);+ let mut config = VideoWriterConfig::new(w, h, 30);+ config.codec = codec;+ config.bitrate = Some(bitrate);+ config.gop = 30;+ let path = dir.join(format!("{codec:?}-{w}x{h}-{bitrate}.mp4"));+ let mut writer = match VideoWriter::create(&path, &config) {+ Ok(writer) => writer,+ Err(error) if codec == VideoCodec::Hevc => {+ eprintln!("skipping HEVC: {error}");+ return None;+ }+ Err(error) => panic!("{error:?}"),+ };+ for (i, frame) in frames.iter().enumerate() {+ writer.write_rgba(&frame.data, i as f64 / 30.0).unwrap();+ }+ writer.finish().unwrap();+ let mut pictures = Vec::new();+ media::decode_video(&path, |p| pictures.push(p)).unwrap();+ Some(pictures)+}++#[test]+fn video_code_survives_low_bitrate_h264_and_hevc_on_full_frames() {+ let dir = tempfile::tempdir().unwrap();+ for (kind, w, h) in [+ (StreamKind::Screen, 640, 360),+ (StreamKind::Camera, 320, 240),+ ] {+ let indices: Vec<u32> = (0..45).map(|i| (i * 977 + 13) % 65_536).collect();+ let frames: Vec<Rgba> = indices+ .iter()+ .map(|&i| marker_frame(FrameMarker::new(kind, 1, i), w, h))+ .collect();+ for codec in [VideoCodec::H264, VideoCodec::Hevc] {+ let Some(pictures) = encode_decode(&frames, codec, 120_000, dir.path()) else {+ continue;+ };+ assert_eq!(pictures.len(), frames.len());+ for (picture, &index) in pictures.iter().zip(&indices) {+ let readout = video_code::read_stream(&picture.view(), kind);+ assert_eq!(+ readout.marker(),+ Some(FrameMarker::new(kind, 1, index)),+ "{codec:?} {kind:?} at {:.3}s: {readout:?}",+ picture.pts_secs+ );+ }+ }+ }+}++#[test]+fn video_code_survives_compositing_scaling_rounding_bubble_and_blur() {+ let dir = tempfile::tempdir().unwrap();+ // 640x360 is a typical verification output; 320x180 puts the screen at+ // a quarter of its source size and the camera code cells at ~6 px.+ for (out_w, out_h, bitrate) in [(640, 360, 150_000), (320, 180, 80_000)] {+ for blur in [false, true] {+ let pairs: Vec<(u32, u32)> = (0..40).map(|i| (i * 3 + 100, i / 2 + 7)).collect();+ let frames: Vec<Rgba> = pairs+ .iter()+ .map(|&(s, c)| composite(s, c, out_w, out_h, blur))+ .collect();+ for (raw, &(s, c)) in frames.iter().zip(&pairs) {+ let readout = video_code::read_frame(&raw.view());+ assert_eq!(readout.screen.marker().map(|m| m.index), Some(s));+ assert_eq!(readout.camera.marker().map(|m| m.index), Some(c));+ }+ for codec in [VideoCodec::H264, VideoCodec::Hevc] {+ let Some(pictures) = encode_decode(&frames, codec, bitrate, dir.path()) else {+ continue;+ };+ for (picture, &(s, c)) in pictures.iter().zip(&pairs) {+ let readout = video_code::read_frame(&picture.view());+ assert_eq!(+ (+ readout.screen.marker().map(|m| m.index),+ readout.camera.marker().map(|m| m.index)+ ),+ (Some(s), Some(c)),+ "{codec:?} {out_w}x{out_h} blur={blur}: {readout:?}"+ );+ }+ }+ }+ }+}++#[test]+fn damaged_codes_read_as_unreadable_never_as_another_frame() {+ let w = 320;+ let h = 180;+ let marker = FrameMarker::new(StreamKind::Screen, 0, 4242);+ let mut hits = 0;+ // Smear a grey bar across successive rows of the code: every damaged+ // picture must read as the true marker or as unreadable.+ for bar in 0..h {+ let mut frame = marker_frame(marker, w, h);+ for y in bar..(bar + 6).min(h) {+ for x in 0..w {+ let i = (y * w + x) * 4;+ frame.data[i..i + 3].copy_from_slice(&[128, 128, 128]);+ }+ }+ match video_code::read_stream(&frame.view(), StreamKind::Screen) {+ Readout::Marker { marker: m, .. } => {+ assert_eq!(m, marker);+ hits += 1;+ }+ Readout::Unreadable { .. } | Readout::Absent => {}+ }+ }+ assert!(hits > 0);+}++#[test]+fn sequence_oracle_flags_wrong_duplicated_and_missing_frames_after_encode() {+ let dir = tempfile::tempdir().unwrap();+ let expected: Vec<u32> = (0..60).collect();+ let mut shown = expected.clone();+ shown[10] = 9; // duplicate of the previous frame (stale)+ shown[20] = 23; // a frame from the future+ shown.remove(30); // one frame skipped...+ shown.insert(31, 31); // ...and one repeated to keep the length+ let frames: Vec<Rgba> = shown+ .iter()+ .map(|&i| marker_frame(FrameMarker::new(StreamKind::Screen, 0, i), 320, 180))+ .collect();+ let pictures = encode_decode(&frames, VideoCodec::H264, 100_000, dir.path()).unwrap();+ let observed: Vec<Readout> = pictures+ .iter()+ .map(|p| video_code::read_stream(&p.view(), StreamKind::Screen))+ .collect();+ let expectations: Vec<StreamExpectation> = expected+ .iter()+ .map(|&i| StreamExpectation::frame(0, i))+ .collect();+ let report = oracle::check_stream(StreamKind::Screen, &expectations, &observed, 30);+ let wrong: Vec<u32> = report.mismatches.iter().map(|m| m.output_frame).collect();+ assert_eq!(wrong, vec![10, 20, 30]);+ assert_eq!(report.stale, 1);+ assert_eq!(report.ahead, 2);+ assert_eq!(report.skipped_source_frames, vec![10, 20, 30]);+ assert_eq!(report.repeated_source_frames, vec![9, 23, 31]);+}++#[test]+fn audio_markers_locate_within_a_millisecond_after_lossy_codecs_and_resampling() {+ let dir = tempfile::tempdir().unwrap();+ let rate = 48_000;+ let secs = 8.0;+ let mut mix = vec![0.0f32; (secs * f64::from(rate)) as usize];+ let mut schedules = Vec::new();+ for source in [AudioSource::Mic, AudioSource::System] {+ let schedule = audio_code::standard_schedule(source, 0.25, secs - 0.5, 0.5);+ audio_code::render_markers(&mut mix, rate, source, &schedule, 0.25);+ schedules.push((source, schedule));+ }+ for (codec, ext, bitrate) in [+ (AudioCodec::Aac, "m4a", 64_000),+ (AudioCodec::Opus, "ogg", 32_000),+ ] {+ let path = dir.path().join(format!("markers.{ext}"));+ media::write_audio(&path, &[mix.clone(), mix.clone()], rate, codec, bitrate).unwrap();+ for out_rate in [None, Some(44_100), Some(16_000)] {+ let decoded = media::decode_audio(&path, out_rate).unwrap();+ let mono = decoded.mono();+ for (source, schedule) in &schedules {+ let found = audio_code::locate_markers(&mono, decoded.sample_rate, *source);+ assert_eq!(+ found.len(),+ schedule.len(),+ "{codec:?} {out_rate:?} {source:?}"+ );+ let mut worst = 0.0f64;+ for (f, e) in found.iter().zip(schedule) {+ assert_eq!(f.index, Some(e.index), "{codec:?} {out_rate:?} {source:?}");+ let error = (f.time_secs + decoded.start_secs - e.time_secs).abs();+ worst = worst.max(error);+ assert!((f.gain / 0.25 - 1.0).abs() < 0.3, "gain {}", f.gain);+ }+ assert!(+ worst < 0.001,+ "{codec:?} {out_rate:?} {source:?}: worst error {:.3} ms",+ worst * 1e3+ );+ eprintln!(+ "{codec:?} {out_rate:?} {source:?}: {} markers, worst {:.3} ms",+ found.len(),+ worst * 1e3+ );+ }+ }+ }+}