FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M9.10: Matroska/WebM import (H.264/HEVC/ProRes/MJPEG video; AAC/FLAC/MP3/Vorbis/PCM audio); GOP random access shared by MP4 and MKV sources (codecs::gop)
Brandon Thomasc6cfa8ddb3c3
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.tomlindex 5af91c946..9b98df6a1 100644--- a/crates/codecs/Cargo.toml+++ b/crates/codecs/Cargo.toml@@ -15,6 +15,7 @@ filmcraft-color = { workspace = true }filmcraft-frame = { workspace = true }filmcraft-media = { workspace = true }filmcraft-isobmff = { workspace = true }+filmcraft-matroska = { workspace = true }filmcraft-bitstream = { workspace = true }filmcraft-h264 = { workspace = true }filmcraft-hevc = { workspace = true }diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rsnew file mode 100644index 000000000..13e2add2f--- /dev/null+++ b/crates/codecs/src/gop.rs@@ -0,0 +1,119 @@+//! GOP-aware random access shared by the container sources (MP4/MOV, Matroska/WebM).+//!+//! Seeking: find the sample whose presentation interval covers the requested time, decode forward+//! from the preceding sync sample, and cache every decoded frame (keyed by pts). Playback requests+//! for the next frames therefore hit the cache or continue the running decoder without re-seeking.++use std::collections::BTreeMap;+use std::sync::{Arc, Mutex};++use filmcraft_color::ColorInfo;+use filmcraft_frame::VideoFrame;++use crate::CodecError;+use crate::video::VideoDecoder;++/// A container's video sample table, in decode (file) order.+pub trait VideoSamples {+ fn count(&self) -> usize;+ /// Presentation timestamp of sample `i` (track units).+ fn pts(&self, i: usize) -> i64;+ /// Nearest sync sample at or before `i`.+ fn sync_before(&self, i: usize) -> usize;+ /// The sample presented at `t` (track units), if any.+ fn sample_at(&self, t: i64) -> Option<usize>;+ fn read(&self, i: usize) -> crate::Result<Vec<u8>>;+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>>;+}++struct State {+ decoder: Option<Box<dyn VideoDecoder>>,+ /// Next sample (decode order) to feed.+ next: usize,+ /// Decoded frames by presentation pts (bounded).+ frames: BTreeMap<i64, Arc<VideoFrame>>,+ bytes: usize,+}++/// Decoder + decoded-frame cache for one video track.+pub struct GopCache {+ state: Mutex<State>,+ /// Colour signalled by the container, which wins over the bitstream's.+ explicit_color: Option<ColorInfo>,+ budget: usize,+}++impl GopCache {+ pub fn new(explicit_color: Option<ColorInfo>) -> Self {+ Self { state: Mutex::new(State { decoder: None, next: usize::MAX, frames: BTreeMap::new(), bytes: 0 }), explicit_color, budget: 384 << 20 }+ }++ fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame) {+ if let Some(c) = self.explicit_color+ && !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_) | filmcraft_frame::PixelData::RgbaF32(_))+ {+ f.color = c;+ }+ st.bytes += f.byte_size();+ st.frames.insert(pts, Arc::new(f));+ // evict frames far from the most recent (keep a window around the working position)+ while st.bytes > self.budget && st.frames.len() > 2 {+ let first = *st.frames.keys().next().expect("non-empty");+ let last = *st.frames.keys().next_back().expect("non-empty");+ let victim = if pts - first > last - pts { first } else { last };+ if let Some(v) = st.frames.remove(&victim) {+ st.bytes -= v.byte_size();+ }+ }+ }++ /// The frame presented at `target` (track units, clamped to the stream).+ pub fn frame(&self, s: &dyn VideoSamples, target: i64) -> crate::Result<Arc<VideoFrame>> {+ let n = s.count();+ let i = s.sample_at(target.max(0)).or_else(|| (n > 0).then(|| n - 1)).ok_or_else(|| CodecError::Decode("empty track".into()))?;+ let want_pts = s.pts(i);+ let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(f) = st.frames.get(&want_pts) {+ return Ok(f.clone());+ }+ if st.decoder.is_none() {+ st.decoder = Some(s.make_decoder()?);+ st.next = usize::MAX;+ }+ let key = s.sync_before(i);+ // Continue the running decoder when the wanted sample is ahead within this GOP run.+ let continuing = st.next != usize::MAX && st.next > key && st.next <= i + 16 && st.next <= n;+ if !continuing {+ if let Some(d) = st.decoder.as_mut() {+ d.reset();+ }+ st.next = key;+ }+ let limit = (i + 64).min(n);+ while st.next < limit {+ let k = st.next;+ let data = s.read(k)?;+ let out = st.decoder.as_mut().expect("decoder").decode(&data, s.pts(k))?;+ st.next += 1;+ for d in out {+ self.store(&mut st, d.pts, d.frame);+ }+ if st.frames.contains_key(&want_pts) {+ break;+ }+ }+ if !st.frames.contains_key(&want_pts) {+ let out = st.decoder.as_mut().expect("decoder").flush();+ for d in out {+ self.store(&mut st, d.pts, d.frame);+ }+ st.next = usize::MAX;+ }+ // nearest decoded frame at or before the wanted pts (robust to decoder pts quirks)+ st.frames+ .get(&want_pts)+ .cloned()+ .or_else(|| st.frames.range(..=want_pts).next_back().map(|(_, f)| f.clone()))+ .ok_or_else(|| CodecError::Decode("frame not produced".into()))+ }+}diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex 92d0d8463..5881cf179 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -11,12 +11,15 @@//! - [`openers`]: the openers to register with the engine's media pool.pub mod audio;+pub mod gop;+pub mod mkv;pub mod mp4;pub mod video;use std::sync::{Arc, RwLock};pub use audio::AudioFileSource;+pub use mkv::MkvSource;pub use mp4::Mp4Source;pub use video::{DecodedFrame, VideoDecoder, VideoDecoderFactory};@@ -65,9 +68,9 @@ pub fn make_video_decoder(entry: &filmcraft_isobmff::SampleEntry) -> Result<Box<Err(CodecError::Unsupported(format!("no decoder for {} video", entry.codec.name())))}-/// Openers for the engine's media pool (MP4/MOV, standalone audio).+/// Openers for the engine's media pool (MP4/MOV, Matroska/WebM, standalone audio).pub fn openers() -> Vec<filmcraft_media::Opener> {- vec![mp4::opener, audio::opener]+ vec![mp4::opener, mkv::opener, audio::opener]}/// Convenience: an `Arc` media source from bytes (tries MP4/MOV then audio files).diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rsnew file mode 100644index 000000000..90abae2b8--- /dev/null+++ b/crates/codecs/src/mkv.rs@@ -0,0 +1,377 @@+//! Matroska/WebM media source (`filmcraft-matroska` demux, GOP-aware video via [`crate::gop`]).+//!+//! Video codecs are mapped onto ISO-BMFF sample entries so the same decoder factories serve both+//! containers (H.264, HEVC, ProRes, MJPEG; VP9/AV1 once their decoders land). Audio: AAC via our+//! decoder, PCM directly, MP3/FLAC/Vorbis via the bootstrap decoders.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};++use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};+use filmcraft_frame::{AudioBuffer, VideoFrame};+use filmcraft_isobmff::{AvcConfig, FourCc, HevcConfig, PcmConfig, SampleEntry};+use filmcraft_matroska::{Codec, MkvFile, TrackKind};+use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};+use filmcraft_time::{FrameRate, Tick};++use crate::audio::{PacketDecoder, decode_pcm};+use crate::gop::{GopCache, VideoSamples};+use crate::video::VideoDecoder;+use crate::{CodecError, make_video_decoder};++pub fn sniff(b: &[u8]) -> bool {+ b.len() >= 4 && b[..4] == [0x1A, 0x45, 0xDF, 0xA3]+}++struct AudioState {+ decoder: Option<PacketDecoder>,+ packets: HashMap<usize, Arc<Vec<Vec<f32>>>>,+ order: Vec<usize>,+ last_decoded: Option<usize>,+}++pub struct MkvSource {+ info: MediaInfo,+ bytes: Arc<[u8]>,+ file: MkvFile,+ vtrack: Option<usize>,+ atrack: Option<usize>,+ /// Video codec as an ISO-BMFF sample entry (for the decoder factories).+ ventry: Option<SampleEntry>,+ video: GopCache,+ audio: Mutex<AudioState>,+ /// Audio packet start positions in source sample frames.+ audio_starts: Vec<i64>,+}++/// Seconds per track timestamp unit as a rational.+fn tb(t: &filmcraft_matroska::Track) -> (i64, i64) {+ (t.timebase.0.max(1) as i64, t.timebase.1.max(1) as i64)+}++fn to_tick(t: &filmcraft_matroska::Track, pts: i64) -> Tick {+ let (n, d) = tb(t);+ Tick::from_rational(pts * n, 1, d)+}++fn from_tick(t: &filmcraft_matroska::Track, time: Tick) -> i64 {+ let (n, d) = tb(t);+ time.to_rational_floor(n, d)+}++fn sample_entry(c: &Codec, w: u16, h: u16) -> Option<SampleEntry> {+ Some(match c {+ Codec::Avc { avcc } => SampleEntry::avc(AvcConfig::parse(avcc).ok()?, w, h),+ Codec::Hevc { hvcc } => SampleEntry::hevc(HevcConfig::parse(hvcc).ok()?, w, h),+ Codec::ProRes { fourcc } => SampleEntry::prores(FourCc(fourcc.unwrap_or(*b"apcn")), w, h),+ Codec::Mjpeg => SampleEntry::jpeg(w, h),+ _ => return None,+ })+}++fn color_of(v: &filmcraft_matroska::VideoInfo, w: u32, h: u32) -> (ColorInfo, bool) {+ let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };+ let Some(col) = &v.colour else { return (c, false) };+ let mut explicit = false;+ if let Some(m) = col.matrix_coefficients.and_then(|m| Matrix::from_code(m as u8)) {+ c.matrix = m;+ explicit = true;+ }+ if let Some(t) = col.transfer_characteristics.and_then(|t| Transfer::from_code(t as u8)) {+ c.transfer = t;+ explicit = true;+ }+ if let Some(p) = col.primaries {+ c.primaries = match p {+ 9 => Primaries::Bt2020,+ 12 => Primaries::P3D65,+ 5 => Primaries::Bt601_625,+ 6 => Primaries::Bt601_525,+ _ => Primaries::Bt709,+ };+ }+ if col.full_range() {+ c.range = Range::Full;+ explicit = true;+ }+ (c, explicit)+}++fn codec_label(c: &Codec) -> String {+ match c {+ Codec::Avc { .. } => "H.264".into(),+ Codec::Hevc { .. } => "HEVC".into(),+ Codec::Vp8 => "VP8".into(),+ Codec::Vp9 { .. } => "VP9".into(),+ Codec::Av1 { .. } => "AV1".into(),+ Codec::ProRes { .. } => "Apple ProRes".into(),+ Codec::Mjpeg => "Motion JPEG".into(),+ Codec::Aac { .. } => "AAC".into(),+ Codec::Opus { .. } => "Opus".into(),+ Codec::Vorbis { .. } => "Vorbis".into(),+ Codec::Flac { .. } => "FLAC".into(),+ Codec::Pcm { bits, float, .. } => format!("PCM {bits}-bit{}", if *float { " float" } else { "" }),+ Codec::Mp3 => "MP3".into(),+ other => other.name().to_string(),+ }+}++impl MkvSource {+ pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {+ let file = filmcraft_matroska::open(&bytes[..]).map_err(|e| CodecError::Container(e.to_string()))?;+ let vtrack = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty());+ let atrack = file.tracks.iter().position(|t| t.kind == TrackKind::Audio && !t.samples.is_empty());+ if vtrack.is_none() && atrack.is_none() {+ return Err(CodecError::Unsupported("no playable tracks".into()));+ }+ let mut explicit_color = None;+ let mut ventry = None;+ let video = vtrack.map(|i| {+ let t = &file.tracks[i];+ let v = t.video.clone().unwrap_or_default();+ let (w, h) = (v.pixel_width, v.pixel_height);+ let rate = match t.default_duration_ns {+ Some(ns) if ns > 0 => FrameRate::from_f64(1e9 / ns as f64),+ _ => {+ let mut d: Vec<i64> = t.samples.windows(2).take(240).map(|p| (p[1].pts - p[0].pts).abs()).filter(|d| *d > 0).collect();+ d.sort_unstable();+ let (n, dd) = tb(t);+ let step = d.get(d.len() / 2).copied().unwrap_or(1).max(1) as f64 * n as f64 / dd as f64;+ FrameRate::from_f64(1.0 / step)+ }+ };+ let (color, explicit) = color_of(&v, w, h);+ if explicit {+ explicit_color = Some(color);+ }+ ventry = sample_entry(&t.codec, w as u16, h as u16);+ let secs = file.duration_ns().unwrap_or(0) as f64 / 1e9;+ let bitrate = (secs > 0.0).then(|| (t.samples.iter().map(|s| s.size as u64).sum::<u64>() as f64 * 8.0 / secs) as u64);+ VideoStreamInfo {+ width: w,+ height: h,+ frame_rate: rate,+ par: v.pixel_aspect(),+ codec: codec_label(&t.codec),+ pixel_format: String::new(),+ color,+ has_alpha: v.alpha_mode != 0,+ bitrate,+ }+ });+ let audio = atrack.map(|i| {+ let t = &file.tracks[i];+ let a = t.audio.clone().unwrap_or_default();+ let rate = a.output_sampling_frequency.unwrap_or(a.sampling_frequency).round().max(1.0) as u32;+ AudioStreamInfo {+ sample_rate: rate,+ channels: (a.channels as u32).max(1),+ codec: codec_label(&t.codec),+ bits_per_sample: a.bit_depth.map(|b| b as u32),+ }+ });+ let duration = match file.duration_ns() {+ Some(ns) => Tick::from_rational(ns as i64, 1, 1_000_000_000),+ None => vtrack+ .or(atrack)+ .map(|i| {+ let t = &file.tracks[i];+ let end = t.samples.iter().map(|s| s.pts + s.duration as i64).max().unwrap_or(0);+ to_tick(t, end)+ })+ .unwrap_or_default(),+ };+ let info = MediaInfo {+ name: name.to_string(),+ kind: if video.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly },+ duration,+ video,+ audio,+ container: if file.is_webm() { "WebM".into() } else { "Matroska".into() },+ start_timecode: None,+ file_size: Some(bytes.len() as u64),+ };+ let audio_starts = atrack+ .map(|i| {+ let t = &file.tracks[i];+ let rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64;+ let (n, d) = tb(t);+ t.samples.iter().map(|s| (s.pts as i128 * n as i128 * rate as i128 / d as i128) as i64).collect()+ })+ .unwrap_or_default();+ Ok(Self {+ info,+ bytes,+ file,+ vtrack,+ atrack,+ ventry,+ video: GopCache::new(explicit_color),+ audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),+ audio_starts,+ })+ }++ fn read(&self, track: usize, i: usize) -> crate::Result<Vec<u8>> {+ self.file.read_sample(&self.bytes[..], track, i).map_err(|e| CodecError::Container(e.to_string()))+ }++ fn audio_decoder(&self, c: &Codec, rate: u32) -> crate::Result<PacketDecoder> {+ use symphonia::core::codecs::{CODEC_TYPE_FLAC, CODEC_TYPE_MP3, CODEC_TYPE_VORBIS};+ match c {+ Codec::Aac { asc } => PacketDecoder::aac(asc, rate),+ Codec::Mp3 => PacketDecoder::new(CODEC_TYPE_MP3, rate, None),+ // symphonia wants the STREAMINFO block body: skip `fLaC` + the 4-byte block header.+ Codec::Flac { private } => PacketDecoder::new(CODEC_TYPE_FLAC, rate, private.get(8..42).map(<[u8]>::to_vec)),+ Codec::Vorbis { headers } if headers.len() == 3 => {+ let mut extra = headers[0].clone();+ extra.extend_from_slice(&headers[2]);+ PacketDecoder::new(CODEC_TYPE_VORBIS, rate, Some(extra))+ }+ other => Err(CodecError::Unsupported(format!("{} audio", codec_label(other)))),+ }+ }++ fn audio_packet(&self, st: &mut AudioState, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {+ if let Some(p) = st.packets.get(&i) {+ return Ok(p.clone());+ }+ let ti = self.atrack.expect("audio");+ let track = &self.file.tracks[ti];+ let ainfo = self.info.audio.as_ref().expect("audio info");+ let data = self.read(ti, i)?;+ let decoded = match &track.codec {+ Codec::Pcm { float, big_endian, bits } => {+ let cfg = PcmConfig {+ bits: *bits,+ float: *float,+ big_endian: *big_endian,+ signed: *bits > 8,+ channels: ainfo.channels,+ sample_rate: ainfo.sample_rate as f64,+ };+ decode_pcm(&data, &cfg)+ }+ c => {+ if st.decoder.is_none() {+ st.decoder = Some(self.audio_decoder(c, ainfo.sample_rate)?);+ }+ // Non-sequential access: reset and prime with the previous packet (codec pre-roll).+ if st.last_decoded.is_none_or(|l| l + 1 != i) {+ let d = st.decoder.as_mut().expect("decoder");+ d.reset();+ if i > 0+ && let Ok(prev) = self.read(ti, i - 1)+ {+ let _ = d.decode(&prev, 0);+ }+ }+ let r = st.decoder.as_mut().expect("decoder").decode(&data, self.audio_starts[i].max(0) as u64);+ st.last_decoded = Some(i);+ r.unwrap_or_default()+ }+ };+ let p = Arc::new(decoded);+ st.packets.insert(i, p.clone());+ st.order.push(i);+ if st.order.len() > 4096 {+ let old = st.order.remove(0);+ st.packets.remove(&old);+ }+ Ok(p)+ }+}++/// The Matroska video track as a [`VideoSamples`] table.+struct MkvVideo<'a> {+ src: &'a MkvSource,+ track: usize,+}++impl VideoSamples for MkvVideo<'_> {+ fn count(&self) -> usize {+ self.src.file.tracks[self.track].samples.len()+ }+ fn pts(&self, i: usize) -> i64 {+ self.src.file.tracks[self.track].samples[i].pts+ }+ fn sync_before(&self, i: usize) -> usize {+ self.src.file.tracks[self.track].sync_sample_before(i)+ }+ fn sample_at(&self, t: i64) -> Option<usize> {+ self.src.file.tracks[self.track].sample_at_pts(t)+ }+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {+ self.src.read(self.track, i)+ }+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {+ match &self.src.ventry {+ Some(e) => make_video_decoder(e),+ None => Err(CodecError::Unsupported(format!("no decoder for {} video", codec_label(&self.src.file.tracks[self.track].codec)))),+ }+ }+}++impl MediaSource for MkvSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }++ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {+ let ti = self.vtrack.ok_or(MediaError::NoStream("video"))?;+ let target = from_tick(&self.file.tracks[ti], req.time.max(Tick::ZERO));+ Ok(self.video.frame(&MkvVideo { src: self, track: ti }, target)?)+ }++ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer, MediaError> {+ let ti = self.atrack.ok_or(MediaError::NoStream("audio"))?;+ let n_packets = self.file.tracks[ti].samples.len();+ let ainfo = self.info.audio.as_ref().ok_or(MediaError::NoStream("audio"))?;+ let src_rate = ainfo.sample_rate;+ let ch = ainfo.channels.max(1) as usize;+ let ratio = src_rate as f64 / sample_rate as f64;+ let s0 = (start as f64 * ratio).floor() as i64;+ let need = (frames as f64 * ratio).ceil() as i64 + 2;+ let mut src: Vec<Vec<f32>> = vec![vec![0.0; need.max(0) as usize]; ch];+ let mut st = self.audio.lock().unwrap_or_else(|e| e.into_inner());+ let mut i = self.audio_starts.partition_point(|&x| x <= s0).saturating_sub(1);+ while i < n_packets {+ let pk_start = self.audio_starts[i];+ if pk_start >= s0 + need {+ break;+ }+ let pk = self.audio_packet(&mut st, i)?;+ for (c, dst) in src.iter_mut().enumerate() {+ let Some(chan) = pk.get(c.min(pk.len().saturating_sub(1))) else { continue };+ for (k, v) in chan.iter().enumerate() {+ let pos = pk_start + k as i64 - s0;+ if pos >= 0 && (pos as usize) < dst.len() {+ dst[pos as usize] = *v;+ }+ }+ }+ i += 1;+ }+ drop(st);+ let frac = s0 as f64 - start as f64 * ratio;+ let mut out = AudioBuffer::silence(sample_rate, ch, frames);+ for k in 0..frames {+ let pos = k as f64 * ratio - frac;+ let i0 = pos.floor().max(0.0) as usize;+ let f = (pos - i0 as f64) as f32;+ for c in 0..ch {+ let a = src[c].get(i0).copied().unwrap_or(0.0);+ let b = src[c].get(i0 + 1).copied().unwrap_or(a);+ out.channels[c][k] = a + (b - a) * f;+ }+ }+ Ok(out)+ }+}++pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {+ if !sniff(&bytes) {+ return None;+ }+ Some(MkvSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))+}diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rsindex cb2de8bc6..4497bc2f2 100644--- a/crates/codecs/src/mp4.rs+++ b/crates/codecs/src/mp4.rs@@ -1,10 +1,6 @@-//! MP4/MOV media source with GOP-aware random access.-//!-//! Seeking: find the sample whose presentation interval covers the requested time, decode forward-//! from the preceding sync sample, and cache every decoded frame (keyed by pts). Playback requests-//! for the next frames therefore hit the cache or continue the running decoder without re-seeking.+//! MP4/MOV media source with GOP-aware random access (see [`crate::gop`]).-use std::collections::{BTreeMap, HashMap};+use std::collections::HashMap;use std::sync::{Arc, Mutex};use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};@@ -14,18 +10,10 @@ use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, Mediuse filmcraft_time::{FrameRate, Tick};use crate::audio::{PacketDecoder, decode_pcm};+use crate::gop::{GopCache, VideoSamples};use crate::video::VideoDecoder;use crate::{CodecError, make_video_decoder};-struct VideoState {- decoder: Option<Box<dyn VideoDecoder>>,- /// Next sample (decode order) to feed.- next: usize,- /// Decoded frames by presentation pts (bounded).- frames: BTreeMap<i64, Arc<VideoFrame>>,- bytes: usize,-}-struct AudioState {decoder: Option<PacketDecoder>,/// Decoded packets by sample index.@@ -40,13 +28,10 @@ pub struct Mp4Source {file: Mp4File,vtrack: Option<usize>,atrack: Option<usize>,- video: Mutex<VideoState>,+ video: GopCache,audio: Mutex<AudioState>,- /// Colour from an explicit `colr` box, if the file has one.- explicit_color: Option<ColorInfo>,/// Cumulative sample start frames for the audio track (for packet lookup).audio_starts: Vec<i64>,- cache_budget: usize,}pub fn sniff(b: &[u8]) -> bool {@@ -184,11 +169,9 @@ impl Mp4Source {file,vtrack,atrack,- video: Mutex::new(VideoState { decoder: None, next: usize::MAX, frames: BTreeMap::new(), bytes: 0 }),+ video: GopCache::new(explicit_color),audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),- explicit_color,audio_starts,- cache_budget: 384 << 20,})}@@ -196,80 +179,10 @@ impl Mp4Source {self.file.read_sample(&self.bytes[..], track, i).map_err(|e| CodecError::Container(e.to_string()))}- fn store(&self, st: &mut VideoState, pts: i64, mut f: VideoFrame) {- // An explicit container `colr` box wins; otherwise keep what the decoder signalled.- if let Some(c) = self.explicit_color- && !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_) | filmcraft_frame::PixelData::RgbaF32(_))- {- f.color = c;- }- st.bytes += f.byte_size();- st.frames.insert(pts, Arc::new(f));- // evict frames far from the most recent (keep a window around the working position)- while st.bytes > self.cache_budget && st.frames.len() > 2 {- let first = *st.frames.keys().next().expect("non-empty");- let last = *st.frames.keys().next_back().expect("non-empty");- let victim = if pts - first > last - pts { first } else { last };- if let Some(v) = st.frames.remove(&victim) {- st.bytes -= v.byte_size();- }- }- }-fn video_at(&self, t: Tick) -> crate::Result<Arc<VideoFrame>> {let ti = self.vtrack.ok_or_else(|| CodecError::Unsupported("no video".into()))?;- let track = &self.file.tracks[ti];- let ts = track.timescale as i64;- let target = t.to_rational_floor(1, ts).max(0);- let i = track- .sample_at_presentation_time(target)- .or_else(|| (!track.samples.is_empty()).then(|| track.samples.len() - 1))- .ok_or_else(|| CodecError::Decode("empty track".into()))?;- let want_pts = track.samples[i].pts;- let mut st = self.video.lock().unwrap_or_else(|e| e.into_inner());- if let Some(f) = st.frames.get(&want_pts) {- return Ok(f.clone());- }- if st.decoder.is_none() {- st.decoder = Some(make_video_decoder(&track.entries[0])?);- st.next = usize::MAX;- }- let key = track.sync_sample_before(i);- // Continue the running decoder when the wanted sample is ahead within this GOP run.- let continuing = st.next != usize::MAX && st.next > key && st.next <= i + 16 && st.next <= track.samples.len();- if !continuing {- if let Some(d) = st.decoder.as_mut() {- d.reset();- }- st.next = key;- }- let limit = (i + 64).min(track.samples.len());- while st.next < limit {- let n = st.next;- let data = self.read(ti, n)?;- let pts = track.samples[n].pts;- let out = st.decoder.as_mut().expect("decoder").decode(&data, pts)?;- st.next += 1;- for d in out {- self.store(&mut st, d.pts, d.frame);- }- if st.frames.contains_key(&want_pts) {- break;- }- }- if !st.frames.contains_key(&want_pts) {- let out = st.decoder.as_mut().expect("decoder").flush();- for d in out {- self.store(&mut st, d.pts, d.frame);- }- st.next = usize::MAX;- }- // nearest decoded frame at or before the wanted pts (robust to decoder pts quirks)- st.frames- .get(&want_pts)- .cloned()- .or_else(|| st.frames.range(..=want_pts).next_back().map(|(_, f)| f.clone()))- .ok_or_else(|| CodecError::Decode("frame not produced".into()))+ let ts = self.file.tracks[ti].timescale as i64;+ self.video.frame(&Mp4Video { src: self, track: ti }, t.to_rational_floor(1, ts))}fn audio_packet(&self, st: &mut AudioState, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {@@ -315,6 +228,33 @@ impl Mp4Source {}}+/// The MP4 video track as a [`VideoSamples`] table.+struct Mp4Video<'a> {+ src: &'a Mp4Source,+ track: usize,+}++impl VideoSamples for Mp4Video<'_> {+ fn count(&self) -> usize {+ self.src.file.tracks[self.track].samples.len()+ }+ fn pts(&self, i: usize) -> i64 {+ self.src.file.tracks[self.track].samples[i].pts+ }+ fn sync_before(&self, i: usize) -> usize {+ self.src.file.tracks[self.track].sync_sample_before(i)+ }+ fn sample_at(&self, t: i64) -> Option<usize> {+ self.src.file.tracks[self.track].sample_at_presentation_time(t)+ }+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {+ self.src.read(self.track, i)+ }+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {+ make_video_decoder(&self.src.file.tracks[self.track].entries[0])+ }+}+impl MediaSource for Mp4Source {fn info(&self) -> &MediaInfo {&self.infodiff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rsindex 77abc20fd..1adfdb3c9 100644--- a/crates/codecs/src/tests.rs+++ b/crates/codecs/src/tests.rs@@ -135,3 +135,46 @@ fn prores_mov_decodes() {let c = &px[(100 * 640 + 20) * 4..][..3];assert!((c[0] as i32 - 104).abs() < 6, "{c:?}");}++/// Solid-colour Matroska fixtures: decoded frames must match the colour, audio must be a 1 kHz tone.+fn check_mkv(name: &str, vcodec: &[&str], acodec: &[&str]) {+ let mut args: Vec<&str> =+ vec!["-f", "lavfi", "-i", "color=c=0x3060c0:s=320x240:r=25:d=2", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:d=2"];+ args.extend_from_slice(vcodec);+ args.extend_from_slice(acodec);+ let Some(b) = fixture(name, &args) else { return };+ let src = crate::open_bytes(name, b).expect("open");+ let info = src.info();+ assert_eq!(info.container, "Matroska");+ let v = info.video.as_ref().expect("video");+ assert_eq!((v.width, v.height), (320, 240));+ assert_eq!(v.frame_rate.num as f64 / v.frame_rate.den as f64, 25.0);+ let d = info.duration.0 as f64 / TICKS_PER_SECOND as f64;+ assert!((d - 2.0).abs() < 0.1, "duration {d}");+ for secs in [0.0, 1.24, 0.4] {+ let f = src.video_frame(FrameRequest { time: Tick((secs * TICKS_PER_SECOND as f64) as i64), scale: 1.0 }).expect("frame");+ let rgba = f.to_rgba8();+ let px = &rgba[(120 * 320 + 160) * 4..][..3];+ for (got, want) in px.iter().zip([0x30u8, 0x60, 0xc0]) {+ assert!((*got as i32 - want as i32).abs() <= 6, "{name} at {secs}s: {px:?}");+ }+ }+ let a = src.audio(24_000, 4800, 48_000).expect("audio");+ let peak = a.channels[0].iter().fold(0f32, |m, s| m.max(s.abs()));+ assert!(peak > 0.05 && peak < 1.0, "{name}: audio peak {peak}");+}++#[test]+fn matroska_h264_aac() {+ check_mkv("blue_h264_aac.mkv", &["-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p"], &["-c:a", "aac"]);+}++#[test]+fn matroska_hevc_flac() {+ check_mkv("blue_hevc_flac.mkv", &["-c:v", "libx265", "-x265-params", "log-level=error", "-pix_fmt", "yuv420p"], &["-c:a", "flac"]);+}++#[test]+fn matroska_prores_pcm() {+ check_mkv("blue_prores_pcm.mkv", &["-c:v", "prores_ks", "-profile:v", "2"], &["-c:a", "pcm_s16le"]);+}