From 13d281b9578c8c30d864d85f6ced4b8f359b03ca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:40:05 -0500 Subject: [PATCH] media: route software MP4/H.264 through craft-video and craft-media-source (#3970) * media: route software MP4/H.264 through craft-video and craft-media-source (#781) * chore: bump craft-video to ad50e51 * fix(media): convert FrameRate::new args to i64 * media: bump craft-libs pin to ce9ff47 and add #781 B-frame acceptance tests * test(media): use h264_encoder() in h264 b-frame test * chore: repin craft-video and craft-media to craft-libs main --- Cargo.lock | 113 +++++- Cargo.toml | 12 +- crates/media/Cargo.toml | 7 +- crates/media/src/convert.rs | 159 ++++---- crates/media/src/lib.rs | 13 + crates/media/src/mp4_h264.rs | 597 +++++++++++++++++++++++++++++++ crates/media/src/pool.rs | 38 +- crates/media/src/probe.rs | 64 +++- crates/media/src/stream.rs | 135 ++++++- crates/media/tests/it/footage.rs | 71 ++++ 10 files changed, 1095 insertions(+), 114 deletions(-) create mode 100644 crates/media/src/mp4_h264.rs diff --git a/Cargo.lock b/Cargo.lock index 3626bf564..6b0dd869b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1207,9 +1207,9 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", "thiserror 2.0.21", ] @@ -1237,6 +1237,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-audio" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031#ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", + "thiserror 2.0.21", +] + [[package]] name = "craft-cfb" version = "0.1.0" @@ -1261,6 +1270,22 @@ name = "craft-codepage" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +[[package]] +name = "craft-color" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-color" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031#ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" +dependencies = [ + "serde", +] + [[package]] name = "craft-doc" version = "0.1.0" @@ -1328,6 +1353,28 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +[[package]] +name = "craft-frame" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +dependencies = [ + "craft-color 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "rayon", + "serde", +] + +[[package]] +name = "craft-frame" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031#ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" +dependencies = [ + "craft-color 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", + "rayon", + "serde", +] + [[package]] name = "craft-gif" version = "0.1.0" @@ -1394,7 +1441,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9 [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" dependencies = [ "thiserror 2.0.21", ] @@ -1416,6 +1463,28 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031#ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-media-source" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +dependencies = [ + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-color 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-frame 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-mesh" version = "0.1.0" @@ -1545,6 +1614,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-time" version = "0.1.0" @@ -1563,6 +1641,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031#ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-timeline" version = "0.1.0" @@ -1652,9 +1739,10 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "rav1e", "rayon", "thiserror 2.0.21", ] @@ -2100,11 +2188,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", "craft-exr", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2266,12 +2354,17 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", + "craft-color 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-exr", + "craft-frame 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media-source", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ce9ff474b763408f1c0dbbe1aef9a2f6b8360031)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", "craft-webp", "effectcraft-color", "effectcraft-effects", diff --git a/Cargo.toml b/Cargo.toml index 84926a587..62060c612 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,10 +95,14 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg"] same-file = "1.0" tempfile = "3.27" -# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["isobmff", "matroska"] } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode", "opus-encode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync. +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce9ff474b763408f1c0dbbe1aef9a2f6b8360031" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce9ff474b763408f1c0dbbe1aef9a2f6b8360031", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 7e2f14170..39ad32f14 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -27,8 +27,13 @@ craft-dpx = { workspace = true } craft-exr = { workspace = true, features = ["decode"] } craft-gif = { workspace = true, features = ["frames"] } craft-webp = { workspace = true, features = ["frames"] } -craft-audio = { workspace = true, features = ["aac-decode"] } +craft-audio = { workspace = true, features = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-color = { workspace = true } +craft-frame = { workspace = true } craft-media = { workspace = true, features = ["mpegts"] } +craft-media-source = { workspace = true } +craft-time = { workspace = true } +craft-video = { workspace = true, features = ["h264-decode", "threads"] } filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index 86fb088f9..bf83a9650 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -63,15 +63,88 @@ impl AlphaOp { } } +/// Borrowed frame view so both `craft_frame::VideoFrame` and `filmcraft_frame::VideoFrame` +/// convert through the same pixel pipeline without copying. +pub(crate) enum PixelsRef<'a> { + Rgba8(&'a [u8]), + RgbaF32(&'a [f32]), + Yuv8 { planes: [&'a [u8]; 3], chroma: Chroma, alpha: Option<&'a [u8]> }, + Yuv16 { planes: [&'a [u16]; 3], chroma: Chroma, bits: u32, alpha: Option<&'a [u16]> }, +} + +pub(crate) struct FrameView<'a> { + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) data: PixelsRef<'a>, + pub(crate) matrix: Matrix, + pub(crate) range: Range, +} + +impl<'a> From<&'a VideoFrame> for FrameView<'a> { + fn from(f: &'a VideoFrame) -> Self { + let data = match &f.data { + PixelData::Rgba8(d) => PixelsRef::Rgba8(d), + PixelData::RgbaF32(d) => PixelsRef::RgbaF32(d), + PixelData::Yuv8 { planes, chroma, alpha } => { + PixelsRef::Yuv8 { planes: [&planes[0], &planes[1], &planes[2]], chroma: *chroma, alpha: alpha.as_deref().map(|a| &a[..]) } + } + PixelData::Yuv16 { planes, chroma, bits, alpha } => { + PixelsRef::Yuv16 { planes: [&planes[0], &planes[1], &planes[2]], chroma: *chroma, bits: *bits, alpha: alpha.as_deref().map(|a| &a[..]) } + } + }; + FrameView { width: f.width, height: f.height, data, matrix: f.color.matrix, range: f.color.range } + } +} + +impl<'a> From<&'a craft_frame::VideoFrame> for FrameView<'a> { + fn from(f: &'a craft_frame::VideoFrame) -> Self { + let chroma = |c: craft_frame::Chroma| match c { + craft_frame::Chroma::C420 => Chroma::C420, + craft_frame::Chroma::C422 => Chroma::C422, + craft_frame::Chroma::C444 => Chroma::C444, + }; + let data = match &f.data { + craft_frame::PixelData::Rgba8(d) => PixelsRef::Rgba8(d), + craft_frame::PixelData::RgbaF32(d) => PixelsRef::RgbaF32(d), + craft_frame::PixelData::Yuv8 { planes, chroma: c, alpha } => { + PixelsRef::Yuv8 { planes: [&planes[0], &planes[1], &planes[2]], chroma: chroma(*c), alpha: alpha.as_deref().map(|a| &a[..]) } + } + craft_frame::PixelData::Yuv16 { planes, chroma: c, bits, alpha } => { + PixelsRef::Yuv16 { planes: [&planes[0], &planes[1], &planes[2]], chroma: chroma(*c), bits: *bits, alpha: alpha.as_deref().map(|a| &a[..]) } + } + }; + let matrix = match f.color.matrix { + craft_color::Matrix::Bt601 => Matrix::Bt601, + craft_color::Matrix::Bt709 => Matrix::Bt709, + craft_color::Matrix::Bt2020Ncl => Matrix::Bt2020Ncl, + }; + let range = match f.color.range { + craft_color::Range::Limited => Range::Limited, + craft_color::Range::Full => Range::Full, + }; + FrameView { width: f.width, height: f.height, data, matrix, range } + } +} + +impl<'a> From<&'a crate::stream::DecodedFrame> for FrameView<'a> { + fn from(f: &'a crate::stream::DecodedFrame) -> Self { + match f { + crate::stream::DecodedFrame::Craft(frame) => FrameView::from(&**frame), + crate::stream::DecodedFrame::Film(frame) => FrameView::from(&**frame), + } + } +} + /// Convert a FilmCraft frame to an [`Image`]. #[cfg(test)] pub(crate) fn frame_to_image(f: &VideoFrame, op: AlphaOp) -> Image { frame_to_image_in(f, op, Vec::new()) } -/// Convert a FilmCraft frame to an [`Image`], reusing `buf`'s allocation when it is large enough +/// Convert a decoded frame to an [`Image`], reusing `buf`'s allocation when it is large enough /// (every pixel is overwritten, so a recycled frame's contents do not matter). -pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) -> Image { +pub(crate) fn frame_to_image_in<'a>(f: impl Into>, op: AlphaOp, mut buf: Vec) -> Image { + let f = f.into(); let (w, h) = (f.width as usize, f.height as usize); if buf.len() != w * h { buf = vec![[0.0; 4]; w * h]; @@ -80,9 +153,9 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - if w == 0 || h == 0 { return img; } - match &f.data { - PixelData::Rgba8(d) => convert_rgba8(&mut img.data, d, w, op, |p| p), - PixelData::RgbaF32(d) => { + match f.data { + PixelsRef::Rgba8(d) => convert_rgba8(&mut img.data, d, w, op, |p| p), + PixelsRef::RgbaF32(d) => { // linear premultiplied → encoded premultiplied img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { let src = &d[y * w * 4..(y + 1) * w * 4]; @@ -94,39 +167,15 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - } }); } - PixelData::Yuv8 { planes, chroma, alpha } => { - let yuv = Yuv::new(f.color.matrix, f.color.range, 8); + PixelsRef::Yuv8 { planes, chroma, alpha } => { + let yuv = Yuv::new(f.matrix, f.range, 8); let amax = 255.0; - convert_yuv( - &mut img.data, - YuvSource { - size: (w, h), - chroma: *chroma, - planes: [&planes[0][..], &planes[1][..], &planes[2][..]], - alpha: alpha.as_deref().map(|a| &a[..]), - amax, - }, - &yuv, - op, - |p| p, - ); + convert_yuv(&mut img.data, YuvSource { size: (w, h), chroma, planes, alpha, amax }, &yuv, op, |p| p); } - PixelData::Yuv16 { planes, chroma, bits, alpha } => { - let yuv = Yuv::new(f.color.matrix, f.color.range, *bits); - let amax = ((1u32 << *bits) - 1) as f32; - convert_yuv( - &mut img.data, - YuvSource { - size: (w, h), - chroma: *chroma, - planes: [&planes[0][..], &planes[1][..], &planes[2][..]], - alpha: alpha.as_deref().map(|a| &a[..]), - amax, - }, - &yuv, - op, - |p| p, - ); + PixelsRef::Yuv16 { planes, chroma, bits, alpha } => { + let yuv = Yuv::new(f.matrix, f.range, bits); + let amax = ((1u32 << bits) - 1) as f32; + convert_yuv(&mut img.data, YuvSource { size: (w, h), chroma, planes, alpha, amax }, &yuv, op, |p| p); } } img @@ -136,26 +185,17 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - /// ([`effectcraft_raster::quantize_px`]), kept as the 8-bit levels: expanded with /// [`effectcraft_raster::expand_u8`] it is that quantised image to the bit, in a quarter of /// the memory. `None` for frames with more than 8 bits (10/12-bit Y'CbCr, float). -pub(crate) fn frame_to_rgba8(f: &VideoFrame, op: AlphaOp) -> Option { +pub(crate) fn frame_to_rgba8<'a>(f: impl Into>, op: AlphaOp) -> Option { + let f = f.into(); let (w, h) = (f.width as usize, f.height as usize); let mut px = vec![[0u8; 4]; w * h]; if w > 0 && h > 0 { - match &f.data { - PixelData::Rgba8(d) => convert_rgba8(&mut px, d, w, op, quantize_px_u8), - PixelData::Yuv8 { planes, chroma, alpha } => convert_yuv( - &mut px, - YuvSource { - size: (w, h), - chroma: *chroma, - planes: [&planes[0][..], &planes[1][..], &planes[2][..]], - alpha: alpha.as_deref().map(|a| &a[..]), - amax: 255.0, - }, - &Yuv::new(f.color.matrix, f.color.range, 8), - op, - quantize_px_u8, - ), - PixelData::RgbaF32(_) | PixelData::Yuv16 { .. } => return None, + match f.data { + PixelsRef::Rgba8(d) => convert_rgba8(&mut px, d, w, op, quantize_px_u8), + PixelsRef::Yuv8 { planes, chroma, alpha } => { + convert_yuv(&mut px, YuvSource { size: (w, h), chroma, planes, alpha, amax: 255.0 }, &Yuv::new(f.matrix, f.range, 8), op, quantize_px_u8) + } + PixelsRef::RgbaF32(_) | PixelsRef::Yuv16 { .. } => return None, } } Some(Frame8 { width: f.width, height: f.height, rgba: px.into_flattened() }) @@ -204,18 +244,15 @@ pub(crate) fn turned(img: Image, turn: image::metadata::Orientation) -> Image { /// pixels get), then resampled the rest of the way. Conversion is linear until it clips, so /// this is the RGB box filter `resample` starts with, except in blocks where some colours clip. /// `None` for other frames. -pub(crate) fn frame_to_image_scaled(f: &VideoFrame, w: u32, h: u32) -> Option { +pub(crate) fn frame_to_image_scaled<'a>(f: impl Into>, w: u32, h: u32) -> Option { + let f = f.into(); let (fw, fh) = (f.width as usize, f.height as usize); if w == 0 || h == 0 || fw % 2 != 0 || fh % 2 != 0 || (w as usize).saturating_mul(2) > fw || (h as usize).saturating_mul(2) > fh { return None; } - let half = match &f.data { - PixelData::Yuv8 { planes, chroma: Chroma::C420, alpha: None } => { - half_420(fw, fh, [&planes[0][..], &planes[1][..], &planes[2][..]], &Yuv::new(f.color.matrix, f.color.range, 8))? - } - PixelData::Yuv16 { planes, chroma: Chroma::C420, bits, alpha: None } => { - half_420(fw, fh, [&planes[0][..], &planes[1][..], &planes[2][..]], &Yuv::new(f.color.matrix, f.color.range, *bits))? - } + let half = match f.data { + PixelsRef::Yuv8 { planes, chroma: Chroma::C420, alpha: None } => half_420(fw, fh, planes, &Yuv::new(f.matrix, f.range, 8))?, + PixelsRef::Yuv16 { planes, chroma: Chroma::C420, bits, alpha: None } => half_420(fw, fh, planes, &Yuv::new(f.matrix, f.range, bits))?, _ => return None, }; Some(if (half.width, half.height) == (w, h) { half } else { effectcraft_raster::resample(&half, w, h) }) diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 2f9087fff..4f337c0bf 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -26,6 +26,7 @@ mod exr_read; mod gif_anim; mod layered; mod localize; +mod mp4_h264; pub use layered::vector_doc; mod pool; mod probe; @@ -67,6 +68,18 @@ impl From for MediaError { } } +impl From for MediaError { + fn from(e: craft_media_source::MediaError) -> Self { + use craft_media_source::MediaError as C; + match e { + C::Unsupported(s) => MediaError::Unsupported(s), + C::Io(s) | C::Offline(s) => MediaError::Io(s), + C::Cancelled => MediaError::Cancelled, + other => MediaError::Decode(other.to_string()), + } + } +} + /// File extensions recognised as stills. pub const STILL_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"]; diff --git a/crates/media/src/mp4_h264.rs b/crates/media/src/mp4_h264.rs new file mode 100644 index 000000000..456fcd92b --- /dev/null +++ b/crates/media/src/mp4_h264.rs @@ -0,0 +1,597 @@ +//! Software MP4/MOV H.264 route backed by `craft-media`, `craft-video`, `craft-audio`, and +//! `craft-media-source`. +//! +//! Preserves sync-sample backward seek, B-frame reordering, cooperative cancellation, VUI + +//! container colour resolution, draft mode for reduced-resolution playback, and bounded worker +//! threads. + +use std::sync::{Arc, Mutex}; + +use craft_audio::{AudioBuffer, TrackDecoder as AudioTrackDecoder}; +use craft_color::{ColorInfo, Matrix, Primaries, Range, Transfer}; +use craft_frame::{Chroma, PixelData, VideoFrame}; +use craft_media::isobmff::{self, Mp4File, Track, TrackKind}; +use craft_media::{ByteSource, CodecId}; +use craft_media_source::{ + AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo, +}; +use craft_time::{FrameRate, Tick}; +use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame}; +use craft_video::{TrackDecoder, TrackDecoderOptions}; + +/// Maximum worker threads per `TrackDecoder` instance. +const MAX_WORKERS: usize = 8; + +/// Maximum decoded frames retained in the per-source GOP window cache. +const MAX_CACHED_FRAMES: usize = 32; + +/// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`. +const AUDIO_LOOKAHEAD: usize = 8; + +fn worker_cap() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) +} + +/// True when `head` begins with a plausible ISO-BMFF top-level box. +fn looks_like_isobmff(head: &[u8]) -> bool { + if head.len() < 8 { + return false; + } + matches!(&head[4..8], b"ftyp" | b"moov" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" | b"uuid") +} + +/// Open an in-place MP4/MOV H.264 source via `craft-media` / `craft-video`. +/// Returns `None` when the file is not ISO-BMFF, has no H.264 video track, or has an audio track +/// whose codec is not yet handled by `craft-audio`. +pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option> { + if !looks_like_isobmff(head) { + return None; + } + open_byte_source(name, reader.clone()) +} + +/// Open an in-memory MP4/MOV H.264 source via `craft-media` / `craft-video`. +pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { + if !looks_like_isobmff(&bytes) { + return None; + } + open_byte_source(name, Arc::new(bytes)) +} + +fn open_byte_source(name: &str, source: SharedBytes) -> Option> { + let file = isobmff::open(source.clone()).ok()?; + let video_idx = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0)?; + let video_track = &file.tracks[video_idx]; + let video_params = video_track.codec_params(); + if video_params.codec != CodecId::H264 { + return None; + } + + // Collect playable audio tracks and ensure `craft-audio` can decode every one of them. + let mut audio_tracks = Vec::new(); + let mut audio_infos = Vec::new(); + for (idx, track) in file.tracks.iter().enumerate() { + if audio_tracks.len() >= MAX_AUDIO_STREAMS { + break; + } + if track.kind != TrackKind::Audio || track.samples.is_empty() || track.entries.is_empty() || track.timescale == 0 { + continue; + } + let params = track.codec_params(); + let mut lookahead = Vec::with_capacity(AUDIO_LOOKAHEAD.min(track.samples.len())); + for s_idx in 0..AUDIO_LOOKAHEAD.min(track.samples.len()) { + let Ok(pkt) = file.read_sample(&*source, idx, s_idx) else { + return None; + }; + lookahead.push(pkt); + } + let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect(); + let Ok(dec) = AudioTrackDecoder::new(¶ms, &refs) else { + return None; + }; + let native_rate = dec.sample_rate().max(1); + let channels = u32::from(dec.layout().channels()).max(1); + audio_infos.push(AudioStreamInfo { + sample_rate: native_rate, + channels, + codec: params.codec.name().to_string(), + bits_per_sample: params.pcm.map(|p| u32::from(p.bits)), + }); + audio_tracks.push(AudioTrackEntry { + track_idx: idx, + native_rate, + state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: 0, buf: Vec::new() }), + }); + } + + let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) { + Ok(d) => d, + Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), + }; + + let container_color = video_track.video().and_then(|v| v.color.as_ref()).map(color_from_isobmff); + let color = container_color.unwrap_or(ColorInfo::REC709); + let (width, height) = video_track + .video() + .map(|v| (u32::from(v.width), u32::from(v.height))) + .filter(|&(w, h)| w > 0 && h > 0) + .unwrap_or((video_track.width, video_track.height)); + let par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1)); + let frame_rate = estimate_frame_rate(video_track); + let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale)); + let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); + + let info = MediaInfo { + name: name.to_string(), + kind: MediaKind::Movie, + duration, + video: Some(VideoStreamInfo { + width, + height, + frame_rate, + par, + codec: "H.264".to_string(), + pixel_format: "yuv420p".to_string(), + color, + has_alpha: false, + bitrate, + hdr: None, + }), + audio_streams: audio_infos, + container: "mp4".to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(Mp4H264Source { + info, + source, + file, + video_track_idx: video_idx, + container_color, + par, + video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), + audio_tracks, + }))) +} + +struct CachedFrame { + pts: i64, + frame: Arc, +} + +struct VideoState { + decoder: TrackDecoder, + next_decode_idx: usize, + gop_start_idx: usize, + flushed: bool, + decoded: Vec, +} + +struct AudioTrackState { + decoder: AudioTrackDecoder, + next_sample: usize, + /// Sample index (in native-rate frames) of `buf[0]` relative to track start (0). + decoded_pos: i64, + /// Interleaved or planar? Planar: one `Vec` per channel. + buf: Vec>, +} + +struct AudioTrackEntry { + track_idx: usize, + native_rate: u32, + state: Mutex, +} + +struct Mp4H264Source { + info: MediaInfo, + source: SharedBytes, + file: Mp4File, + video_track_idx: usize, + container_color: Option, + par: (u32, u32), + video: Mutex, + audio_tracks: Vec, +} + +impl MediaSource for Mp4H264Source { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, req: FrameRequest) -> Result> { + let track = &self.file.tracks[self.video_track_idx]; + let t_track = tick_to_units(req.time, track.timescale); + let target_idx = track.sample_at_presentation_time(t_track).ok_or_else(|| MediaError::Decode("no video samples".into()))?; + let target_pts = track.samples[target_idx].pts; + + let mut state = self.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts) { + return Ok(hit.frame.clone()); + } + + let sync_idx = track.sync_sample_before(target_idx); + // Backward seek or jump to a later GOP: reset the decoder to the target sync sample. + if target_idx < state.next_decode_idx || sync_idx > state.gop_start_idx { + state.decoder.reset().map_err(|e| MediaError::Decode(e.to_string()))?; + state.decoded.clear(); + state.next_decode_idx = sync_idx; + state.gop_start_idx = sync_idx; + state.flushed = false; + } + + let want_draft = req.scale < 0.99; + if state.decoder.draft() != want_draft { + state.decoder.set_draft(want_draft); + } + + while !state.decoded.iter().any(|c| c.pts >= target_pts) { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + if state.next_decode_idx < track.samples.len() { + let idx = state.next_decode_idx; + let sample = track.samples[idx]; + let pkt = self.file.read_sample(&*self.source, self.video_track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?; + let frames = state.decoder.decode(&pkt, sample.pts).map_err(|e| MediaError::Decode(e.to_string()))?; + state.next_decode_idx = idx + 1; + push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?; + } else if !state.flushed { + let frames = state.decoder.flush().map_err(|e| MediaError::Decode(e.to_string()))?; + state.flushed = true; + push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?; + break; + } else { + break; + } + } + + if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts) { + return Ok(exact.frame.clone()); + } + // Fallback: latest decoded frame at or before target_pts, or earliest available. + let best = state + .decoded + .iter() + .filter(|c| c.pts <= target_pts) + .max_by_key(|c| c.pts) + .or_else(|| state.decoded.first()) + .ok_or_else(|| MediaError::Decode("H.264 decoder produced no frame".into()))?; + Ok(best.frame.clone()) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + self.audio_stream(0, start, frames, sample_rate) + } + + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + let entry = self.audio_tracks.get(stream).ok_or(MediaError::NoStream("audio"))?; + if sample_rate == 0 { + return Err(MediaError::Decode("invalid audio sample rate 0".into())); + } + let channels_count = self.info.audio_streams.get(stream).map_or(2, |s| s.channels as usize); + if frames == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, 0)); + } + + let native_rate = entry.native_rate; + let (native_start, native_frames) = if sample_rate == native_rate { + (start, frames) + } else { + let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate); + let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; + (i64::try_from(s0).unwrap_or(0), len) + }; + + let track = &self.file.tracks[entry.track_idx]; + let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let decoded = + decode_audio_range(&self.file, &*self.source, entry.track_idx, track, native_rate, channels_count, &mut state, native_start, native_frames)?; + + if sample_rate == native_rate { + return Ok(AudioBuffer { sample_rate, channels: decoded }); + } + + let mut resampled = vec![vec![0.0f32; frames]; channels_count]; + let ratio = f64::from(native_rate) / f64::from(sample_rate); + for (c, out_ch) in resampled.iter_mut().enumerate() { + let in_ch = &decoded[c]; + if in_ch.is_empty() { + continue; + } + for (i, dst) in out_ch.iter_mut().enumerate() { + let pos = i as f64 * ratio; + let idx = pos.floor() as usize; + let frac = (pos - idx as f64) as f32; + let s0 = in_ch.get(idx).copied().unwrap_or(0.0); + let s1 = in_ch.get(idx + 1).copied().unwrap_or(s0); + *dst = s0 + (s1 - s0) * frac; + } + } + Ok(AudioBuffer { sample_rate, channels: resampled }) + } +} + +#[allow(clippy::too_many_arguments)] +fn decode_audio_range( + file: &Mp4File, + source: &dyn ByteSource, + track_idx: usize, + track: &Track, + native_rate: u32, + channels_count: usize, + state: &mut AudioTrackState, + start: i64, + frames: usize, +) -> Result>> { + let mut out = vec![vec![0.0f32; frames]; channels_count]; + let end = start.saturating_add(frames as i64); + if end <= 0 { + return Ok(out); + } + + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + let buf_end = state.decoded_pos.saturating_add(buf_len); + if start < state.decoded_pos || start > buf_end + i64::from(native_rate) * 2 { + // Seek to the sample at or before `start` in track timescale. + let t_track = (i128::from(start.max(0)) * i128::from(track.timescale)) / i128::from(native_rate); + let sample_idx = track.sample_at_presentation_time(i64::try_from(t_track).unwrap_or(0)).unwrap_or(0); + // Back up a few packets for AAC/Opus overlap/preroll. + let seek_idx = sample_idx.saturating_sub(2); + state.decoder.reset(); + state.next_sample = seek_idx; + let sample_pts = track.presentation_pts(seek_idx).unwrap_or(0); + state.decoded_pos = i64::try_from((i128::from(sample_pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1))).unwrap_or(0); + for ch in &mut state.buf { + ch.clear(); + } + } + + if state.buf.len() != channels_count { + state.buf = vec![Vec::new(); channels_count]; + } + + while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end && state.next_sample < track.samples.len() { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + let idx = state.next_sample; + let pkt = file.read_sample(source, track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?; + state.next_sample = idx + 1; + let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; + for (c, ch) in state.buf.iter_mut().enumerate() { + if let Some(src_ch) = block.channels.get(c) { + ch.extend_from_slice(src_ch); + } + } + } + + let avail = state.buf.first().map_or(0, Vec::len); + for i in 0..frames { + let pos = start.saturating_add(i as i64); + if pos >= state.decoded_pos { + let off = (pos - state.decoded_pos) as usize; + if off < avail { + for (c, out_ch) in out.iter_mut().enumerate() { + out_ch[i] = state.buf[c][off]; + } + } + } + } + + // Trim already-consumed audio older than `end` minus a small safety margin. + let drop_to = (end - state.decoded_pos).max(0) as usize; + let trim = drop_to.min(avail); + if trim > 0 { + for ch in &mut state.buf { + ch.drain(..trim); + } + state.decoded_pos = state.decoded_pos.saturating_add(trim as i64); + } + + Ok(out) +} + +fn push_decoded( + cache: &mut Vec, + frames: Vec, + container_color: Option, + par: (u32, u32), + timescale: u32, + edit_offset: i64, +) -> Result<()> { + for vf in frames { + let pts = vf.pts.unwrap_or(0); + let frame = Arc::new(to_craft_frame(vf, container_color, par, timescale, edit_offset)?); + cache.push(CachedFrame { pts, frame }); + } + if cache.len() > MAX_CACHED_FRAMES { + let excess = cache.len() - MAX_CACHED_FRAMES; + cache.drain(..excess); + } + Ok(()) +} + +fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option, default_par: (u32, u32), timescale: u32, edit_offset: i64) -> Result { + let width = vf.width(); + let height = vf.height(); + let subsampling = vf.subsampling(); + let family = vf.family(); + let tags = vf.color; + let pts_units = vf.pts.unwrap_or(0).saturating_add(edit_offset); + let pts = Tick::from_units(pts_units, i64::from(timescale.max(1))); + let par = vf.sar.filter(|&(n, d)| n > 0 && d > 0).unwrap_or(default_par); + let color = resolve_color(tags, container_color); + let bit_depth = vf.bit_depth(); + let (planes, alpha) = vf.into_planes(); + + let data = match family { + ColorFamily::YCbCr => { + let chroma = match subsampling { + Subsampling::S420 => Chroma::C420, + Subsampling::S422 => Chroma::C422, + Subsampling::S444 => Chroma::C444, + _ => return Err(MediaError::Unsupported("unsupported YCbCr subsampling".into())), + }; + let mut iter = planes.into_iter(); + let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else { + return Err(MediaError::Decode("missing YUV planes".into())); + }; + if bit_depth <= 8 { + let y = Arc::new(plane_u8(y)?); + let cb = Arc::new(plane_u8(cb)?); + let cr = Arc::new(plane_u8(cr)?); + let a = alpha.map(plane_u8).transpose()?.map(Arc::new); + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a } + } else { + let y = Arc::new(plane_u16(y)?); + let cb = Arc::new(plane_u16(cb)?); + let cr = Arc::new(plane_u16(cr)?); + let a = alpha.map(plane_u16).transpose()?.map(Arc::new); + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a } + } + } + ColorFamily::Rgb | ColorFamily::Gray => return Err(MediaError::Unsupported("non-YCbCr H.264 pixel format".into())), + }; + + Ok(VideoFrame { width, height, data, color, par, pts }) +} + +fn plane_u8(p: Plane) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + match p.into_samples() { + Samples::U8(mut v) => { + if stride == w { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend_from_slice(&v[row..row + w]); + } + Ok(out) + } + Samples::U16(_) => Err(MediaError::Decode("expected 8-bit plane".into())), + } +} + +fn plane_u16(p: Plane) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + match p.into_samples() { + Samples::U16(mut v) => { + if stride == w { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend_from_slice(&v[row..row + w]); + } + Ok(out) + } + Samples::U8(_) => Err(MediaError::Decode("expected 16-bit plane".into())), + } +} + +fn resolve_color(vui: ColorTags, container: Option) -> ColorInfo { + let base = container.unwrap_or(ColorInfo::REC709); + let matrix = Matrix::from_code(vui.matrix).unwrap_or(base.matrix); + let transfer = Transfer::from_code(vui.transfer).unwrap_or(base.transfer); + let primaries = primaries_from_code(vui.primaries).unwrap_or(base.primaries); + let range = if vui.full_range { Range::Full } else { base.range }; + ColorInfo { matrix, transfer, primaries, range } +} + +fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo { + match c { + isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo { + matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: if *full_range { Range::Full } else { Range::Limited }, + }, + isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => ColorInfo { + matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: Range::Limited, + }, + isobmff::ColorInfo::Icc { .. } => ColorInfo::REC709, + } +} + +fn primaries_from_code(c: u8) -> Option { + match c { + 1 => Some(Primaries::Bt709), + 5 => Some(Primaries::Bt601_625), + 6 => Some(Primaries::Bt601_525), + 9 => Some(Primaries::Bt2020), + 11 | 12 => Some(Primaries::P3D65), + _ => None, + } +} + +fn tick_to_units(t: Tick, timescale: u32) -> i64 { + let v = (i128::from(t.0) * i128::from(timescale)) / i128::from(craft_time::TICKS_PER_SECOND); + i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) +} + +fn estimate_frame_rate(track: &Track) -> FrameRate { + let ts = i128::from(track.timescale); + if ts <= 0 || track.samples.is_empty() { + return FrameRate::FPS_30; + } + let mut durs: Vec = track.samples.iter().map(|s| s.duration).filter(|&d| d > 0).collect(); + if durs.is_empty() { + return FrameRate::FPS_30; + } + durs.sort_unstable(); + let median = durs[durs.len() / 2]; + for r in FrameRate::COMMON { + if ts * i128::from(r.den) == i128::from(median) * i128::from(r.num) { + return r; + } + } + let fps = track.timescale as f64 / f64::from(median); + FrameRate::COMMON + .into_iter() + .map(|r| (r, (fps / r.as_f64() - 1.0).abs())) + .filter(|&(_, off)| off <= 0.005) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(r, _)| r) + .unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn worker_cap_is_bounded() { + let cap = worker_cap(); + assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}"); + } + + #[test] + fn vui_overrides_container_color_and_falls_back_when_unspecified() { + let container = color_from_isobmff(&isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: false }); + assert_eq!(container.primaries, Primaries::Bt2020); + assert_eq!(container.transfer, Transfer::Pq); + assert_eq!(container.matrix, Matrix::Bt2020Ncl); + assert_eq!(container.range, Range::Limited); + + // Unspecified VUI (2) falls back to container color. + let resolved = resolve_color(ColorTags::UNSPECIFIED, Some(container)); + assert_eq!(resolved, container); + + // Explicit VUI overrides container color. + let vui = ColorTags { primaries: 1, transfer: 1, matrix: 1, full_range: true }; + let resolved = resolve_color(vui, Some(container)); + assert_eq!(resolved.primaries, Primaries::Bt709); + assert_eq!(resolved.transfer, Transfer::Bt709); + assert_eq!(resolved.matrix, Matrix::Bt709); + assert_eq!(resolved.range, Range::Full); + } +} diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index f6d11ba3c..7bb4ae78b 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -12,13 +12,13 @@ use effectcraft_render::disk_cache::Frame8; use effectcraft_render::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; use effectcraft_render::{FloatCurve, FootageSource}; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; -use filmcraft_media::{FrameRequest, SharedSource}; use image::metadata::Orientation; use crate::convert::{AlphaOp, dynamic_to_image, frame_to_image_in, frame_to_image_scaled, frame_to_rgba8, turned}; use crate::downmix::Order; use crate::gif_anim::{self, Anim}; use crate::reads; +use crate::stream::MediaSource; use crate::{MediaError, Result}; /// Default frame-cache budget: 1 GiB of decoded frames. @@ -560,7 +560,7 @@ type SourceSlot = Arc, ReadFile)>>; /// audio channels arrive in. #[derive(Clone)] struct Opened { - src: SharedSource, + src: MediaSource, turn: Orientation, order: Order, } @@ -568,7 +568,7 @@ struct Opened { impl Opened { /// `src` with what its container says: `header` is an MP4/MOV's ftyp and moov (or the whole /// file), `file` the file for other containers' AAC configuration. - fn new(src: SharedSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened { + fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened { let turn = header.map_or(Orientation::NoTransforms, crate::probe::video_turn); Opened { order: channel_order(&src, header, file), src, turn } } @@ -576,9 +576,11 @@ impl Opened { /// The order `src`'s audio channels decode in; multichannel AAC's by its configuration, where /// the container's header shows it ([`crate::aac::config`]). -fn channel_order(src: &SharedSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order { - match src.info().audio() { - Some(a) if a.codec.contains("AAC") && a.channels > 2 => crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc)), +fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order { + match src.primary_audio() { + Some((_, channels, codec)) if codec.contains("AAC") && channels > 2 => { + crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc)) + } _ => Order::Wav, } } @@ -1071,7 +1073,7 @@ impl MediaPool { let path: Arc = footage.path.as_str().into(); let Opened { src, order, .. } = self.inner.opened(&path).ok_or("the file can't be opened")?; let s0 = start.to_units_floor(rate as i64); - let native = src.info().audio().map_or(rate, |a| a.sample_rate); + let native = src.primary_audio().map_or(rate, |(sr, _, _)| sr); // The header's rate scales the samples read: 0xFFFFFFFF Hz made one conform chunk about // 47 GB (#2141). Real audio is 1–768 kHz. if native != 0 && !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&native) { @@ -1217,7 +1219,7 @@ impl Inner { let (bytes, read) = self.read_file(path); let opened = bytes.and_then(|bytes| { let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?; + let src = crate::stream::open_bytes(&name, bytes.clone())?; Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) }); (opened, read) @@ -1759,18 +1761,20 @@ impl Inner { } Some(mt) => { let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; - let vf = src - .video_frame(FrameRequest::full(filmcraft_time::Tick(mt.0))) - .map_err(MediaError::from) - .inspect_err(|e| self.note_problem(path, &footage.codec, e))?; // A movie shown turned a quarter (a phone held upright): the footage's size and // the render's are the turned picture's, the decoded frame's are the file's. let side = |(w, h): (u32, u32)| if crate::probe::swaps_sides(turn) { (h, w) } else { (w, h) }; // A reduced-resolution render's frame, made at its size (a frame of the footage's // own size only, as the renderer resamples only those). let (w, h) = side(loc.key.size); + let scale = if w > 0 && footage.width > 0 && footage.height > 0 && (w < footage.width || h < footage.height) { + (w as f32 / footage.width as f32).min(h as f32 / footage.height as f32) + } else { + 1.0 + }; + let vf = src.video_frame(mt, scale).inspect_err(|e| self.note_problem(path, &footage.codec, e))?; if w > 0 - && (vf.width, vf.height) == side((footage.width, footage.height)) + && (vf.width(), vf.height()) == side((footage.width, footage.height)) && let Some(img) = frame_to_image_scaled(&vf, w, h) { return Ok(f32(turned(img, turn))); @@ -1781,7 +1785,7 @@ impl Inner { { return Ok(Pixels::Q8(Arc::new(f))); } - let buf = lock(&self.cache).lru.take_spare(vf.width as usize * vf.height as usize); + let buf = lock(&self.cache).lru.take_spare(vf.width() as usize * vf.height() as usize); Ok(f32(turned(frame_to_image_in(&vf, op, buf), turn))) } } @@ -2005,15 +2009,15 @@ impl FootageSource for MediaPool { /// `frames` stereo sample frames (interleaved) of `src` from sample `s0` at `rate` Hz, which /// FilmCraft serves as decoded when it is the source's own rate. Mono is duplicated to both /// channels, multichannel sources (channels in `order`) are downmixed ([`crate::downmix`]); silence before the start. An error where decoding fails. -fn read_stereo(src: &SharedSource, order: &Order, s0: i64, frames: usize, rate: u32) -> std::result::Result, String> { +fn read_stereo(src: &MediaSource, order: &Order, s0: i64, frames: usize, rate: u32) -> std::result::Result, String> { let mut out = vec![0.0; frames * 2]; let skip = usize::try_from(s0.saturating_neg()).unwrap_or(0); if skip >= frames { return Ok(out); } - let buf = src.audio(s0.max(0), frames - skip, rate).map_err(|e| e.to_string())?; + let channels = src.audio(s0.max(0), frames - skip, rate)?; let Some(dst) = skip.checked_mul(2).and_then(|i| out.get_mut(i..)) else { return Ok(out) }; - crate::downmix::downmix_into(&buf.channels, order, dst); + crate::downmix::downmix_into(&channels, order, dst); Ok(out) } diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index cf62eb910..52a29a363 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -27,7 +27,7 @@ pub fn probe(path: impl AsRef) -> Result { let path = path.as_ref(); // A movie is read in place (its index), not loaded whole. if let Some(src) = crate::stream::probe_source(path) { - let mut f = footage_from_info(&path.to_string_lossy(), src?.info()); + let mut f = footage_from_source(&path.to_string_lossy(), &src?); let header = crate::stream::movie_header(path); let turn = header.as_deref().map_or(Orientation::NoTransforms, video_turn); turn_footage(&mut f, turn); @@ -134,8 +134,8 @@ pub fn probe_bytes(path: &str, bytes: Arc<[u8]>) -> Result { let shown = video_shown(&bytes); // A WAV's cue points and XMP markers become the footage's markers. let markers = crate::wav_markers::read(&bytes); - let src = filmcraft_codecs::open_bytes(&name, bytes)?; - let mut f = footage_from_info(path, src.info()); + let src = crate::stream::open_bytes(&name, bytes)?; + let mut f = footage_from_source(path, &src); f.markers = markers; turn_footage(&mut f, turn); correct_rate(&mut f, rate); @@ -190,6 +190,64 @@ fn turn_footage(f: &mut Footage, turn: Orientation) { } } +pub(crate) fn footage_from_source(path: &str, src: &crate::stream::MediaSource) -> Footage { + match src { + crate::stream::MediaSource::Craft(s) => footage_from_craft_info(path, s.info()), + crate::stream::MediaSource::Film(s) => footage_from_info(path, s.info()), + } +} + +pub(crate) fn footage_from_craft_info(path: &str, info: &craft_media_source::MediaInfo) -> Footage { + let v = info.video.as_ref(); + let kind = match (info.kind, v) { + (craft_media_source::MediaKind::Still, _) => FootageKind::Still, + (_, Some(_)) => FootageKind::Video, + (_, None) => FootageKind::Audio, + }; + let rate = v.map_or(FrameRate::FPS_30, |v| { + if v.frame_rate.num > 0 && v.frame_rate.den > 0 { FrameRate::new(v.frame_rate.num, v.frame_rate.den) } else { FrameRate::FPS_30 } + }); + let codec = match (v, info.audio()) { + (Some(v), _) => v.codec.clone(), + (None, Some(a)) => a.codec.clone(), + _ => String::new(), + }; + Footage { + path: path.to_string(), + kind, + width: v.map_or(0, |v| v.width), + height: v.map_or(0, |v| v.height), + pixel_aspect: v.map_or(1.0, |v| if v.par.1 > 0 { v.par.0 as f64 / v.par.1 as f64 } else { 1.0 }), + frame_rate: rate, + native_rate: None, + duration: if kind == FootageKind::Still { Tick::ZERO } else { Tick(info.duration.0) }, + has_video: v.is_some(), + has_audio: info.has_audio(), + alpha: if v.is_some_and(|v| v.has_alpha) { AlphaMode::Straight } else { AlphaMode::Ignore }, + premul_color: [0.0; 3], + loop_count: 1, + codec, + missing: false, + sequence: Vec::new(), + color_profile: v.and_then(|v| profile_of_craft(&v.color)), + file_timecode: v.and(info.start_timecode), + ..Default::default() + } +} + +fn profile_of_craft(c: &craft_color::ColorInfo) -> Option { + use craft_color::{Primaries, Transfer}; + use effectcraft_project::ColorSpace; + match (c.primaries, c.transfer) { + (Primaries::Bt2020, Transfer::Pq) => Some(ColorSpace::Rec2100Pq), + (Primaries::Bt2020, Transfer::Hlg) => Some(ColorSpace::Rec2100Hlg), + (Primaries::Bt2020, _) => Some(ColorSpace::Rec2020), + (Primaries::P3D65, _) => Some(ColorSpace::DisplayP3), + (_, Transfer::Bt709) => Some(ColorSpace::Rec709), + _ => None, + } +} + pub(crate) fn footage_from_info(path: &str, info: &filmcraft_media::MediaInfo) -> Footage { let v = info.video.as_ref(); let kind = match (info.kind, v) { diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 0155b4acd..5f81239f3 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -2,17 +2,83 @@ //! //! Reading a file whole before opening it made a clip cost its full size in memory (twice while //! probing: the file's bytes plus the demuxer's copy), so a 45-minute movie took gigabytes just to -//! import. FilmCraft's reader openers (MP4/MOV, Matroska/WebM, MXF, Ogg, MPEG-PS/TS) open from a -//! random-access [`ByteReader`]; [`FileReader`] serves them positional reads from the open file. +//! import. Reader openers (MP4/MOV, Matroska/WebM, MXF, Ogg, MPEG-PS/TS) open from a random-access +//! byte reader; [`FileReader`] serves them positional reads from the open file. //! Formats decoded in one go (stills, WAV, FLAC, MP3…) still read the whole file, as before. //! Builds without a native file system (wasm32) keep using in-memory bytes. use std::path::Path; +use std::sync::Arc; use effectcraft_render::reads::FileStamp; -use filmcraft_media::SharedSource; +use effectcraft_time::Tick; -use crate::Result; +use crate::{MediaError, Result}; + +/// A decoded video frame from either `craft-media-source` or `filmcraft-media`. +pub(crate) enum DecodedFrame { + Craft(Arc), + Film(Arc), +} + +impl DecodedFrame { + pub(crate) fn width(&self) -> u32 { + match self { + DecodedFrame::Craft(f) => f.width, + DecodedFrame::Film(f) => f.width, + } + } + + pub(crate) fn height(&self) -> u32 { + match self { + DecodedFrame::Craft(f) => f.height, + DecodedFrame::Film(f) => f.height, + } + } +} + +/// An opened movie/audio source, routed through `craft-media-source` for migrated formats +/// (currently software MP4/H.264) and `filmcraft-media` for remaining formats. +#[derive(Clone)] +pub(crate) enum MediaSource { + Craft(craft_media_source::SharedSource), + Film(filmcraft_media::SharedSource), +} + +impl MediaSource { + pub(crate) fn video_frame(&self, time: Tick, scale: f32) -> Result { + match self { + MediaSource::Craft(s) => { + s.video_frame(craft_media_source::FrameRequest { time: craft_time::Tick(time.0), scale }).map(DecodedFrame::Craft).map_err(MediaError::from) + } + MediaSource::Film(s) => { + s.video_frame(filmcraft_media::FrameRequest { time: filmcraft_time::Tick(time.0), scale }).map(DecodedFrame::Film).map_err(MediaError::from) + } + } + } + + pub(crate) fn audio(&self, start: i64, frames: usize, rate: u32) -> std::result::Result>, String> { + match self { + MediaSource::Craft(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()), + MediaSource::Film(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()), + } + } + + pub(crate) fn primary_audio(&self) -> Option<(u32, u32, String)> { + match self { + MediaSource::Craft(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())), + MediaSource::Film(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())), + } + } +} + +/// Open an in-memory movie/audio source, trying migrated `craft-media-source` routes first. +pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Result { + if let Some(res) = crate::mp4_h264::open_bytes(name, bytes.clone()) { + return res.map(MediaSource::Craft).map_err(MediaError::from); + } + filmcraft_codecs::open_bytes(name, bytes).map(MediaSource::Film).map_err(MediaError::from) +} /// A file on disk read in place: it stays open and only the requested ranges are read. #[cfg(any(unix, windows))] @@ -40,13 +106,13 @@ impl FileReader { } #[cfg(any(unix, windows))] -impl filmcraft_media::ByteReader for FileReader { - fn len(&self) -> u64 { +impl FileReader { + fn len_bytes(&self) -> u64 { self.len } /// Positional reads: threads decoding different parts of the file share no cursor. - fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + fn read_exact_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { #[cfg(unix)] { std::os::unix::fs::FileExt::read_exact_at(&self.file, buf, offset) @@ -70,6 +136,28 @@ impl filmcraft_media::ByteReader for FileReader { } } +#[cfg(any(unix, windows))] +impl filmcraft_media::ByteReader for FileReader { + fn len(&self) -> u64 { + self.len_bytes() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.read_exact_at(offset, buf) + } +} + +#[cfg(any(unix, windows))] +impl craft_media::ByteSource for FileReader { + fn len(&self) -> u64 { + self.len_bytes() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.read_exact_at(offset, buf) + } +} + #[cfg(any(unix, windows))] fn name_of(path: &Path) -> String { path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default() @@ -80,17 +168,24 @@ fn name_of(path: &Path) -> String { /// when the file can't be opened in place (the caller reads it whole, which reports the error). /// With the file's identity as opened. #[cfg(any(unix, windows))] -pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp)> { - let reader = FileReader::open(path).ok()?; +pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp)> { + let reader = Arc::new(FileReader::open(path).ok()?); let stamp = reader.stamp; - let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader); - let opened = filmcraft_media::reader::open_reader(&name_of(path), reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers()); - Some((opened.map_err(Into::into), stamp)) + let name = name_of(path); + let craft_reader: craft_media_source::SharedBytes = reader.clone(); + if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, craft_media_source::HEAD_LEN) + && let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) + { + return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp)); + } + let fc_reader: filmcraft_media::SharedReader = reader; + let opened = filmcraft_media::reader::open_reader(&name, fc_reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers()); + Some((opened.map(MediaSource::Film).map_err(MediaError::from), stamp)) } /// Without a native file system there is no in-place source: always `None`. #[cfg(not(any(unix, windows)))] -pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { +pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { None } @@ -160,23 +255,27 @@ pub(crate) fn movie_header(_path: &Path) -> Option> { /// handles and nothing probed before containers (stills, layered and vector documents, 3D models) /// claims it. `None`: probe the whole file's bytes as before. #[cfg(any(unix, windows))] -pub(crate) fn probe_source(path: &Path) -> Option> { +pub(crate) fn probe_source(path: &Path) -> Option> { let ext = crate::ext_of(path); if crate::STILL_EXTENSIONS.contains(&ext.as_str()) || crate::MODEL_EXTENSIONS.contains(&ext.as_str()) { return None; } - let reader = FileReader::open(path).ok()?; - let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader); + let reader = Arc::new(FileReader::open(path).ok()?); let head = filmcraft_media::reader::read_range(&*reader, 0, filmcraft_media::reader::HEAD_LEN).ok()?; let name = path.to_string_lossy(); if crate::layered::sniff(&name, &head) || image::guess_format(&head).is_ok() { return None; } let name = name_of(path); - filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &reader)).map(|r| r.map_err(Into::into)) + let craft_reader: craft_media_source::SharedBytes = reader.clone(); + if let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) { + return Some(res.map(MediaSource::Craft).map_err(MediaError::from)); + } + let fc_reader: filmcraft_media::SharedReader = reader; + filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into)) } #[cfg(not(any(unix, windows)))] -pub(crate) fn probe_source(_path: &Path) -> Option> { +pub(crate) fn probe_source(_path: &Path) -> Option> { None } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index ed152541c..944a88721 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1290,3 +1290,74 @@ fn the_h264_fixture_options_fit_the_picked_encoder() { assert!(options.contains(&"-b:v"), "{enc} gets a bitrate: {options:?}"); } } + +/// #781: software MP4/H.264 route on a B-frame fixture: backward seek across GOPs, cooperative +/// cancellation, VUI/container color resolution, and draft mode for reduced-resolution playback. +#[test] +fn h264_bframe_route_backward_seek_cancel_color_and_draft() { + use std::sync::atomic::AtomicBool; + if h264_encoder() != Some("libx264") { + return; + } + let Some(p) = try_ffmpeg_fixture( + "h264_bframes_bt709.mp4", + &[ + "-f", + "lavfi", + "-i", + "testsrc2=size=320x180:rate=24:duration=1", + "-c:v", + "libx264", + "-preset", + "fast", + "-bf", + "2", + "-g", + "12", + "-pix_fmt", + "yuv420p", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-color_range", + "tv", + ], + ) else { + return; + }; + let f = probe(&p).expect("probe"); + assert_eq!((f.width, f.height), (320, 180)); + assert_eq!(f.color_profile, Some(effectcraft_project::ColorSpace::Rec709)); + + let pool = MediaPool::new(); + // Forward decode into second GOP, then backward seek across GOP boundary and within GOP. + let f18 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 18)).expect("frame 18"); + let f13 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 13)).expect("frame 13"); + let f7 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("frame 7"); + let f0 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 0)).expect("frame 0"); + for img in [&f18, &f13, &f7, &f0] { + assert_eq!((img.width, img.height), (320, 180)); + } + // Verify backward-seeked frame 7 matches a fresh pool decode of frame 7. + let fresh_f7 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("fresh frame 7"); + assert!(psnr(&f7, &fresh_f7) > 55.0, "backward seek frame 7 must match fresh decode"); + + // Draft mode at reduced resolution. + let draft = pool.frame_at_size(ItemId(1), &f, t_of(f.frame_rate, 5), 160, 90).expect("draft frame"); + let full = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("full frame"); + assert_eq!((draft.width, draft.height), (160, 90)); + assert!(psnr(&draft, &effectcraft_raster::resample(&full, 160, 90)) > 40.0, "draft frame matches resampled full frame"); + + // Cooperative cancellation. + let off = Arc::new(AtomicBool::new(true)); + let mut cancelled = Some(Arc::clone(&f0)); + pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); + assert!(cancelled.is_none(), "cancelled read must not decode"); + let on = Arc::new(AtomicBool::new(false)); + let mut resumed = None; + pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); + assert_eq!(resumed.map(|i| (i.width, i.height)), Some((320, 180))); +}