diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4f0ae1f5b..78ff936bd 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -180,3 +180,9 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository. Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. + +## Y4M range-backed playback + +`crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). + +`crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. diff --git a/Cargo.lock b/Cargo.lock index 48ed641f3..1a93a5400 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2637,6 +2637,7 @@ dependencies = [ "craft-frame", "craft-media", "craft-time", + "craft-y4m", "serde", "serde_json", "thiserror 2.0.21", diff --git a/NOTICE b/NOTICE index 66b01e02f..84f9d4c54 100644 --- a/NOTICE +++ b/NOTICE @@ -432,3 +432,8 @@ Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/core MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt. + +The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's +original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed +MIT OR Apache-2.0. Source notice retained: +Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. diff --git a/crates/media-source/Cargo.toml b/crates/media-source/Cargo.toml index 3edda0b2e..ea9f5fd83 100644 --- a/crates/media-source/Cargo.toml +++ b/crates/media-source/Cargo.toml @@ -10,12 +10,16 @@ repository.workspace = true [lints] workspace = true +[features] +y4m = ["dep:craft-y4m"] + [dependencies] craft-audio = { workspace = true } craft-color = { workspace = true } craft-frame = { workspace = true } craft-media = { workspace = true } craft-time = { workspace = true } +craft-y4m = { workspace = true, optional = true } serde = { workspace = true } thiserror = { workspace = true } diff --git a/crates/media-source/src/lib.rs b/crates/media-source/src/lib.rs index 65b42e498..909fdbaad 100644 --- a/crates/media-source/src/lib.rs +++ b/crates/media-source/src/lib.rs @@ -27,6 +27,8 @@ use craft_time::{FrameRate, Tick}; use serde::{Deserialize, Serialize}; pub mod cancel; +#[cfg(feature = "y4m")] +pub mod y4m; /// Errors from opening or reading a media source. #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] diff --git a/crates/media-source/src/y4m.rs b/crates/media-source/src/y4m.rs new file mode 100644 index 000000000..89a014c71 --- /dev/null +++ b/crates/media-source/src/y4m.rs @@ -0,0 +1,171 @@ +//! Indexed, range-backed YUV4MPEG2 playback over the shared parser. +//! +//! Adapted to the shared source and frame types from FilmCraft's in-house `Y4mSource`; +//! see the repository's attribution for source history. + +use std::sync::Arc; + +use craft_audio::AudioBuffer; +use craft_color::{ColorInfo, Range}; +use craft_frame::{Chroma, PixelData, VideoFrame, default_matrix}; +use craft_time::{FrameRate, Tick}; +use craft_y4m::{Error, Layout, Limits, Stream, samples_u16}; + +use crate::{DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, VideoStreamInfo, read_range}; + +pub use craft_y4m::sniff; + +/// Y4M video whose frame payloads are read on demand from an indexed byte source. +pub struct Y4mSource { + source: SharedBytes, + stream: Stream, + info: MediaInfo, + rate: FrameRate, +} + +impl Y4mSource { + /// Index complete pictures without loading the video. A picture larger than the shared + /// byte-reader allocation ceiling is reported as unsupported before this source is returned. + pub fn open(name: &str, source: SharedBytes) -> Result { + let len = source.len(); + let mut read_error = None; + let stream = Stream::open( + len, + |offset, len| match read_range(&*source, offset, len) { + Ok(bytes) if bytes.len() == len => Some(bytes), + Ok(_) => { + // The parser already clips requests to the length snapshotted at open. + // A shorter read here is an I/O failure, not a known incomplete tail. + read_error = Some(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read while indexing Y4M")); + None + } + Err(err) => { + read_error = Some(err); + None + } + }, + &Limits::default(), + ); + if let Some(err) = read_error { + return Err(MediaError::Io(format!("{name}: Y4M: {err}"))); + } + let stream = stream.map_err(|err| match err { + Error::UnsupportedColourSpace(c) => MediaError::Unsupported(format!("{name}: Y4M colour space {c}")), + Error::LimitExceeded(limit) => MediaError::Unsupported(format!("{name}: Y4M exceeds its {limit} limit")), + Error::Malformed(reason) => MediaError::Decode(format!("{name}: Y4M: {reason}")), + })?; + if stream.frame_bytes > DEFAULT_MAX_MEDIA_BYTES { + return Err(MediaError::Unsupported(format!("{name}: Y4M frame exceeds the media buffer limit"))); + } + + let header = &stream.header; + let (width, height) = (header.width, header.height); + let rate = header.frame_rate.map_or(FrameRate::FPS_25, |(n, d)| FrameRate::new(n, d)); + let color = ColorInfo { + matrix: default_matrix(width, height), + range: if header.full_range { Range::Full } else { Range::Limited }, + ..ColorInfo::REC709 + }; + let duration = picture_time(stream.frames.len(), rate); + let bitrate = (stream.frame_bytes as u64 * 8).checked_mul(rate.num as u64).map(|bits| bits / rate.den as u64); + let info = MediaInfo { + name: name.into(), + kind: MediaKind::Movie, + duration, + video: Some(VideoStreamInfo { + width, + height, + frame_rate: rate, + par: header.pixel_aspect.unwrap_or((1, 1)), + codec: "Uncompressed YUV".into(), + pixel_format: layout_label(header.layout), + color, + has_alpha: header.layout.alpha, + bitrate, + hdr: None, + }), + audio_streams: Vec::new(), + container: "Y4M".into(), + start_timecode: None, + file_size: Some(len), + }; + Ok(Self { source, stream, info, rate }) + } + + fn picture(&self, index: usize) -> Result { + let (Some(payload), Some(info)) = (self.stream.frame(index), self.info.video.as_ref()) else { + return Err(MediaError::Decode("Y4M: frame index out of range".into())); + }; + let len = self.stream.frame_bytes; + let bytes = read_range(&*self.source, payload.start, len).map_err(|err| MediaError::Decode(format!("Y4M: {err}")))?; + if bytes.len() != len { + return Err(MediaError::Decode("Y4M: incomplete frame payload".into())); + } + + let header = &self.stream.header; + let layout = header.layout; + let planes = header.planes(); + let grey = header.chroma_samples(craft_y4m::Chroma::C420); + let chroma = layout.chroma.map(chroma).unwrap_or(Chroma::C420); + let data = if layout.bits == 8 { + let y = Arc::new(bytes[planes.y].to_vec()); + let (cb, cr) = if layout.chroma.is_some() { + (Arc::new(bytes[planes.cb].to_vec()), Arc::new(bytes[planes.cr].to_vec())) + } else { + let neutral = Arc::new(vec![128; grey]); + (neutral.clone(), neutral) + }; + let alpha = layout.alpha.then(|| Arc::new(bytes[planes.alpha].to_vec())); + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha } + } else { + let plane = |range: std::ops::Range| Arc::new(samples_u16(&bytes[range], layout.bits)); + let y = plane(planes.y); + let (cb, cr) = if layout.chroma.is_some() { + (plane(planes.cb), plane(planes.cr)) + } else { + let neutral = Arc::new(vec![1 << (layout.bits - 1); grey]); + (neutral.clone(), neutral) + }; + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: layout.bits, alpha: None } + }; + Ok(VideoFrame { width: info.width, height: info.height, data, color: info.color, par: info.par, pts: picture_time(index, self.rate) }) + } +} + +impl MediaSource for Y4mSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, req: FrameRequest) -> Result> { + let last = self.stream.frames.len().saturating_sub(1); + let index = usize::try_from(self.rate.frame_at(req.time.max(Tick::ZERO))).unwrap_or(last).min(last); + self.picture(index).map(Arc::new) + } + + fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result { + Err(MediaError::NoStream("audio")) + } +} + +fn picture_time(index: usize, rate: FrameRate) -> Tick { + // The parser's default frame-count cap is below i64::MAX on every target. + // Round up to the same boundary used by frame_at, within Tick resolution and range. + rate.tick_of(index as i64) +} + +fn chroma(chroma: craft_y4m::Chroma) -> Chroma { + match chroma { + craft_y4m::Chroma::C420 => Chroma::C420, + craft_y4m::Chroma::C422 => Chroma::C422, + craft_y4m::Chroma::C444 => Chroma::C444, + } +} + +fn layout_label(layout: Layout) -> String { + match (layout.chroma, layout.alpha) { + (None, _) => format!("Monochrome {}-bit", layout.bits), + (Some(_), true) => format!("YUVA 4:4:4:4 {}-bit", layout.bits), + (Some(subsampling), false) => format!("YUV {} {}-bit", chroma(subsampling).label(), layout.bits), + } +} diff --git a/crates/media-source/tests/it/main.rs b/crates/media-source/tests/it/main.rs new file mode 100644 index 000000000..94659dc7d --- /dev/null +++ b/crates/media-source/tests/it/main.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "y4m")] +mod y4m; diff --git a/crates/media-source/tests/it/y4m.rs b/crates/media-source/tests/it/y4m.rs new file mode 100644 index 000000000..95b06a743 --- /dev/null +++ b/crates/media-source/tests/it/y4m.rs @@ -0,0 +1,205 @@ +use std::io; +use std::sync::{Arc, Mutex}; + +use craft_color::{ColorInfo, Matrix, Range}; +use craft_frame::{Chroma, PixelData}; +use craft_media::ByteSource; +use craft_media_source::y4m::{Y4mSource, sniff}; +use craft_media_source::{DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaKind, MediaSource, SharedBytes}; +use craft_time::{FrameRate, Tick}; + +type TestResult = std::result::Result>; + +struct Tracked { + prefix: Vec, + length: u64, + fail_at: Option, + shrink_after: Option<(usize, u64)>, + reads: Mutex>, +} + +impl Tracked { + fn new(bytes: Vec, length: u64) -> Arc { + Arc::new(Self { prefix: bytes, length, fail_at: None, shrink_after: None, reads: Mutex::new(Vec::new()) }) + } + + fn take_reads(&self) -> Vec<(u64, usize)> { + std::mem::take(&mut *self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) + } +} + +impl ByteSource for Tracked { + fn len(&self) -> u64 { + if let Some((reads, length)) = self.shrink_after + && self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len() >= reads + { + return length; + } + self.length + } + + fn read_at(&self, offset: u64, out: &mut [u8]) -> io::Result<()> { + self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((offset, out.len())); + if self.fail_at.is_some_and(|at| offset <= at && at < offset.saturating_add(out.len() as u64)) { + return Err(io::Error::other("injected second Y4M delimiter read failure")); + } + let start = usize::try_from(offset).map_err(io::Error::other)?; + let available = self.prefix.get(start..).unwrap_or_default(); + let n = out.len().min(available.len()); + out[..n].copy_from_slice(&available[..n]); + out[n..].fill(0); + Ok(()) + } +} + +#[test] +fn plays_exact_odd_10_bit_frames_on_cfr_boundaries() -> TestResult<()> { + // Original deterministic Y4M: 3x3 luma and two 2x2 chroma planes, independently authored. + let first = [64u16, 65, 66, 67, 68, 69, 70, 71, 72, 401, 402, 403, 404, 601, 602, 603, 604]; + let second = [721u16, 722, 723, 724, 725, 726, 727, 728, 729, 801, 802, 803, 804, 201, 202, 203, 204]; + let mut bytes = b"YUV4MPEG2 W3 H3 F30000:1001 A4:3 C420p10 XCOLORRANGE=FULL\nFRAME\n".to_vec(); + let at_first = bytes.len() as u64; + bytes.extend(first.into_iter().flat_map(u16::to_le_bytes)); + bytes.extend_from_slice(b"FRAME Xtest\n"); + let at_second = bytes.len() as u64; + bytes.extend(second.into_iter().flat_map(u16::to_le_bytes)); + bytes.extend_from_slice(b"FRAME\n\x01\x02"); + let length = bytes.len() as u64; + let reader = Tracked::new(bytes, length); + let input: SharedBytes = reader.clone(); + let source = Y4mSource::open("odd.y4m", input)?; + let info = source.info(); + let video = info.video.as_ref().ok_or("expected Y4M video")?; + let period = Tick(8_475_667_200); + let color = ColorInfo { matrix: Matrix::Bt601, range: Range::Full, ..ColorInfo::REC709 }; + assert_eq!((info.kind, info.duration, info.file_size), (MediaKind::Movie, Tick(2 * period.0), Some(length))); + assert_eq!(info.container, "Y4M"); + assert!(info.start_timecode.is_none() && !info.has_audio()); + assert!(matches!(source.audio(0, 2, 48_000), Err(MediaError::NoStream("audio")))); + assert_eq!((video.width, video.height, video.par), (3, 3, (4, 3))); + assert_eq!((video.frame_rate, video.color), (FrameRate::new(30_000, 1_001), color)); + assert_eq!(video.codec, "Uncompressed YUV"); + assert!(!video.has_alpha); + + assert!(reader.take_reads().into_iter().all(|(_, len)| len <= 128)); + for (ask, pts, offset, expected) in [ + (Tick(-1), Tick::ZERO, at_first, first), + (Tick(period.0 - 1), Tick::ZERO, at_first, first), + (period, period, at_second, second), + (Tick(3 * period.0), period, at_second, second), + (Tick::ZERO, Tick::ZERO, at_first, first), + ] { + let frame = source.video_frame(FrameRequest { time: ask, scale: 0.5 })?; + assert_eq!((frame.pts, frame.par, frame.color, frame.width, frame.height), (pts, (4, 3), color, 3, 3)); + let PixelData::Yuv16 { planes, chroma, bits, alpha } = &frame.data else { + return Err("expected YUV16, not a converted RGB frame".into()); + }; + assert_eq!((*chroma, *bits, alpha.is_none()), (Chroma::C420, 10, true)); + assert_eq!(planes.each_ref().map(|plane| plane.as_slice()), [&expected[..9], &expected[9..13], &expected[13..]]); + assert_eq!(reader.take_reads(), vec![(offset, 34)]); + } + Ok(()) +} + +#[test] +fn defaults_and_special_planes_remain_distinct() -> TestResult<()> { + let cases = [ + (b"YUV4MPEG2 W1 H1 Cmono\nFRAME\n\x31".as_slice(), Chroma::C420, [0x31, 128, 128], None), + (b"YUV4MPEG2 W1 H1 C444alpha\nFRAME\n\x45\x67\x89\xab".as_slice(), Chroma::C444, [0x45, 0x67, 0x89], Some(0xab)), + ]; + for (bytes, expected_chroma, expected, expected_alpha) in cases { + let memory: Arc<[u8]> = bytes.into(); + let source = Y4mSource::open("one.y4m", Arc::new(memory))?; + let video = source.info().video.as_ref().ok_or("expected Y4M video")?; + assert_eq!((source.info().duration, video.frame_rate, video.par), (Tick::from_units(1, 25), FrameRate::FPS_25, (1, 1))); + assert_eq!(video.color.range, Range::Limited); + assert_eq!(video.has_alpha, expected_alpha.is_some()); + let frame = source.video_frame(FrameRequest::full(Tick::ZERO))?; + let PixelData::Yuv8 { planes, chroma, alpha } = &frame.data else { + return Err("expected YUV8".into()); + }; + assert_eq!(*chroma, expected_chroma); + assert_eq!(planes.each_ref().map(|plane| plane.as_slice()), expected.each_ref().map(std::slice::from_ref)); + assert_eq!(alpha.as_ref().map(|plane| plane.as_slice()), expected_alpha.as_ref().map(std::slice::from_ref)); + } + Ok(()) +} + +#[test] +fn declines_unknown_and_oversize_without_reading_payloads() { + assert!(!sniff(b"YUV4MPEG2x")); + let unknown: Arc<[u8]> = b"YUV4MPEG2 W2 H2 C411\nFRAME\n".as_slice().into(); + assert!(sniff(&unknown)); + assert!(matches!(Y4mSource::open("unknown.y4m", Arc::new(unknown)), Err(MediaError::Unsupported(_)))); + + // 2^26 pixels, 6 bytes per pixel: within the parser's pixel limit, but above the + // source's byte-allocation ceiling. Model the payload length; allocate only its header. + let prefix = b"YUV4MPEG2 W8192 H8192 C444p16\nFRAME\n".to_vec(); + let frame_bytes = 8192u64 * 8192 * 6; + assert!(frame_bytes > DEFAULT_MAX_MEDIA_BYTES as u64); + let length = prefix.len() as u64 + frame_bytes; + let reader = Tracked::new(prefix, length); + let input: SharedBytes = reader.clone(); + assert!(matches!(Y4mSource::open("large.y4m", input), Err(MediaError::Unsupported(_)))); + let reads = reader.take_reads(); + assert!(!reads.is_empty() && reads.into_iter().all(|(_, len)| len <= 128)); +} + +fn sparse_mono_pair() -> (Vec, u64, u64, u64) { + let header = b"YUV4MPEG2 W16 H16 Cmono\n"; + let mut prefix = header.to_vec(); + prefix.extend_from_slice(b"FRAME\n"); + prefix.resize(prefix.len() + 256, 0); + let at_second = prefix.len() as u64; + prefix.extend_from_slice(b"FRAME\n"); + let length = prefix.len() as u64 + 256; + (prefix, header.len() as u64, at_second, length) +} + +#[test] +fn index_preserves_second_frame_delimiter_io_error() -> TestResult<()> { + let (prefix, first, second, length) = sparse_mono_pair(); + // Only the read starting at the second delimiter fails; the payload was in bounds. + let reader = Arc::new(Tracked { prefix, length, fail_at: Some(second), shrink_after: None, reads: Mutex::new(Vec::new()) }); + let input: SharedBytes = reader.clone(); + let result = Y4mSource::open("unreadable.y4m", input); + assert_eq!(reader.take_reads(), vec![(0, 128), (first, 128), (second, 128)]); + let Err(MediaError::Io(message)) = result else { + return Err("a second delimiter read failure must not silently shorten the video".into()); + }; + assert!(message.contains("injected second Y4M delimiter read failure")); + Ok(()) +} + +#[test] +fn index_reports_short_read_when_source_shrinks_mid_open() -> TestResult<()> { + let (prefix, first, second, length) = sparse_mono_pair(); + // The opener and the first two range reads see the original extent. The allocator + // observes the shrink on the next range, just two bytes into the second delimiter. + let reader = Arc::new(Tracked { prefix, length, fail_at: None, shrink_after: Some((2, second + 2)), reads: Mutex::new(Vec::new()) }); + let input: SharedBytes = reader.clone(); + let result = Y4mSource::open("shrunk.y4m", input); + assert_eq!(reader.take_reads(), vec![(0, 128), (first, 128), (second, 2)]); + let Err(MediaError::Io(message)) = result else { + return Err("a short read from a changing source must not silently shorten the video".into()); + }; + assert!(message.contains("short read while indexing Y4M")); + Ok(()) +} + +#[test] +fn nonintegral_tick_pts_selects_the_frame_it_labels() -> TestResult<()> { + let bytes: Arc<[u8]> = b"YUV4MPEG2 W1 H1 F31:1 Cmono\nFRAME\n\x11FRAME\n\x22".as_slice().into(); + let source = Y4mSource::open("fractional-ticks.y4m", Arc::new(bytes))?; + let second_tick = Tick(8_194_064_517); + assert_eq!(source.info().duration, Tick(16_388_129_033)); + for (ask, pts, luma) in [(Tick(second_tick.0 - 1), Tick::ZERO, 0x11), (second_tick, second_tick, 0x22)] { + let frame = source.video_frame(FrameRequest::full(ask))?; + let PixelData::Yuv8 { planes, .. } = &frame.data else { + return Err("expected YUV8".into()); + }; + assert_eq!(frame.pts, pts); + assert_eq!(planes[0].as_slice(), &[luma]); + } + Ok(()) +}