Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(verify): close mutation gaps in captions, colour, frame size and audio

Richie McIlroy97e218e780e5
diff --git a/Cargo.lock b/Cargo.lock
index 3c5bd2acf..6c5bfd6bb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2156,6 +2156,7 @@ name = "cap-verify"
version = "0.1.0"
dependencies = [
"anyhow",
+ "cap-audio",
"cap-editor",
"cap-enc-avfoundation",
"cap-export",
diff --git a/crates/verify/Cargo.toml b/crates/verify/Cargo.toml
index 9e9e58da0..2678ea749 100644
--- a/crates/verify/Cargo.toml
+++ b/crates/verify/Cargo.toml
@@ -31,6 +31,7 @@ cidre = { workspace = true }
[dev-dependencies]
cap-editor = { path = "../editor", features = ["test-hooks"] }
+cap-audio = { path = "../audio" }
cap-export = { path = "../export" }
cap-rendering = { path = "../rendering" }
tempfile = "3"
diff --git a/crates/verify/expectations.toml b/crates/verify/expectations.toml
index 495483f4e..7a7bcc189 100644
--- a/crates/verify/expectations.toml
+++ b/crates/verify/expectations.toml
@@ -271,3 +271,15 @@ case = "seek/seek-gop/home-then-play30/ffmpeg"
class = "stale"
reason = "NEW: FFmpeg decoder freezes on the first frame after a jump to the start. Seek 6.1 s, seek 0, seek 2.0 s and play: 31 of 122 frames show source frame 0 (up to 89 frames stale, about 1 s frozen). A request at grid 0..2 is answered by the first-frame shortcut (ffmpeg.rs, requested_frame <= MAX_FRAME_LOOKBACK_TOLERANCE) without resetting the reader, which stays near 6 s, and last_sent_frame becomes frame 0; the next request is then not 'far forward' of frame 0 (< FRAME_CACHE_SIZE), so no reset happens, the reader vends frames past the request and the answer falls back to last_sent_frame (frame 0) until playback outruns FRAME_CACHE_SIZE. Main decoder on Linux and on Windows without a D3D11 video device; macOS AVAssetReader passes. Minimal: CAP_VERIFY_SEEK_SCRIPT='seek-gop@60:6.1,0.0167,2.0667' (third request shows frame 0 for 61)"
link = ""
+
+[[xfail]]
+case = "export/basic/colour-red/mp430/*"
+class = "colour-level"
+reason = "NEW: export converts rendered RGBA to NV12 with BT.601 coefficients (GPU: crates/rendering/src/shaders/rgba_to_nv12.wgsl; software adapters: convert_rgba_to_nv12 in crates/rendering/src/lib.rs) but the encoder tags the stream BT.709 (crates/enc-ffmpeg/src/video/h264.rs), so players decode renderer-generated colour (backgrounds, captions, cursor, text) shifted: background (220,40,40) decodes about 13 luma code values too bright. Screen video whose decode matrix matches passes through unchanged"
+link = ""
+
+[[xfail]]
+case = "export/basic/colour-red/mp430/*"
+class = "colour-matrix"
+reason = "NEW: same root cause as colour-level (BT.601 coefficients in an export tagged BT.709): background (220,40,40) decodes Cb about 9 code values low"
+link = ""
diff --git a/crates/verify/tests/audio.rs b/crates/verify/tests/audio.rs
index 53bc96ef3..f4e30e29c 100644
--- a/crates/verify/tests/audio.rs
+++ b/crates/verify/tests/audio.rs
@@ -138,7 +138,16 @@ const FPS: u32 = 30;
const RES: (u32, u32) = (320, 180);
fn export_case(spec: &FixtureSpec, variant: &Variant, path: ExportPath) -> Option<String> {
- let id = format!("audio/{}/{}/{}{FPS}", spec.name, variant.edit, path.label());
+ export_case_at(spec, variant, path, FPS)
+}
+
+fn export_case_at(
+ spec: &FixtureSpec,
+ variant: &Variant,
+ path: ExportPath,
+ fps: u32,
+) -> Option<String> {
+ let id = format!("audio/{}/{}/{}{fps}", spec.name, variant.edit, path.label());
if !report::selected(&id) {
return None;
}
@@ -152,7 +161,7 @@ fn export_case(spec: &FixtureSpec, variant: &Variant, path: ExportPath) -> Optio
&project,
config.clone(),
path,
- FPS,
+ fps,
RES,
dir.path(),
)) {
@@ -176,9 +185,9 @@ fn export_case(spec: &FixtureSpec, variant: &Variant, path: ExportPath) -> Optio
let report = audio_support::check_pcm(&mut case, "export", &model, &mono);
let video = project.model(&config);
let frames =
- common::read_output(&out, Some(&|i| video.expect(i as u32, FPS)));
- common::check_sequence(&mut case, &video, &frames, FPS, true);
- audio_support::check_av(&mut case, &project.meta, &report, &frames, FPS);
+ common::read_output(&out, Some(&|i| video.expect(i as u32, fps)));
+ common::check_sequence(&mut case, &video, &frames, fps, true);
+ audio_support::check_av(&mut case, &project.meta, &report, &frames, fps);
}
}
}
@@ -206,6 +215,143 @@ fn export_mp4() {
);
}
+/// Studio Sound under timeline music at 10 fps (`cap export --fps 10`).
+/// Music sends the export through the editor's `AudioRenderer` instead of
+/// the streaming mixer, and at 10 fps every video frame asks it for 4800
+/// samples: more than one 4096-sample Studio Sound block, so the blocks
+/// after the first in a request must line up too.
+#[test]
+fn export_studio_sound_low_fps() {
+ let failures: Vec<String> = export_case_at(
+ &audio_fixture::mix(report::tier()),
+ &Variant {
+ edit: "studio-sound-music",
+ apply: |config| {
+ studio_sound(config);
+ audio_fixture::add_music(config, 1.0, 7.0, 0.5, -6.0);
+ },
+ },
+ ExportPath::App,
+ 10,
+ )
+ .into_iter()
+ .collect();
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+/// Full decode of audio recorded at another rate than 48 kHz (44.1 kHz USB
+/// microphones are common): the resampler's buffered tail must be flushed,
+/// so the decoded track lasts exactly as long as the source, its last
+/// milliseconds still carry the signal, and every sample sits at its time.
+#[test]
+fn resampled_decode_tail() {
+ const TONE_HZ: f64 = 1000.0;
+ const AMPLITUDE: f64 = 0.5;
+ let mut failures = Vec::new();
+ for rate in [44_100u32, 32_000] {
+ let id = format!("audio/decode/resample-{rate}/tail");
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut case = Case::new(&id);
+ let dir = common::scratch_dir(&id);
+ let path = dir.path().join("tone.wav");
+ let frames = rate as usize;
+ let tone: Vec<i16> = (0..frames)
+ .map(|n| {
+ let t = n as f64 / f64::from(rate);
+ (AMPLITUDE * (2.0 * std::f64::consts::PI * TONE_HZ * t).sin() * 32767.0).round()
+ as i16
+ })
+ .collect();
+ write_wav_mono(&path, rate, &tone);
+ match cap_audio::AudioData::from_file(&path) {
+ Err(e) => case.problem("error", format!("decode: {e}")),
+ Ok(data) => {
+ let channels = usize::from(data.channels());
+ let mono: Vec<f64> = data
+ .samples()
+ .chunks(channels)
+ .map(|c| f64::from(c[0]))
+ .collect();
+ let expected_len = frames * 48_000 / rate as usize;
+ if mono.len().abs_diff(expected_len) > 2 {
+ case.problem(
+ "duration",
+ format!(
+ "decoded {} samples at 48 kHz, the {frames}-sample {rate} Hz source lasts {expected_len} ({:+.2} ms)",
+ mono.len(),
+ (mono.len() as f64 - expected_len as f64) / 48.0
+ ),
+ );
+ }
+ let ideal = |m: usize| {
+ AMPLITUDE * (2.0 * std::f64::consts::PI * TONE_HZ * m as f64 / 48_000.0).sin()
+ };
+ let worst = (4_800..mono.len().min(expected_len).saturating_sub(4_800))
+ .map(|m| ((mono[m] - ideal(m)).abs(), m))
+ .max_by(|a, b| a.0.total_cmp(&b.0));
+ if let Some((error, m)) = worst
+ && error > 0.02
+ {
+ case.problem(
+ "timing",
+ format!(
+ "sample {m} ({:.3} s) is {error:.3} away from the source tone at that time",
+ m as f64 / 48_000.0
+ ),
+ );
+ }
+ let tail = 240.min(mono.len());
+ let rms = (mono[mono.len() - tail..].iter().map(|v| v * v).sum::<f64>()
+ / tail.max(1) as f64)
+ .sqrt();
+ let tone_rms = AMPLITUDE / std::f64::consts::SQRT_2;
+ if rms < 0.6 * tone_rms {
+ case.problem(
+ "duration",
+ format!(
+ "the last 5 ms are {:.1} dB below the tone (rms {rms:.3}, tone {tone_rms:.3})",
+ 20.0 * (rms / tone_rms).log10()
+ ),
+ );
+ }
+ case.note(format!(
+ "{} samples (expected {expected_len}), worst interior error {:.4}, tail rms {rms:.3}",
+ mono.len(),
+ worst.map_or(0.0, |w| w.0)
+ ));
+ }
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+/// A 16-bit PCM mono WAV file.
+fn write_wav_mono(path: &std::path::Path, rate: u32, samples: &[i16]) {
+ let data_len = (samples.len() * 2) as u32;
+ let mut bytes = Vec::with_capacity(44 + data_len as usize);
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(36 + data_len).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16u32.to_le_bytes());
+ bytes.extend_from_slice(&1u16.to_le_bytes());
+ bytes.extend_from_slice(&1u16.to_le_bytes());
+ bytes.extend_from_slice(&rate.to_le_bytes());
+ bytes.extend_from_slice(&(rate * 2).to_le_bytes());
+ bytes.extend_from_slice(&2u16.to_le_bytes());
+ bytes.extend_from_slice(&16u16.to_le_bytes());
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&data_len.to_le_bytes());
+ for s in samples {
+ bytes.extend_from_slice(&s.to_le_bytes());
+ }
+ std::fs::write(path, bytes).expect("write wav");
+}
+
#[test]
fn export_other_formats() {
run_exports(
diff --git a/crates/verify/tests/captions.rs b/crates/verify/tests/captions.rs
index 9c97cb9b1..026256ba9 100644
--- a/crates/verify/tests/captions.rs
+++ b/crates/verify/tests/captions.rs
@@ -594,6 +594,86 @@ fn projection_all() {
);
}
+/// Fullscreen text holds placed exactly where captions end or start (as when
+/// a text card is snapped to a caption): a caption ending exactly at a hold
+/// ends before it, one starting there starts after it, also when an earlier
+/// hold has already moved the boundary.
+#[test]
+fn projection_hold_boundaries() {
+ let id = "captions/projection/hold-boundaries";
+ if !report::selected(id) {
+ return;
+ }
+ let mut case = Case::new(id);
+ let durations = [6.0];
+ let mut config = edits::base_config(&durations);
+ {
+ let timeline = config.timeline.as_mut().expect("timeline");
+ // Output time; the second hold starts at gapless 4.0 s.
+ timeline
+ .text_segments
+ .push(edits::fullscreen_text(2.0, 3.0));
+ timeline
+ .text_segments
+ .push(edits::fullscreen_text(5.0, 5.5));
+ }
+ let word = |text: &str, start: f32, end: f32| CaptionWord {
+ text: text.into(),
+ start,
+ end,
+ };
+ let captions = vec![
+ CaptionSegment {
+ id: "ends-at-hold".into(),
+ start: 1.0,
+ end: 2.0,
+ text: "apple river".into(),
+ words: vec![word("apple", 1.0, 1.5), word("river", 1.5, 2.0)],
+ },
+ CaptionSegment {
+ id: "starts-at-hold".into(),
+ start: 2.0,
+ end: 3.0,
+ text: "cloud stone".into(),
+ words: vec![word("cloud", 2.0, 2.5), word("stone", 2.5, 3.0)],
+ },
+ CaptionSegment {
+ id: "text-only-ends-at-second-hold".into(),
+ start: 3.5,
+ end: 4.0,
+ text: "maple tiger".into(),
+ words: Vec::new(),
+ },
+ ];
+ set_captions(&mut config, captions.clone(), true);
+ cap_project::synchronize_captions(&mut config, &durations);
+ let model = model_project(&captions, &config, &durations);
+ let product = &edits::timeline(&config).caption_segments;
+ let mut problems = compare_track(product, &model);
+ // The documented outcome, written out: the model must agree with it.
+ for (id, start, end) in [
+ ("ends-at-hold", 1.0, 2.0),
+ ("starts-at-hold", 3.0, 4.0),
+ ("text-only-ends-at-second-hold", 4.5, 5.0),
+ ] {
+ if !model
+ .iter()
+ .any(|p| p.id == id && close(p.start, start) && close(p.end, end))
+ {
+ problems.push(format!("model has no piece {id} {start:.1}-{end:.1}"));
+ }
+ }
+ if problems.is_empty() {
+ case.note(format!("{} pieces at hold boundaries", model.len()));
+ } else {
+ case.problem(
+ "caption-track",
+ format!("{} problems: {}", problems.len(), problems.join("; ")),
+ );
+ }
+ finish(case);
+}
+
fn track_as_captions(track: &[CaptionTrackSegment]) -> Vec<CaptionSegment> {
track
.iter()
@@ -1462,6 +1542,11 @@ struct RenderEdit {
/// Apply the edit after the caption track was projected, leaving the
/// stored track stale (the export must re-project it).
stale_track: bool,
+ /// Source captions for the recording's total length.
+ captions: fn(f64) -> Vec<CaptionSegment>,
+ /// Check frames that fall exactly on a caption start or end too. Only
+ /// for captions whose boundaries are exact in f32 and on the frame grid.
+ strict_edges: bool,
}
fn render_case(
@@ -1476,7 +1561,7 @@ fn render_case(
let project = common::project(&spec);
let mut case = Case::new(&id);
let durations = display_durations(&mut case, &project, &spec);
- let captions = scripted_captions(durations.iter().sum());
+ let captions = (edit.captions)(durations.iter().sum());
let mut config = project.config();
config.camera.hide = true;
if !edit.stale_track {
@@ -1528,7 +1613,7 @@ fn render_case(
let edge = pieces
.iter()
.any(|p| (t - p.start).abs() < 1e-3 || (t - p.visible_end()).abs() < 1e-3);
- if edge {
+ if edge && !edit.strict_edges {
continue;
}
checked += 1;
@@ -1591,6 +1676,8 @@ fn render_edits() -> Vec<RenderEdit> {
name: "full",
apply: |_| {},
stale_track: false,
+ captions: scripted_captions,
+ strict_edges: false,
},
RenderEdit {
name: "cuts-speeds-reorder",
@@ -1606,6 +1693,8 @@ fn render_edits() -> Vec<RenderEdit> {
)
},
stale_track: false,
+ captions: scripted_captions,
+ strict_edges: false,
},
RenderEdit {
name: "transition",
@@ -1614,15 +1703,63 @@ fn render_edits() -> Vec<RenderEdit> {
common::add_transition(c, 1, 0.4);
},
stale_track: false,
+ captions: scripted_captions,
+ strict_edges: false,
},
RenderEdit {
name: "stale-track",
apply: |c| common::set_cuts(c, &[(2.7, 6.0, 1.0), (0.0, 2.0, 1.0)]),
stale_track: true,
+ captions: scripted_captions,
+ strict_edges: false,
+ },
+ RenderEdit {
+ // Half speed: the third caption's stretched last word lasts
+ // 4.6 s on the output, so the renderer's 2.5 s word limit
+ // decides when it disappears.
+ name: "slow",
+ apply: |c| common::set_cuts(c, &[(0.0, 6.0, 0.5)]),
+ stale_track: false,
+ captions: scripted_captions,
+ strict_edges: false,
+ },
+ RenderEdit {
+ name: "back-to-back",
+ apply: |_| {},
+ stale_track: false,
+ captions: back_to_back_captions,
+ strict_edges: true,
},
]
}
+/// Captions that follow each other without a gap, every boundary on a half
+/// second (exact in f32 and on the 30 fps frame grid): on the frame where
+/// one caption ends the next one shows, and after the last one nothing.
+fn back_to_back_captions(total: f64) -> Vec<CaptionSegment> {
+ let mut captions = Vec::new();
+ let mut start = 0.5;
+ while start + 1.0 <= total - 0.5 && captions.len() < 5 {
+ let k = captions.len() * 2;
+ let words: Vec<CaptionWord> = (0..2)
+ .map(|i| CaptionWord {
+ text: WORDS[k + i].into(),
+ start: (start + 0.5 * i as f64) as f32,
+ end: (start + 0.5 * (i + 1) as f64) as f32,
+ })
+ .collect();
+ captions.push(CaptionSegment {
+ id: format!("segment-{}", captions.len()),
+ start: words[0].start,
+ end: words[1].end,
+ text: join_words(words.iter().map(|w| w.text.as_str())),
+ words,
+ });
+ start += 1.0;
+ }
+ captions
+}
+
#[test]
fn render_single_clip() {
let rt = common::runtime();
@@ -1643,6 +1780,8 @@ fn render_multi_clip() {
timeline.segments.reverse();
},
stale_track: true,
+ captions: scripted_captions,
+ strict_edges: false,
};
let failures: Vec<String> = render_case(catalog::multi_segment(report::tier()), &edit, &rt)
.into_iter()
diff --git a/crates/verify/tests/export.rs b/crates/verify/tests/export.rs
index 49097d561..1dc93d99f 100644
--- a/crates/verify/tests/export.rs
+++ b/crates/verify/tests/export.rs
@@ -688,3 +688,250 @@ fn uhd() {
);
common::assert_passed(failures);
}
+
+/// Fixed aspect ratios (Wide, Vertical, Square, Classic, Tall): the frame is
+/// the crop's longer side (relative to the aspect) with the other side
+/// derived from the aspect, rounded up to even numbers. It must hold the
+/// exact aspect-fit size (never smaller, or the picture is squeezed into a
+/// frame that is too small) and be at most 2 px larger on each side.
+#[test]
+fn aspect_frame_size() {
+ use cap_project::AspectRatio;
+ use cap_rendering::{ProjectUniforms, RenderOptions};
+ let id = "export/frame-size/aspect-ratios";
+ if !report::selected(id) {
+ return;
+ }
+ let mut case = Case::new(id);
+ let mut checked = 0;
+ let mut wrong = Vec::new();
+ for (w, h) in [
+ (1000u32, 700u32),
+ (1512, 982),
+ (1920, 1080),
+ (1081, 1919),
+ (333, 777),
+ (2559, 1599),
+ (1470, 956),
+ (3024, 1964),
+ ] {
+ for (aspect, ratio) in [
+ (AspectRatio::Wide, 16.0 / 9.0),
+ (AspectRatio::Vertical, 9.0 / 16.0),
+ (AspectRatio::Square, 1.0),
+ (AspectRatio::Classic, 4.0 / 3.0),
+ (AspectRatio::Tall, 3.0 / 4.0),
+ ] {
+ let mut config = cap_verify::fixture::verification_project_config();
+ config.aspect_ratio = Some(aspect.clone());
+ config.background.padding = 0.0;
+ config.background.crop = None;
+ let options = RenderOptions {
+ camera_size: None,
+ screen_size: cap_project::XY::new(w, h),
+ preserve_screen_alpha: false,
+ };
+ let (bw, bh) = ProjectUniforms::get_base_size(&options, &config);
+ let (fw, fh) = (f64::from(w), f64::from(h));
+ let (ew, eh) = if fw / fh > ratio {
+ (fw, fw / ratio)
+ } else {
+ (fh * ratio, fh)
+ };
+ checked += 1;
+ let fits = |got: u32, exact: f64| {
+ got % 2 == 0 && f64::from(got) >= exact - 1e-6 && f64::from(got) < exact + 2.0
+ };
+ if !fits(bw, ew) || !fits(bh, eh) {
+ wrong.push(format!(
+ "{w}x{h} at {aspect:?}: frame {bw}x{bh}, exact fit {ew:.2}x{eh:.2}"
+ ));
+ }
+ }
+ }
+ if wrong.is_empty() {
+ case.note(format!("{checked} crop sizes and aspect ratios"));
+ } else {
+ case.problem(
+ "frame-size",
+ format!(
+ "{} of {checked} frames are not the smallest even size holding the aspect fit: {}",
+ wrong.len(),
+ wrong[..wrong.len().min(4)].join("; ")
+ ),
+ );
+ }
+ common::finish(case);
+}
+
+#[derive(Clone, Copy, Debug)]
+struct MeasuredColour {
+ ycbcr: [f64; 3],
+ space: ffmpeg::util::color::Space,
+ range: ffmpeg::util::color::Range,
+}
+
+/// Measured minus expected (Y, Cb, Cr) code values for `rgb` encoded the way
+/// the stream's colour tag says (BT.709 unless tagged BT.601; limited range
+/// unless tagged full), the way players decode it.
+fn colour_error(colour: &MeasuredColour, rgb: [u8; 3]) -> [f64; 3] {
+ use ffmpeg::util::color::{Range, Space};
+ let [r, g, b] = rgb.map(|v| f64::from(v) / 255.0);
+ let (kr, kb) = if matches!(colour.space, Space::BT470BG | Space::SMPTE170M) {
+ (0.299, 0.114)
+ } else {
+ (0.2126, 0.0722)
+ };
+ let y = kr * r + (1.0 - kr - kb) * g + kb * b;
+ let (cb, cr) = ((b - y) / (2.0 * (1.0 - kb)), (r - y) / (2.0 * (1.0 - kr)));
+ let expected = if colour.range == Range::JPEG {
+ [255.0 * y, 128.0 + 255.0 * cb, 128.0 + 255.0 * cr]
+ } else {
+ [16.0 + 219.0 * y, 128.0 + 224.0 * cb, 128.0 + 224.0 * cr]
+ };
+ [0, 1, 2].map(|k| colour.ycbcr[k] - expected[k])
+}
+
+/// Mean code values and tag of a rectangle (fractions of the picture).
+fn rect_colour(
+ frame: &ffmpeg::frame::Video,
+ view: &impl cap_verify::video_code::PixelSource,
+ rect: [f64; 4],
+) -> Option<MeasuredColour> {
+ if !matches!(
+ frame.format(),
+ ffmpeg::format::Pixel::YUV420P | ffmpeg::format::Pixel::NV12
+ ) {
+ return None;
+ }
+ let (w, h) = (view.width() as f64, view.height() as f64);
+ let (x0, x1) = ((rect[0] * w) as usize, (rect[2] * w) as usize);
+ let (y0, y1) = ((rect[1] * h) as usize, (rect[3] * h) as usize);
+ let mut sum = [0.0; 3];
+ let mut n = 0.0;
+ for y in y0..y1.max(y0 + 1) {
+ for x in x0..x1.max(x0 + 1) {
+ let (cb, cr) = view.chroma(x, y);
+ sum[0] += view.luma(x, y);
+ sum[1] += cb + 128.0;
+ sum[2] += cr + 128.0;
+ n += 1.0;
+ }
+ }
+ Some(MeasuredColour {
+ ycbcr: sum.map(|v| v / n),
+ space: frame.color_space(),
+ range: frame.color_range(),
+ })
+}
+
+/// Allowed error of a flat background (code values): luma level, chroma.
+const COLOUR_LEVEL_TOLERANCE: f64 = 4.0;
+const COLOUR_MATRIX_TOLERANCE: f64 = 2.0;
+
+/// Colour fidelity of pixels the renderer generates in RGB (the background):
+/// a flat background must decode, under the stream's own colour tag (what
+/// players use), to the configured colour. Red separates BT.601 from BT.709
+/// (about 13 luma and 9 chroma code values apart); black and white sit at
+/// the ends of the limited range (Y 16 and 235, neutral chroma) under every
+/// matrix, so they pin the range independently of the matrix question.
+#[test]
+fn colour() {
+ use cap_project::BackgroundSource;
+ use cap_verify::media;
+ let spec = catalog::basic(report::tier());
+ let mut failures = Vec::new();
+ for (name, background) in [
+ ("colour-red", [220u8, 40, 40]),
+ ("colour-black", [0, 0, 0]),
+ ("colour-white", [255, 255, 255]),
+ ] {
+ let id = case_id(&spec.name, name, Format::Mp4, 30, Decoder::Default);
+ if !report::selected(&id) {
+ continue;
+ }
+ let project = common::project(&spec);
+ let mut config = project.config();
+ config.background.source = BackgroundSource::Color {
+ value: background.map(u16::from),
+ alpha: 255,
+ };
+ config.background.padding = 40.0;
+ let mut case = Case::new(&id);
+ let dir = common::scratch_dir(&id);
+ let run = ExportRun {
+ fps: 30,
+ resolution: RES,
+ format: Format::Mp4,
+ decoder: Decoder::Default,
+ };
+ let out = dir.path().join("a.mp4");
+ match common::runtime().block_on(common::export(&project, config, &run, &out)) {
+ Err(e) => case.problem("error", format!("export failed: {e}")),
+ Ok(path) => {
+ let mut errors = Vec::new();
+ let mut index = 0usize;
+ let decoded = media::decode_video(&path, |picture| {
+ let i = index;
+ index += 1;
+ if i % 10 != 0 {
+ return;
+ }
+ let view = picture.view();
+ if let Some(colour) =
+ rect_colour(&picture.frame, &view, [0.01, 0.01, 0.06, 0.06])
+ {
+ errors.push((i, colour_error(&colour, background), colour));
+ }
+ });
+ if let Err(e) = decoded {
+ case.problem("error", format!("decode: {e:?}"));
+ }
+ if errors.is_empty() {
+ case.problem("error", "no YUV frames to measure");
+ }
+ if let Some((i, [dy, _, _], colour)) = errors
+ .iter()
+ .find(|(_, e, _)| e[0].abs() > COLOUR_LEVEL_TOLERANCE)
+ {
+ case.problem(
+ "colour-level",
+ format!(
+ "background luma off by {dy:+.1} code values (Y {:.1}) for the stream's {:?} {:?} tag (frame {i})",
+ colour.ycbcr[0], colour.space, colour.range
+ ),
+ );
+ }
+ if let Some((i, [_, dcb, dcr], colour)) = errors
+ .iter()
+ .find(|(_, e, _)| e[1].abs().max(e[2].abs()) > COLOUR_MATRIX_TOLERANCE)
+ {
+ case.problem(
+ "colour-matrix",
+ format!(
+ "background chroma off by Cb {dcb:+.1} Cr {dcr:+.1} for the stream's {:?} tag (frame {i})",
+ colour.space
+ ),
+ );
+ }
+ if let Some((_, e, colour)) = errors.first() {
+ case.note(format!(
+ "frame 0: Y {:.1} Cb {:.1} Cr {:.1} ({:?} {:?}), error {:+.1} {:+.1} {:+.1}",
+ colour.ycbcr[0],
+ colour.ycbcr[1],
+ colour.ycbcr[2],
+ colour.space,
+ colour.range,
+ e[0],
+ e[1],
+ e[2]
+ ));
+ }
+ }
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ common::assert_passed(failures);
+}