From f70208cef39195dc82db75068a920730c0283aef Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:31:03 +0800 Subject: [PATCH] media: route MP4 and Matroska FLAC through craft-audio (#4049) * media: route MP4 and Matroska FLAC through craft-audio * media: propagate errors when generating FLAC test fixtures --------- Co-authored-by: Dylan M. Taylor --- Cargo.lock | 54 ++++---- Cargo.toml | 14 +-- crates/media/src/craft_source.rs | 71 ++++++----- .../src/craft_source/flac_tracks_tests.rs | 116 ++++++++++++++++++ 4 files changed, 194 insertions(+), 61 deletions(-) create mode 100644 crates/media/src/craft_source/flac_tracks_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 68eb957f3..5ec8226e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1207,10 +1207,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-xml 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=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "log", "thiserror 2.0.21", ] @@ -1266,7 +1266,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "serde", ] @@ -1341,10 +1341,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-frame" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "craft-color", - "craft-time 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=587339c787682592ed46bab5a15cae52e60da2e3)", "rayon", "serde", ] @@ -1415,7 +1415,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=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "chrono", "thiserror 2.0.21", @@ -1441,13 +1441,13 @@ dependencies = [ [[package]] name = "craft-media-source" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-color", "craft-frame", - "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)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "serde", "thiserror 2.0.21", ] @@ -1584,7 +1584,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" dependencies = [ "serde", "thiserror 2.0.21", @@ -1593,7 +1593,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1697,9 +1697,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-media 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=587339c787682592ed46bab5a15cae52e60da2e3)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1745,6 +1745,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -2146,11 +2156,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-exr", "craft-gif", - "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)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2312,17 +2322,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=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-color", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-exr", "craft-frame", "craft-gif", - "craft-media 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=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-media-source", - "craft-time 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)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-webp", "effectcraft-color", "effectcraft-effects", diff --git a/Cargo.toml b/Cargo.toml index 011553b8c..e5753ceff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,13 +97,13 @@ same-file = "1.0" tempfile = "3.27" # 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 = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", 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"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", 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 = "587339c787682592ed46bab5a15cae52e60da2e3", 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/src/craft_source.rs b/crates/media/src/craft_source.rs index ea98cd383..5405c5b9e 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -10,14 +10,14 @@ //! - Shared (`craft-media::isobmff` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes` (coded alpha via `craft_video::prores::probe`, #3999), `Dnxhd`, //! `Mpeg2Video`, and strictly admitted video-only `Apv` MP4; -//! audio `Aac`, `Alac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. +//! audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. //! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, other `Apv`, or unsupported audio. //! - **Matroska / WebM (`MKV`/`MKA`/`WebM`, video+audio & audio-only)**: //! - Shared (`craft-media::matroska` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, -//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, //! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). //! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib -//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Flac`/`Pcm`). +//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Pcm`). //! - **MXF (`MXF`, video+audio & audio-only OP1a/OP-Atom)**: //! - Shared (`craft-media::mxf` + `craft-video` + `MxfFile::read_pcm`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; sound `Pcm` and `Aes3` (D-10). @@ -420,7 +420,7 @@ fn place_packet(packet: PacketTime, next: &mut Option, tolerance: u64) -> i start } -struct OpusPrefix { +struct PacketTimingPrefix { len: usize, next: Option, tolerance: u64, @@ -428,27 +428,28 @@ struct OpusPrefix { } struct AudioStarts { - // For Opus, unvisited entries still hold raw container stamps. Resolve in place + // Unvisited entries still hold raw container stamps. Resolve in place // as packets arrive, reusing this table for the finished timeline. positions: Vec, - opus: Option, + pending: Option, } impl AudioStarts { fn complete(positions: Vec) -> Self { - Self { positions, opus: None } + Self { positions, pending: None } } - fn opus(positions: Vec, tolerance: i64) -> Self { + fn from_packet_timing(positions: Vec, tolerance: i64) -> Self { // Open resolves exactly the bounded lookahead before anyone can seek. let min_pending_stamp = positions.iter().skip(AUDIO_LOOKAHEAD).copied().min().unwrap_or(i64::MIN); - let opus = (!positions.is_empty()).then_some(OpusPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); - Self { positions, opus } + let pending = + (!positions.is_empty()).then_some(PacketTimingPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); + Self { positions, pending } } fn start(&self, file: &ContainerFile, track: usize, idx: usize) -> Option { let stamp = *self.positions.get(idx)?; - let Some(prefix) = &self.opus else { return Some(stamp) }; + let Some(prefix) = &self.pending else { return Some(stamp) }; if idx < prefix.len { return Some(stamp); } @@ -459,22 +460,26 @@ impl AudioStarts { }) } - fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8]) { - let Some(prefix) = &mut self.opus else { return }; + fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8], decoder: &AudioTrackDecoder) { + let Some(prefix) = &mut self.pending else { return }; if idx != prefix.len { return; } - let timing = - PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples: opus_packet_samples(packet).map(i64::from) }; + let samples = match decoder.codec() { + CodecId::Opus => opus_packet_samples(packet).map(i64::from), + CodecId::Flac => decoder.flac_packet_frames(packet).and_then(|n| i64::try_from(n).ok()), + _ => None, + }; + let timing = PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples }; self.positions[idx] = place_packet(timing, &mut prefix.next, prefix.tolerance); prefix.len += 1; if prefix.len == self.positions.len() { - self.opus = None; + self.pending = None; } } fn seek_proves_first_packet(&self, target: i64) -> bool { - let Some(prefix) = &self.opus else { return false }; + let Some(prefix) = &self.pending else { return false }; // A normal read that starts before the very first packet looks like a // backward seek. It need not read the suffix if the ordinary seek // would back up to packet 0 anyway. Stamped starts can only move by the @@ -485,18 +490,18 @@ impl AudioStarts { && self.positions.get(AUDIO_SEEK_BACKUP_PACKETS + 1..prefix.len).is_some_and(|p| p.iter().all(|&start| start > target)) } - fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize) -> Result<()> { + fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize, decoder: &AudioTrackDecoder) -> Result<()> { // The exact recurrence can carry a timing phase across arbitrarily many // rounded or laced packets. A first discontinuous seek may still have to // index the unread suffix; normal open and sequential decode never do this. - while let Some(idx) = self.opus.as_ref().map(|prefix| prefix.len) { + while let Some(idx) = self.pending.as_ref().map(|prefix| prefix.len) { if filmcraft_media::cancel::cancelled() { return Err(MediaError::Cancelled); } // Do not commit a guessed duration after an I/O error; the next // request can retry this packet without re-reading the valid prefix. let packet = file.read_sample(source, track, idx)?; - self.observe(file, track, idx, &packet); + self.observe(file, track, idx, &packet, decoder); } Ok(()) } @@ -556,8 +561,8 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code let ts = i128::from(track.timescale.max(1)); let stamps: Vec = (0..track.samples.len()).map(|i| isobmff_audio_position(track, i, native_rate)).collect(); let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); - if codec == CodecId::Opus { - return AudioStarts::opus(stamps, unit.saturating_mul(2).saturating_add(1)); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(stamps, unit.saturating_mul(2).saturating_add(1)); } let Some(frame) = fixed_samples else { return AudioStarts::complete(stamps); @@ -579,8 +584,8 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code i64::try_from(audio_frames_from_ns(ns, native_rate) - delay_frames).unwrap_or(0) }; let tick_samples = i64::try_from(i128::from(track.ticks_to_ns(2)) * rate / 1_000_000_000).unwrap_or(i64::MAX).saturating_add(1); - if codec == CodecId::Opus { - return AudioStarts::opus(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); } let Some(frame) = fixed_samples else { return AudioStarts::complete(track.samples.iter().map(|s| stamp_for(s.pts)).collect()); @@ -671,9 +676,9 @@ where let codec = dec.codec(); let fixed_samples = fixed_packet_samples(&mut dec, codec, &lookahead); let mut audio_starts = compute_audio_starts(container, idx, codec, native_rate, fixed_samples); - if codec == CodecId::Opus { + if audio_starts.pending.is_some() { for (s_idx, pkt) in lookahead.iter().enumerate() { - audio_starts.observe(container, idx, s_idx, pkt); + audio_starts.observe(container, idx, s_idx, pkt, &dec); } } let seek_preroll_samples = match container { @@ -688,7 +693,7 @@ where sample_rate: native_rate, channels, codec: params.codec.name().to_string(), - bits_per_sample: params.pcm.map(|p| u32::from(p.bits)), + bits_per_sample: dec.flac_stream_info().map(|info| u32::from(info.bits_per_sample)).or_else(|| params.pcm.map(|p| u32::from(p.bits))), }); audio_tracks.push(AudioTrackEntry { track_idx: idx, @@ -2201,7 +2206,7 @@ fn decode_audio_range( let (seek_idx, decoded_pos) = if moves_backward && state.next_sample == 0 && state.audio_starts.seek_proves_first_packet(target) { (0, state.decoded_pos) } else { - state.audio_starts.finish_for_seek(file, source, track_idx)?; + state.audio_starts.finish_for_seek(file, source, track_idx, &state.decoder)?; file.audio_seek_info(track_idx, &state.audio_starts.positions, seek_preroll_samples, start) }; state.decoder.reset(); @@ -2233,7 +2238,7 @@ fn decode_audio_range( break; } let pkt = file.read_sample(source, track_idx, idx)?; - state.audio_starts.observe(file, track_idx, idx, &pkt); + state.audio_starts.observe(file, track_idx, idx, &pkt, &state.decoder); state.next_sample = idx + 1; let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; let buf_len = state.buf.first().map_or(0, Vec::len) as i64; @@ -2770,6 +2775,8 @@ fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { FrameRate::FPS_30 } +#[cfg(all(test, any(unix, windows)))] +mod flac_tracks_tests; #[cfg(all(test, any(unix, windows)))] mod raw_avi_tests; @@ -3154,7 +3161,7 @@ mod tests { assert_eq!(backward, decode(&mut reference[0], &source.bytes, backward_start, OPUS_FRAME)); let (_, state) = tracks[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); - assert!(state.audio_starts.opus.is_none()); + assert!(state.audio_starts.pending.is_none()); early } @@ -3185,7 +3192,7 @@ mod tests { let (preroll, state) = fresh[0].decoder_parts(); let error = decode_audio_range(file, source, 0, OPUS_RATE, 1, preroll, state, start, 3 * OPUS_FRAME).unwrap_err(); assert!(matches!(error, MediaError::Io(_))); - assert_eq!(state.audio_starts.opus.as_ref().unwrap().len, transient_packet); + assert_eq!(state.audio_starts.pending.as_ref().unwrap().len, transient_packet); assert_eq!((state.next_sample, state.decoded_pos), (0, first)); } let cold = decode(&mut fresh[0], source, start, 3 * OPUS_FRAME); @@ -3193,7 +3200,7 @@ mod tests { assert!(cold[0].iter().any(|s| s.abs() > 1e-5)); let (_, state) = fresh[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); - assert!(state.audio_starts.opus.is_none()); + assert!(state.audio_starts.pending.is_none()); } #[test] diff --git a/crates/media/src/craft_source/flac_tracks_tests.rs b/crates/media/src/craft_source/flac_tracks_tests.rs new file mode 100644 index 000000000..8395c81d1 --- /dev/null +++ b/crates/media/src/craft_source/flac_tracks_tests.rs @@ -0,0 +1,116 @@ +use std::io::Cursor; +use std::sync::Arc; + +use craft_audio::flac::{Encoder, EncoderConfig, STREAMINFO_OFFSET}; +use craft_media::{isobmff, matroska}; +use craft_media_source::MediaKind; + +use crate::stream::{self, MediaSource as OpenedSource}; + +const RATE: u32 = 96_000; +const BLOCK: usize = 1_000; +const FRAMES: usize = 196 * BLOCK + 221; +const COLD_SEEK: usize = 2 * RATE as usize + BLOCK + 200; + +struct Fixture { + private: Vec, + packets: Vec>, + samples: Vec>, +} + +impl Fixture { + fn new() -> Result> { + let left: Vec = (0..FRAMES).map(|i| (i as i32 * 307 % 65_536) - 30_000).collect(); + let right: Vec = (0..FRAMES).map(|i| 28_000 - (i as i32 * 701 % 59_000)).collect(); + let mut config = EncoderConfig::new(RATE, 2, 24); + config.block_size = BLOCK as u16; + let mut encoder = Encoder::new(config)?; + let mut packets = encoder.encode_frames(&[&left, &right])?; + packets.push(encoder.finish()); + let mut private = encoder.header(&[]); + let offset = STREAMINFO_OFFSET as usize; + private[offset..offset + 34].copy_from_slice(&encoder.streaminfo()); + Ok(Self { private, packets, samples: vec![left, right] }) + } + + fn mp4(&self) -> Result, Box> { + let offset = STREAMINFO_OFFSET as usize; + let mut entry = isobmff::SampleEntry::flac(self.private[offset..offset + 34].try_into()?); + entry.audio.as_mut().ok_or("FLAC sample entry needs an audio header")?.sample_rate = 48_000.0; + let mut writer = isobmff::Mp4Writer::new(Cursor::new(Vec::new()), isobmff::WriterOptions::new(isobmff::Brand::Mp4))?; + writer.add_track(isobmff::TrackConfig::new(entry, RATE))?; + for (i, packet) in self.packets.iter().enumerate() { + let duration = (FRAMES - i * BLOCK).min(BLOCK) as u32; + writer.write_sample(0, isobmff::WriteSample { data: packet, duration, composition_offset: 0, is_sync: true })?; + } + Ok(writer.finish()?.into_inner()) + } + + fn mkv(&self, private: &[u8]) -> Result, Box> { + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_FLAC"); + track.audio = Some((f64::from(RATE), 2, Some(24))); + track.codec_private = private.to_vec(); + let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?; + for (i, packet) in self.packets.iter().enumerate() { + // The muxer rounds starts to its millisecond clock. A 1000-frame packet + // at 96 kHz does not start on a millisecond boundary after packet zero. + let pts = (i * BLOCK) as i64 * 1_000_000_000 / i64::from(RATE); + let duration = (FRAMES - i * BLOCK).min(BLOCK) as u64 * 1_000_000_000 / u64::from(RATE); + writer.write_frame(0, pts, true, packet, Some(duration))?; + } + Ok(writer.finish()?.into_inner()) + } +} + +#[test] +fn flac_in_mp4_and_matroska_uses_shared_samples_after_cold_and_backward_seeks() -> Result<(), Box> { + let fixture = Fixture::new()?; + let dir = tempfile::tempdir().unwrap(); + for (name, bytes) in [("audio.mp4", fixture.mp4()?), ("audio.mka", fixture.mkv(&fixture.private)?)] { + let bytes: Arc<[u8]> = bytes.into(); + let path = dir.path().join(name); + std::fs::write(&path, &bytes).unwrap(); + let disk = stream::open_source(&path).unwrap().0.unwrap(); + let memory = stream::open_bytes(name, bytes).unwrap(); + for opened in [disk, memory] { + let OpenedSource::Craft(source) = opened else { panic!("{name}: expected the shared FLAC reader") }; + let info = source.info(); + assert_eq!(info.kind, MediaKind::AudioOnly); + let audio = info.audio().unwrap(); + assert_eq!((audio.codec.as_str(), audio.sample_rate, audio.channels, audio.bits_per_sample), ("FLAC", RATE, 2, Some(24))); + + for (start, frames) in [(COLD_SEEK, 48), (991, 33), (FRAMES - 25, 50), (0, FRAMES)] { + let decoded = source.audio(start as i64, frames, RATE).unwrap(); + assert_eq!((decoded.num_channels(), decoded.frames()), (2, frames)); + for (actual, expected) in decoded.channels.iter().zip(&fixture.samples) { + for (i, &sample) in actual.iter().enumerate() { + let want = expected.get(start + i).copied().unwrap_or(0) as f32 / 8_388_608.0; + assert_eq!(sample, want, "{name} sample {}", start + i); + } + } + } + + let whole = source.audio(451, 93, 44_100).unwrap(); + let first = source.audio(451, 31, 44_100).unwrap(); + let second = source.audio(482, 62, 44_100).unwrap(); + for ((whole, first), second) in whole.channels.iter().zip(&first.channels).zip(&second.channels) { + assert_eq!(&whole[..31], first, "{name} first resampled segment"); + assert_eq!(&whole[31..], second, "{name} second resampled segment"); + } + } + } + Ok(()) +} + +#[test] +fn flac_without_the_expected_private_marker_keeps_matroska_fallback() -> Result<(), Box> { + let fixture = Fixture::new()?; + let mut private = fixture.private.clone(); + private[..4].copy_from_slice(b"test"); + let OpenedSource::Film(source) = stream::open_bytes("legacy.mka", fixture.mkv(&private)?.into()).unwrap() else { + panic!("expected the legacy FLAC reader"); + }; + let decoded = source.audio(0, 16, RATE).unwrap(); + assert!(decoded.channels[0].iter().any(|&sample| sample != 0.0)); + Ok(()) +}