Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M9.15: MPEG TS/PS/ES media source (MPEG-2, H.264, HEVC; MP2, AAC ADTS/LATM, LPCM) with ffmpeg oracle tests

Brandon Thomas1fc10b694933
diff --git a/Cargo.lock b/Cargo.lock
index 872b548c8..637edb650 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1768,6 +1768,8 @@ dependencies = [
"filmcraft-isobmff",
"filmcraft-matroska",
"filmcraft-media",
+ "filmcraft-mpeg2v",
+ "filmcraft-mpegts",
"filmcraft-mxf",
"filmcraft-ogg",
"filmcraft-opus",
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index f262d452a..432ddb0b1 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -17,6 +17,8 @@ filmcraft-media = { workspace = true }
filmcraft-isobmff = { workspace = true }
filmcraft-matroska = { workspace = true }
filmcraft-mxf = { workspace = true }
+filmcraft-mpegts = { workspace = true }
+filmcraft-mpeg2v = { workspace = true }
filmcraft-ogg = { workspace = true }
filmcraft-bitstream = { workspace = true }
filmcraft-h264 = { workspace = true }
@@ -33,7 +35,7 @@ log = { workspace = true }
web-time = "1"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
# Bootstrap audio decoding (MPL-2.0, used unmodified); replaced by own decoders over time.
-symphonia = { version = "0.5.5", default-features = false, features = ["aac", "mp3", "flac", "alac", "pcm", "wav", "ogg", "vorbis", "isomp4"] }
+symphonia = { version = "0.5.5", default-features = false, features = ["aac", "mp1", "mp2", "mp3", "flac", "alac", "pcm", "wav", "ogg", "vorbis", "isomp4"] }
[dev-dependencies]
filmcraft-testkit = { workspace = true }
diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rs
index ab7aa7d4f..53fa12627 100644
--- a/crates/codecs/src/audio.rs
+++ b/crates/codecs/src/audio.rs
@@ -17,6 +17,8 @@ use crate::{CodecError, Result};
enum Inner {
/// Our own AAC-LC decoder.
Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8> },
+ /// AAC whose configuration arrives with the first frame (ADTS / LATM).
+ AacPending,
/// Our own Opus decoder (always 48 kHz output; pre-skip is left to container timestamps).
/// `order` maps output channel → decoded channel (Vorbis → WAV/SMPTE order for surround).
Opus { dec: Box<filmcraft_opus::Decoder>, order: Option<&'static [usize]> },
@@ -94,6 +96,34 @@ impl PacketDecoder {
let order = if dec.head().mapping_family == 1 { vorbis_to_wav_order(channels) } else { None };
Ok(Self { inner: Inner::Opus { dec: Box::new(dec), order }, channels })
}
+ /// MPEG-1/2 audio layer I, II or III (symphonia).
+ pub fn mpeg_audio(layer: u8, sample_rate: u32) -> Result<Self> {
+ let codec = match layer {
+ 1 => symphonia::core::codecs::CODEC_TYPE_MP1,
+ 2 => symphonia::core::codecs::CODEC_TYPE_MP2,
+ _ => CODEC_TYPE_MP3,
+ };
+ Self::new(codec, sample_rate, None)
+ }
+ /// AAC configured by [`Self::ensure_aac`] from in-band headers (ADTS, LATM).
+ pub fn lazy_aac() -> Self {
+ Self { inner: Inner::AacPending, channels: 0 }
+ }
+ /// (Re)configure for the AudioSpecificConfig `asc` unless it is the current one.
+ pub fn ensure_aac(&mut self, asc: &[u8]) -> Result<()> {
+ if let Inner::Aac { asc: cur, .. } = &self.inner
+ && cur == asc
+ {
+ return Ok(());
+ }
+ let dec = filmcraft_aac::Decoder::new(asc).map_err(|e| CodecError::Unsupported(format!("AAC: {e}")))?;
+ self.inner = Inner::Aac { dec: Box::new(dec), asc: asc.to_vec() };
+ Ok(())
+ }
+ /// AC-3 (ATSC A/52).
+ pub fn ac3() -> Result<Self> {
+ Err(CodecError::Unsupported("AC-3 audio".into()))
+ }
/// Whether this decodes Opus (which needs [`OPUS_PRE_ROLL`] of pre-roll after a seek).
pub fn is_opus(&self) -> bool {
matches!(self.inner, Inner::Opus { .. })
@@ -130,6 +160,7 @@ impl PacketDecoder {
return Ok(out);
}
Inner::Symphonia(d) => d,
+ Inner::AacPending => return Err(CodecError::Decode("AAC: no configuration yet".into())),
};
let pkt = Packet::new_from_slice(0, ts, 0, data);
let buf = dec.decode(&pkt).map_err(|e| CodecError::Decode(e.to_string()))?;
@@ -157,8 +188,251 @@ impl PacketDecoder {
}
Inner::Opus { dec, .. } => dec.reset(),
Inner::Symphonia(d) => d.reset(),
+ Inner::AacPending => {}
+ }
+ }
+}
+
+/// Whether AC-3 audio decodes (our ATSC A/52 decoder).
+pub const AC3_DECODER: bool = false;
+
+/// An AudioSpecificConfig for AAC with these parameters (ISO/IEC 14496-3 §1.6.2.1, GA specific
+/// config with no extension flags).
+fn asc_bytes(object_type: u8, sf_index: u8, channel_config: u8) -> Vec<u8> {
+ let v = ((object_type as u16) << 11) | ((sf_index as u16 & 15) << 7) | ((channel_config as u16 & 15) << 3);
+ v.to_be_bytes().to_vec()
+}
+
+/// An ADTS frame (ISO/IEC 13818-7 §6.2): the equivalent AudioSpecificConfig and the raw data
+/// block. Frames with several raw data blocks are not split (`None`).
+pub fn adts_split(frame: &[u8]) -> Option<(Vec<u8>, &[u8])> {
+ if frame.len() < 7 || frame[0] != 0xFF || frame[1] & 0xF6 != 0xF0 {
+ return None;
+ }
+ let protection_absent = frame[1] & 1 != 0;
+ let profile = frame[2] >> 6;
+ let sf = (frame[2] >> 2) & 15;
+ let ch = ((frame[2] & 1) << 2) | (frame[3] >> 6);
+ let len = (((frame[3] & 3) as usize) << 11) | (frame[4] as usize) << 3 | (frame[5] as usize) >> 5;
+ if frame[6] & 3 != 0 {
+ return None;
+ }
+ let hdr = if protection_absent { 7 } else { 9 };
+ let end = len.min(frame.len());
+ (end > hdr).then(|| (asc_bytes(profile + 1, sf, ch), &frame[hdr..end]))
+}
+
+/// The parts of a LATM StreamMuxConfig (ISO/IEC 14496-3 §1.7.3) we decode: one program, one
+/// layer, AAC-LC, variable frame length (type 0).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LatmConfig {
+ pub asc: Vec<u8>,
+ pub sample_rate: u32,
+ pub channels: u32,
+}
+
+const AAC_RATES: [u32; 13] = [96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000, 7_350];
+
+fn latm_value(r: &mut filmcraft_bitstream::BitReader) -> Option<u32> {
+ let n = r.read_bits(2).ok()? + 1;
+ r.read_bits(8 * n).ok()
+}
+
+/// StreamMuxConfig after `audioMuxVersion`, leaving the reader after it.
+fn stream_mux_config(r: &mut filmcraft_bitstream::BitReader) -> Option<LatmConfig> {
+ let version = r.read_bits(1).ok()?;
+ let version_a = if version == 1 { r.read_bits(1).ok()? } else { 0 };
+ if version_a != 0 {
+ return None;
+ }
+ if version == 1 {
+ latm_value(r)?; // taraBufferFullness
+ }
+ let _all_same_framing = r.read_bits(1).ok()?;
+ let sub_frames = r.read_bits(6).ok()?;
+ let programs = r.read_bits(4).ok()?;
+ let layers = r.read_bits(3).ok()?;
+ if sub_frames != 0 || programs != 0 || layers != 0 {
+ return None;
+ }
+ if version == 1 {
+ latm_value(r)?; // ascLen
+ }
+ // AudioSpecificConfig
+ let aot = r.read_bits(5).ok()?;
+ let sf = r.read_bits(4).ok()?;
+ if aot != 2 || sf == 15 {
+ return None;
+ }
+ let ch = r.read_bits(4).ok()?;
+ let frame_length_flag = r.read_bits(1).ok()?;
+ let depends_on_core = r.read_bits(1).ok()?;
+ let _extension = r.read_bits(1).ok()?;
+ if frame_length_flag != 0 || depends_on_core != 0 {
+ return None;
+ }
+ let frame_length_type = r.read_bits(3).ok()?;
+ if frame_length_type != 0 {
+ return None;
+ }
+ r.read_bits(8).ok()?; // latmBufferFullness
+ if r.read_bits(1).ok()? == 1 {
+ // otherData
+ if version == 1 {
+ latm_value(r)?;
+ } else {
+ loop {
+ let esc = r.read_bits(1).ok()?;
+ r.read_bits(8).ok()?;
+ if esc == 0 {
+ break;
+ }
+ }
+ }
+ }
+ if r.read_bits(1).ok()? == 1 {
+ r.read_bits(8).ok()?; // crcCheckSum
+ }
+ Some(LatmConfig { asc: asc_bytes(2, sf as u8, ch as u8), sample_rate: *AAC_RATES.get(sf as usize)?, channels: if ch == 0 { 2 } else { ch } })
+}
+
+/// The configuration carried in a LOAS frame (`None` if it reuses an earlier one or is not
+/// supported).
+pub fn latm_config(frame: &[u8]) -> Option<LatmConfig> {
+ if frame.len() < 4 || frame[0] != 0x56 || frame[1] & 0xE0 != 0xE0 {
+ return None;
+ }
+ let mut r = filmcraft_bitstream::BitReader::new(&frame[3..]);
+ if r.read_bits(1).ok()? == 1 {
+ return None; // useSameStreamMux
+ }
+ stream_mux_config(&mut r)
+}
+
+/// A LOAS/LATM frame: its AudioSpecificConfig and the AAC payload of the single sub-frame.
+/// `last` is the configuration of earlier frames (used by frames that set useSameStreamMux,
+/// updated by frames that carry one).
+pub fn latm_split(frame: &[u8], last: &mut Option<LatmConfig>) -> Option<(Vec<u8>, Vec<u8>)> {
+ if frame.len() < 4 || frame[0] != 0x56 || frame[1] & 0xE0 != 0xE0 {
+ return None;
+ }
+ let mut r = filmcraft_bitstream::BitReader::new(&frame[3..]);
+ let same = r.read_bits(1).ok()? == 1;
+ let cfg = if same {
+ last.clone()?
+ } else {
+ let c = stream_mux_config(&mut r)?;
+ *last = Some(c.clone());
+ c
+ };
+ // PayloadLengthInfo (frameLengthType 0) then PayloadMux, bit-aligned
+ let mut len = 0usize;
+ loop {
+ let b = r.read_bits(8).ok()? as usize;
+ len += b;
+ if b != 255 {
+ break;
+ }
+ }
+ let mut payload = Vec::with_capacity(len);
+ for _ in 0..len {
+ payload.push(r.read_bits(8).ok()? as u8);
+ }
+ Some((cfg.asc, payload))
+}
+
+/// Blu-ray / AVCHD LPCM packet header (4 bytes before the samples).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BlurayLpcm {
+ pub sample_rate: u32,
+ pub channels: usize,
+ pub bits: u32,
+}
+
+/// Channels of each channel_assignment code (mono, stereo, 3/0, 2/1, 3/1, 2/2, 3/2, 3/2+LFE,
+/// 3/4, 3/4+LFE).
+const BD_LPCM_CHANNELS: [usize; 12] = [0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8];
+
+pub fn bluray_lpcm_header(p: &[u8]) -> Option<BlurayLpcm> {
+ if p.len() < 4 {
+ return None;
+ }
+ let channels = *BD_LPCM_CHANNELS.get((p[2] >> 4) as usize).filter(|&&c| c > 0)?;
+ let sample_rate = match p[2] & 15 {
+ 1 => 48_000,
+ 4 => 96_000,
+ 5 => 192_000,
+ _ => return None,
+ };
+ let bits = match p[3] >> 6 {
+ 1 => 16,
+ 2 => 20,
+ 3 => 24,
+ _ => return None,
+ };
+ Some(BlurayLpcm { sample_rate, channels, bits })
+}
+
+/// Decode one Blu-ray LPCM packet (big-endian; channels padded to an even count; 20-bit
+/// samples are stored in 24 bits).
+pub fn decode_bluray_lpcm(p: &[u8]) -> Option<Vec<Vec<f32>>> {
+ let h = bluray_lpcm_header(p)?;
+ let coded = (h.channels + 1) & !1;
+ let bps = if h.bits == 16 { 2 } else { 3 };
+ let data = &p[4..];
+ let n = data.len() / (coded * bps);
+ let mut out = vec![Vec::with_capacity(n); h.channels];
+ for k in 0..n {
+ for (c, o) in out.iter_mut().enumerate() {
+ let at = (k * coded + c) * bps;
+ let v = if bps == 2 {
+ i16::from_be_bytes([data[at], data[at + 1]]) as f32 / 32768.0
+ } else {
+ (i32::from_be_bytes([data[at], data[at + 1], data[at + 2], 0]) >> 8) as f32 / 8_388_608.0
+ };
+ o.push(v);
}
}
+ Some(out)
+}
+
+/// Bytes per two sample frames of DVD LPCM.
+pub fn dvd_lpcm_group_bytes(channels: usize, bits: u32) -> usize {
+ match bits {
+ 16 => 4 * channels,
+ 20 => 5 * channels,
+ _ => 6 * channels,
+ }
+}
+
+/// Decode DVD-Video LPCM (big-endian). 16-bit samples are interleaved; 20- and 24-bit samples
+/// come in groups of two frames: the upper 16 bits of all the group's samples, then their low
+/// 4 / 8 bits.
+pub fn decode_dvd_lpcm(data: &[u8], channels: usize, bits: u32) -> Vec<Vec<f32>> {
+ let ch = channels.max(1);
+ let group = dvd_lpcm_group_bytes(ch, bits);
+ let groups = data.len() / group;
+ let mut out = vec![Vec::with_capacity(groups * 2); ch];
+ for g in 0..groups {
+ let b = &data[g * group..(g + 1) * group];
+ for f in 0..2 {
+ for (c, o) in out.iter_mut().enumerate() {
+ let k = f * ch + c;
+ let hi = i16::from_be_bytes([b[2 * k], b[2 * k + 1]]) as i32;
+ let v = match bits {
+ 16 => hi as f32 / 32768.0,
+ 20 => {
+ let nib = b[4 * ch + k / 2];
+ let lo = if k.is_multiple_of(2) { nib >> 4 } else { nib & 15 } as i32;
+ ((hi << 4) | lo) as f32 / 524_288.0
+ }
+ _ => ((hi << 8) | b[4 * ch + k] as i32) as f32 / 8_388_608.0,
+ };
+ o.push(v);
+ }
+ }
+ }
+ out
}
/// Decode interleaved PCM bytes into planar f32.
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index a93c99bf8..a51b0b9f3 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -17,6 +17,7 @@ pub mod audio;
pub mod gop;
pub mod mkv;
pub mod mp4;
+pub mod mpeg;
pub mod mxf;
pub mod ogg;
pub mod video;
@@ -27,6 +28,7 @@ pub use audio::AudioFileSource;
pub use gop::{GopStats, gop_stats};
pub use mkv::MkvSource;
pub use mp4::Mp4Source;
+pub use mpeg::MpegSource;
pub use mxf::MxfSource;
pub use ogg::OggSource;
pub use video::{DecodedFrame, VideoDecoder, VideoDecoderFactory};
@@ -67,6 +69,7 @@ fn factories() -> &'static RwLock<Vec<VideoDecoderFactory>> {
video::prores_factory,
video::dnx_factory,
video::mjpeg_factory,
+ video::mpeg2_factory,
])
})
}
@@ -90,14 +93,15 @@ 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, Matroska/WebM, MXF, Ogg Opus/Vorbis, standalone audio).
+/// Openers for the engine's media pool (MP4/MOV, Matroska/WebM, MXF, Ogg Opus/Vorbis, MPEG TS/PS and
+/// MPEG-1/2 video elementary streams, standalone audio).
pub fn openers() -> Vec<filmcraft_media::Opener> {
- vec![mp4::opener, mkv::opener, mxf::opener, ogg::opener, audio::opener]
+ vec![mp4::opener, mkv::opener, mxf::opener, ogg::opener, mpeg::opener, audio::opener]
}
fn reader_registry() -> &'static RwLock<Vec<filmcraft_media::ReaderOpener>> {
static R: std::sync::OnceLock<RwLock<Vec<filmcraft_media::ReaderOpener>>> = std::sync::OnceLock::new();
- R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener, mxf::reader_opener, ogg::reader_opener]))
+ R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener, mxf::reader_opener, ogg::reader_opener, mpeg::reader_opener]))
}
/// Openers that read containers through a [`filmcraft_media::ByteReader`] (index now, samples on
diff --git a/crates/codecs/src/mpeg.rs b/crates/codecs/src/mpeg.rs
new file mode 100644
index 000000000..551ef8901
--- /dev/null
+++ b/crates/codecs/src/mpeg.rs
@@ -0,0 +1,849 @@
+//! MPEG-2 transport streams (`.ts`, `.m2ts`, `.mts`), program streams (`.mpg`, `.vob`, `.mod`)
+//! and MPEG-1/2 video elementary streams (`.m2v`, `.m1v`).
+//!
+//! - Demux and the access-unit index come from `filmcraft-mpegts` (built when the file opens).
+//! - Video: MPEG-1/2 (our decoder), H.264 and HEVC (Annex B byte streams, our decoders) with
+//! GOP-aware random access ([`crate::gop`]). Frames are presented in display order, from the
+//! first random-access picture; display order comes from the PTS (or, without timestamps, the
+//! GOP and temporal reference). Leading pictures of an open GOP decode from the previous GOP.
+//! - Audio: MPEG audio layers I-III (symphonia), AAC in ADTS or LATM (our decoder), AC-3 (our
+//! decoder), Blu-ray / AVCHD and DVD LPCM. Audio frames are placed on the timeline from their
+//! PTS relative to the first video frame, sample-contiguously (re-anchored only at gaps).
+
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex};
+
+use filmcraft_frame::{AudioBuffer, VideoFrame};
+use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};
+use filmcraft_mpegts::{Codec, File, Kind, Unit};
+use filmcraft_time::{FrameRate, Tick};
+
+use crate::CodecError;
+use crate::gop::{GopCache, VideoSamples};
+use crate::video::{H264Decoder, HevcDecoder, Mpeg2Decoder, VideoDecoder};
+
+impl filmcraft_mpegts::ByteSource for crate::Src {
+ fn len(&self) -> u64 {
+ self.0.len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
+ self.0.read_at(offset, buf)
+ }
+}
+
+/// An MPEG-1/2 video elementary stream starts with a sequence header.
+fn is_video_es(head: &[u8]) -> bool {
+ head.starts_with(&[0, 0, 1, 0xB3])
+}
+
+pub fn sniff(head: &[u8]) -> bool {
+ filmcraft_mpegts::sniff(head).is_some() || is_video_es(head)
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum VKind {
+ Mpeg2,
+ H264,
+ Hevc,
+}
+
+/// The presented video: samples in decode order from the first random-access unit.
+struct VideoTrack {
+ kind: VKind,
+ /// Stream index in the demuxed file (unused for elementary streams).
+ stream: usize,
+ /// Unit indices (into the stream's units, or the elementary stream's access units).
+ units: Vec<usize>,
+ keys: Vec<bool>,
+ /// Display position of each sample (negative: not presented).
+ pts: Vec<i64>,
+ /// Display position → sample.
+ order: Vec<usize>,
+ /// MPEG-2 sequence header for priming decoders.
+ header: Vec<u8>,
+}
+
+#[derive(Clone, Copy, Debug)]
+enum ACodec {
+ Mpa(u8),
+ Adts,
+ Latm,
+ Ac3,
+ LpcmBluray,
+ LpcmDvd(filmcraft_mpegts::LpcmFormat),
+}
+
+struct AudioState {
+ dec: Option<AudioDecoder>,
+ cache: HashMap<usize, Arc<Vec<Vec<f32>>>>,
+ order: VecDeque<usize>,
+ last: Option<usize>,
+}
+
+struct AudioTrack {
+ stream: usize,
+ codec: ACodec,
+ rate: u32,
+ channels: usize,
+ /// Presentation sample (at `rate`, relative to the first video frame) of each unit.
+ starts: Vec<i64>,
+ /// Samples in each unit.
+ lens: Vec<u32>,
+ /// LATM: the stream's configuration (frames may only reference it).
+ latm: Option<crate::audio::LatmConfig>,
+ /// DVD LPCM: byte offset of each unit in the elementary stream (and the end).
+ byte_starts: Vec<u64>,
+ state: Mutex<AudioState>,
+}
+
+pub struct MpegSource {
+ info: MediaInfo,
+ bytes: crate::Src,
+ file: Option<File>,
+ /// Elementary stream: the whole file and its access units.
+ es: Option<(Arc<[u8]>, Vec<std::ops::Range<usize>>)>,
+ video: Option<VideoTrack>,
+ gop: GopCache,
+ audio: Option<AudioTrack>,
+ /// Why the video or audio stream cannot be decoded.
+ unsupported_video: Option<String>,
+ unsupported_audio: Option<String>,
+}
+
+fn vkind(c: &Codec) -> Option<VKind> {
+ match c {
+ Codec::Mpeg1Video | Codec::Mpeg2Video => Some(VKind::Mpeg2),
+ Codec::H264 => Some(VKind::H264),
+ Codec::Hevc => Some(VKind::Hevc),
+ _ => None,
+ }
+}
+
+fn audio_supported(c: &Codec) -> bool {
+ matches!(c, Codec::MpegAudio | Codec::AacAdts | Codec::AacLatm | Codec::LpcmBluray | Codec::LpcmDvd | Codec::Ac3)
+}
+
+/// Display-order keys of samples (decode order): the PTS when every unit has one, else (MPEG
+/// video) GOP start + temporal_reference, else the decode order.
+fn display_keys(units: &[&Unit], mpeg: bool) -> Vec<i64> {
+ if units.iter().all(|u| u.pts.is_some()) {
+ return units.iter().map(|u| u.pts.unwrap_or(0)).collect();
+ }
+ if mpeg {
+ let mut out = Vec::with_capacity(units.len());
+ let mut base = 0i64;
+ for (i, u) in units.iter().enumerate() {
+ if let Some(p) = u.picture
+ && (p.gop || i == 0)
+ {
+ base = i as i64;
+ }
+ out.push(base + u.picture.map_or(0, |p| p.temporal_reference as i64));
+ }
+ // scale so that a later GOP never sorts before an earlier one
+ return out.iter().map(|&k| k * 4).collect();
+ }
+ let mut last = i64::MIN / 4;
+ units
+ .iter()
+ .map(|u| {
+ last = u.pts.unwrap_or(last + 1);
+ last
+ })
+ .collect()
+}
+
+/// Presentation order of `keys` (decode order) from sample 0 (a random-access unit): samples
+/// shown before it (leading pictures without their references) are not presented.
+fn presentation(keys: &[i64]) -> (Vec<i64>, Vec<usize>) {
+ let mut idx: Vec<usize> = (0..keys.len()).filter(|&i| keys[i] >= keys[0]).collect();
+ idx.sort_by_key(|&i| (keys[i], i));
+ let mut pts = vec![0i64; keys.len()];
+ for (i, p) in pts.iter_mut().enumerate() {
+ *p = -(i as i64) - 1;
+ }
+ for (d, &i) in idx.iter().enumerate() {
+ pts[i] = d as i64;
+ }
+ (pts, idx)
+}
+
+impl MpegSource {
+ pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {
+ Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))
+ }
+
+ /// Open from a random-access reader: the whole file is scanned once to index its access units.
+ pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {
+ let bytes = crate::Src(reader);
+ let head = filmcraft_media::reader::read_range(&*bytes.0, 0, 4096).map_err(|e| CodecError::Container(e.to_string()))?;
+ if is_video_es(&head) {
+ return Self::open_es(name, bytes);
+ }
+ let file = filmcraft_mpegts::open(&bytes).map_err(|e| match e {
+ filmcraft_mpegts::Error::NotMpeg => CodecError::Unsupported("not an MPEG stream".into()),
+ other => CodecError::Container(other.to_string()),
+ })?;
+ for w in &file.warnings {
+ log::warn!("{name}: {w}");
+ }
+ let vstream = file.find(Kind::Video, |c| vkind(c).is_some()).or_else(|| file.find(Kind::Video, |_| true));
+ let astream = file.find(Kind::Audio, audio_supported).or_else(|| file.find(Kind::Audio, |_| true));
+ if vstream.is_none() && astream.is_none() {
+ return Err(CodecError::Unsupported(format!("{}: no video or audio streams", file.format.name())));
+ }
+ let mut src = MpegSource {
+ info: MediaInfo {
+ name: name.to_string(),
+ kind: MediaKind::Movie,
+ duration: Tick::ZERO,
+ video: None,
+ audio: None,
+ container: file.format.name().to_string(),
+ start_timecode: None,
+ file_size: Some(bytes.0.len()),
+ },
+ bytes,
+ file: None,
+ es: None,
+ video: None,
+ gop: GopCache::new(None),
+ audio: None,
+ unsupported_video: None,
+ unsupported_audio: None,
+ };
+ // video
+ let origin;
+ if let Some(vi) = vstream {
+ let st = &file.streams[vi];
+ match vkind(&st.codec) {
+ Some(kind) => {
+ let first_key =
+ st.units.iter().position(|u| u.key).ok_or_else(|| CodecError::Decode("no random-access picture in the video stream".into()))?;
+ let sel: Vec<&Unit> = st.units[first_key..].iter().collect();
+ let keys = display_keys(&sel, kind == VKind::Mpeg2);
+ let (pts, order) = presentation(&keys);
+ // timeline origin: the PTS of the first presented picture
+ origin = order.first().and_then(|&i| sel[i].pts).or_else(|| sel.iter().filter_map(|u| u.pts).min());
+ let rate_from_pts = {
+ let shown: Vec<i64> = order.iter().filter_map(|&i| sel[i].pts).collect();
+ (shown.len() >= 2 && shown.len() == order.len())
+ .then(|| (shown.len() - 1) as f64 * 90_000.0 / (shown[shown.len() - 1] - shown[0]).max(1) as f64)
+ };
+ let track = VideoTrack {
+ kind,
+ stream: vi,
+ units: (first_key..st.units.len()).collect(),
+ keys: sel.iter().map(|u| u.key).collect(),
+ pts,
+ order,
+ header: Vec::new(),
+ };
+ src.file = Some(file);
+ src.video = Some(track);
+ src.describe_video(rate_from_pts)?;
+ let file = src.file.take().expect("file");
+ src.setup_audio(file, astream, origin);
+ }
+ None => {
+ src.unsupported_video = Some(format!("{} video in {} (FilmCraft has no decoder for it)", st.codec.name(), file.format.name()));
+ src.info.video = Some(VideoStreamInfo {
+ width: 0,
+ height: 0,
+ frame_rate: FrameRate::FPS_25,
+ par: (1, 1),
+ codec: format!("{} (unsupported)", st.codec.name()),
+ pixel_format: String::new(),
+ color: filmcraft_color::ColorInfo::REC709,
+ has_alpha: false,
+ bitrate: None,
+ });
+ src.setup_audio(file, astream, None);
+ }
+ }
+ } else {
+ src.info.kind = MediaKind::AudioOnly;
+ src.setup_audio(file, astream, None);
+ }
+ Ok(src)
+ }
+
+ /// A raw MPEG-1/2 video elementary stream (no timestamps: GOP / temporal reference order).
+ fn open_es(name: &str, bytes: crate::Src) -> crate::Result<Self> {
+ let all: Arc<[u8]> = filmcraft_media::reader::read_range(&*bytes.0, 0, usize::try_from(bytes.0.len()).unwrap_or(usize::MAX))
+ .map_err(|e| CodecError::Container(e.to_string()))?
+ .into();
+ let aus = filmcraft_mpeg2v::access_units(&all);
+ let infos: Vec<filmcraft_mpeg2v::AccessUnitInfo> = aus.iter().map(|r| filmcraft_mpeg2v::scan_access_unit(&all[r.clone()])).collect();
+ let first_key = infos.iter().position(|a| a.is_intra()).ok_or_else(|| CodecError::Decode("no I picture in the stream".into()))?;
+ // fake units carrying the picture info for display ordering
+ let mut keys = Vec::new();
+ let mut base = 0i64;
+ for (k, a) in infos[first_key..].iter().enumerate() {
+ if a.gop.is_some() || k == 0 {
+ base = k as i64;
+ }
+ keys.push((base + a.pictures.first().map_or(0, |p| p.0.temporal_reference as i64)) * 4);
+ }
+ let (pts, order) = presentation(&keys);
+ let track = VideoTrack {
+ kind: VKind::Mpeg2,
+ stream: 0,
+ units: (first_key..aus.len()).collect(),
+ keys: infos[first_key..].iter().map(|a| a.is_intra()).collect(),
+ pts,
+ order,
+ header: Vec::new(),
+ };
+ let mut src = MpegSource {
+ info: MediaInfo {
+ name: name.to_string(),
+ kind: MediaKind::Movie,
+ duration: Tick::ZERO,
+ video: None,
+ audio: None,
+ container: "MPEG video elementary stream".into(),
+ start_timecode: None,
+ file_size: Some(bytes.0.len()),
+ },
+ bytes,
+ file: None,
+ es: Some((all, aus)),
+ video: Some(track),
+ gop: GopCache::new(None),
+ audio: None,
+ unsupported_video: None,
+ unsupported_audio: None,
+ };
+ src.describe_video(None)?;
+ // the first GOP's time code (non-drop-frame count at the nominal rate)
+ if let Some(tc) = infos[first_key].gop {
+ let fps = src.info.frame_rate().as_f64().round().max(1.0) as i64;
+ src.info.start_timecode = Some(((tc.hours as i64 * 60 + tc.minutes as i64) * 60 + tc.seconds as i64) * fps + tc.pictures as i64);
+ }
+ Ok(src)
+ }
+
+ /// The demuxed file (streams and their access-unit tables); `None` for elementary streams.
+ pub fn file(&self) -> Option<&File> {
+ self.file.as_ref()
+ }
+
+ /// Timeline position (samples at the audio stream's rate) of the first audio frame, and the
+ /// number of samples in the audio stream.
+ pub fn audio_extent(&self) -> Option<(i64, i64)> {
+ let a = self.audio.as_ref()?;
+ let first = *a.starts.first()?;
+ let end = a.starts.last()? + *a.lens.last()? as i64;
+ Some((first, end - first))
+ }
+
+ /// The demuxed stream indices of the presented video and audio.
+ pub fn stream_indices(&self) -> (Option<usize>, Option<usize>) {
+ (self.video.as_ref().filter(|_| self.es.is_none()).map(|v| v.stream), self.audio.as_ref().map(|a| a.stream))
+ }
+
+ /// Presentation timestamps (90 kHz) of the presented video frames in display order. Frames
+ /// whose PES packet carried none are interpolated at the frame duration from the nearest
+ /// frame with one (`None` only when no frame has a timestamp, and for elementary streams).
+ pub fn video_pts(&self) -> Vec<Option<i64>> {
+ let (Some(v), Some(f)) = (&self.video, &self.file) else { return Vec::new() };
+ let units = &f.streams[v.stream].units;
+ let raw: Vec<Option<i64>> = v.order.iter().map(|&i| units[v.units[i]].pts).collect();
+ let rate = self.info.frame_rate();
+ let dur = |k: i64| (k as i128 * 90_000 * rate.den as i128 / rate.num.max(1) as i128) as i64;
+ let known: Vec<usize> = (0..raw.len()).filter(|&i| raw[i].is_some()).collect();
+ (0..raw.len())
+ .map(|i| {
+ raw[i].or_else(|| {
+ let j = known.iter().rev().find(|&&j| j < i).or_else(|| known.iter().find(|&&j| j > i))?;
+ Some(raw[*j]? + dur(i as i64 - *j as i64))
+ })
+ })
+ .collect()
+ }
+
+ fn read_unit(&self, v: &VideoTrack, i: usize) -> crate::Result<Vec<u8>> {
+ let u = v.units[i];
+ if let Some((data, aus)) = &self.es {
+ return Ok(data[aus[u].clone()].to_vec());
+ }
+ let file = self.file.as_ref().expect("file");
+ file.read_unit(&self.bytes, v.stream, u).map_err(|e| CodecError::Container(e.to_string()))
+ }
+
+ /// Fill in the video stream info from the first picture.
+ fn describe_video(&mut self, rate_from_pts: Option<f64>) -> crate::Result<()> {
+ let mut seq_header = None;
+ let v = self.video.as_ref().expect("video");
+ let first = self.read_unit(v, 0)?;
+ let n = v.order.len();
+ let (width, height, par, codec, pixel_format, mut color);
+ let rate;
+ color = filmcraft_color::ColorInfo::REC709;
+ match v.kind {
+ VKind::Mpeg2 => {
+ let info = filmcraft_mpeg2v::probe(&first).ok_or_else(|| CodecError::Decode("no MPEG video sequence header at the first I picture".into()))?;
+ let header = crate::video::mpeg2_sequence_header(&first).unwrap_or_default();
+ // field order from the first frames' picture coding extensions
+ let mut d = filmcraft_mpeg2v::Decoder::new();
+ let mut fo = None;
+ for i in 0..v.units.len().min(4) {
+ if let Ok(pics) = d.decode(&self.read_unit(v, i)?, i as i64)
+ && let Some(p) = pics.first()
+ {
+ fo = Some(p.field_order());
+ color = crate::video::mpeg2_to_video_frame(p.clone()).color;
+ break;
+ }
+ }
+ let fo = fo.unwrap_or_else(|| d.flush().first().and_then(|p| p.field_order()));
+ width = info.width;
+ height = info.height;
+ par = info.sar;
+ codec = info.codec_name();
+ pixel_format = crate::video::mpeg2_pixel_format(&info, fo);
+ rate = info.frame_rate.map(|(n, d)| FrameRate::new(n as i64, d as i64));
+ seq_header = Some(header);
+ }
+ VKind::H264 | VKind::Hevc => {
+ // decode up to the first frame for size, aspect and colour
+ let mut dec: Box<dyn VideoDecoder> = if v.kind == VKind::H264 { Box::new(H264Decoder::annexb()) } else { Box::new(HevcDecoder::annexb()) };
+ let mut frame = None;
+ for i in 0..v.units.len().min(32) {
+ if let Some(f) = dec.decode(&self.read_unit(v, i)?, i as i64)?.into_iter().next() {
+ frame = Some(f.frame);
+ break;
+ }
+ }
+ let frame = frame.or_else(|| dec.flush().into_iter().next().map(|f| f.frame)).ok_or_else(|| CodecError::Decode("no picture decoded".into()))?;
+ width = frame.width;
+ height = frame.height;
+ par = frame.par;
+ color = frame.color;
+ codec = if v.kind == VKind::H264 { "H.264".into() } else { "HEVC".into() };
+ rate = None;
+ pixel_format = match &frame.data {
+ filmcraft_frame::PixelData::Yuv8 { chroma, .. } => format!("YUV {} 8-bit", chroma_name(*chroma)),
+ filmcraft_frame::PixelData::Yuv16 { chroma, bits, .. } => format!("YUV {} {bits}-bit", chroma_name(*chroma)),
+ _ => String::new(),
+ };
+ }
+ }
+ // the coded rate unless the timestamps say otherwise (3:2 pulldown, field-rate coding)
+ let rate = match (rate, rate_from_pts) {
+ (Some(r), Some(p)) if (r.as_f64() - p).abs() / p > 0.01 => FrameRate::from_f64(p),
+ (Some(r), _) => r,
+ (None, Some(p)) => FrameRate::from_f64(p),
+ (None, None) => FrameRate::FPS_25,
+ };
+ let duration = rate.tick_of(n as i64);
+ let total_bytes: u64 = match (&self.es, &self.file) {
+ (Some((_, aus)), _) => v.units.iter().map(|&u| aus[u].len() as u64).sum(),
+ (None, Some(f)) => v.units.iter().map(|&u| f.streams[v.stream].units[u].size as u64).sum(),
+ _ => 0,
+ };
+ let secs = duration.seconds();
+ if let Some(h) = seq_header {
+ self.video.as_mut().expect("video").header = h;
+ }
+ self.info.duration = duration;
+ self.info.video = Some(VideoStreamInfo {
+ width,
+ height,
+ frame_rate: rate,
+ par,
+ codec,
+ pixel_format,
+ color,
+ has_alpha: false,
+ bitrate: (secs > 0.0).then(|| (total_bytes as f64 * 8.0 / secs) as u64),
+ });
+ Ok(())
+ }
+
+ /// Choose and index the audio stream; `origin`: PTS of the first video frame.
+ fn setup_audio(&mut self, file: File, astream: Option<usize>, origin: Option<i64>) {
+ let track = astream.and_then(|ai| self.audio_track(&file, ai, origin));
+ self.file = Some(file);
+ self.audio = track;
+ }
+
+ /// Mark the audio stream as not decodable (it still shows in the media info).
+ fn audio_unsupported(&mut self, codec_name: &str, why: String) -> Option<AudioTrack> {
+ self.unsupported_audio = Some(why);
+ self.info.audio = Some(AudioStreamInfo { sample_rate: 48_000, channels: 2, codec: format!("{codec_name} (unsupported)"), bits_per_sample: None });
+ None
+ }
+
+ fn audio_track(&mut self, file: &File, ai: usize, origin: Option<i64>) -> Option<AudioTrack> {
+ let st = &file.streams[ai];
+ let codec_name = st.codec.name();
+ if !audio_supported(&st.codec) || st.units.is_empty() {
+ let why = format!("{codec_name} audio in {} (FilmCraft has no decoder for it)", file.format.name());
+ return self.audio_unsupported(&codec_name, why);
+ }
+ let first = match file.read_unit(&self.bytes, ai, 0) {
+ Ok(b) => b,
+ Err(e) => {
+ return self.audio_unsupported(&codec_name, format!("{codec_name}: {e}"));
+ }
+ };
+ let mut latm = None;
+ let (codec, rate, channels, per_frame, bits) = match &st.codec {
+ Codec::MpegAudio | Codec::AacAdts | Codec::Ac3 => {
+ let Some(fi) = filmcraft_mpegts::frame_info(&st.codec, &first) else {
+ return self.audio_unsupported(&codec_name, format!("{codec_name}: bad frame header"));
+ };
+ let c = match st.codec {
+ Codec::MpegAudio => ACodec::Mpa(fi.variant),
+ Codec::AacAdts => ACodec::Adts,
+ _ => ACodec::Ac3,
+ };
+ (c, fi.sample_rate, fi.channels as usize, Some(fi.samples), None)
+ }
+ Codec::AacLatm => match crate::audio::latm_config(&first) {
+ Some(cfg) => {
+ latm = Some(cfg.clone());
+ (ACodec::Latm, cfg.sample_rate, cfg.channels as usize, Some(1024), None)
+ }
+ None => {
+ return self.audio_unsupported(&codec_name, "AAC (LATM): unsupported StreamMuxConfig (only AAC-LC is decoded)".into());
+ }
+ },
+ Codec::LpcmBluray => match crate::audio::bluray_lpcm_header(&first) {
+ Some(h) => (ACodec::LpcmBluray, h.sample_rate, h.channels, None, Some(h.bits)),
+ None => {
+ return self.audio_unsupported(&codec_name, "LPCM: bad header".into());
+ }
+ },
+ Codec::LpcmDvd => match st.lpcm {
+ Some(f) => (ACodec::LpcmDvd(f), f.sample_rate, f.channels as usize, None, Some(f.bits)),
+ None => {
+ return self.audio_unsupported(&codec_name, "DVD LPCM: no format header".into());
+ }
+ },
+ _ => unreachable!("audio_supported"),
+ };
+ if codec_is_ac3_unsupported(codec) {
+ return self.audio_unsupported(&codec_name, format!("{codec_name} audio (FilmCraft has no AC-3 decoder yet)"));
+ }
+ // DVD LPCM packets split sample groups: units own the groups that start in them
+ let mut byte_starts = Vec::new();
+ if let ACodec::LpcmDvd(_) = codec {
+ let mut acc = 0u64;
+ for u in &st.units {
+ byte_starts.push(acc);
+ acc += u.size as u64;
+ }
+ byte_starts.push(acc);
+ }
+ let group = |f: filmcraft_mpegts::LpcmFormat| crate::audio::dvd_lpcm_group_bytes(f.channels as usize, f.bits) as u64;
+ // samples per unit
+ let lens: Vec<u32> = st
+ .units
+ .iter()
+ .enumerate()
+ .map(|(k, u)| match (codec, per_frame) {
+ (_, Some(n)) => n,
+ (ACodec::LpcmBluray, _) => {
+ let coded = (channels + 1) & !1;
+ let bps = if bits == Some(16) { 2 } else { 3 };
+ (u.size.saturating_sub(4) as usize / (coded * bps)) as u32
+ }
+ (ACodec::LpcmDvd(f), _) => {
+ let g = group(f);
+ // groups whose first byte is in this unit (and that end before the stream does)
+ let total = byte_starts[st.units.len()] / g;
+ let (g0, g1) = (byte_starts[k].div_ceil(g).min(total), byte_starts[k + 1].div_ceil(g).min(total));
+ ((g1 - g0) * 2) as u32
+ }
+ _ => 0,
+ })
+ .collect();
+ // place units: contiguous, re-anchored at timestamp gaps of more than half a frame (PCM
+ // byte streams are always contiguous)
+ let origin = origin.or_else(|| st.units.iter().find_map(|u| u.pts)).unwrap_or(0);
+ let to_samples = |pts: i64| ((pts - origin) as i128 * rate as i128).div_euclid(90_000) as i64;
+ let contiguous = matches!(codec, ACodec::LpcmDvd(_));
+ let mut starts = Vec::with_capacity(lens.len());
+ let mut next: Option<i64> = None;
+ for (u, &n) in st.units.iter().zip(&lens) {
+ let s = match (u.pts.map(to_samples), next) {
+ (_, Some(nx)) if contiguous => nx,
+ (Some(p), Some(nx)) if (p - nx).abs() * 2 <= n as i64 => nx,
+ (Some(p), _) => p,
+ (None, Some(nx)) => nx,
+ (None, None) => 0,
+ };
+ starts.push(s);
+ next = Some(s + n as i64);
+ }
+ let total = next.unwrap_or(0).max(0);
+ if self.info.video.is_none() || self.unsupported_video.is_some() {
+ self.info.duration = Tick::from_units(total, rate.max(1) as i64);
+ if self.info.video.is_none() {
+ self.info.kind = MediaKind::AudioOnly;
+ }
+ }
+ self.info.audio = Some(AudioStreamInfo { sample_rate: rate.max(1), channels: channels.max(1) as u32, codec: codec_name, bits_per_sample: bits });
+ Some(AudioTrack {
+ stream: ai,
+ codec,
+ rate,
+ channels: channels.max(1),
+ starts,
+ lens,
+ latm,
+ byte_starts,
+ state: Mutex::new(AudioState { dec: None, cache: HashMap::new(), order: VecDeque::new(), last: None }),
+ })
+ }
+
+ /// Decoded samples of audio unit `i` (cached; non-sequential access primes the decoder with
+ /// the previous unit).
+ fn audio_unit(&self, a: &AudioTrack, st: &mut AudioState, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {
+ if let Some(p) = st.cache.get(&i) {
+ return Ok(p.clone());
+ }
+ let file = self.file.as_ref().expect("file");
+ let read = |k: usize| file.read_unit(&self.bytes, a.stream, k).map_err(|e| CodecError::Container(e.to_string()));
+ if st.dec.is_none() {
+ st.dec = Some(AudioDecoder::new(a.codec, a.rate, a.channels, a.latm.clone())?);
+ }
+ let dec = st.dec.as_mut().expect("decoder");
+ if st.last.is_none_or(|l| l + 1 != i) {
+ dec.reset();
+ if i > 0
+ && let Ok(prev) = read(i - 1)
+ {
+ let _ = dec.decode(&prev);
+ }
+ }
+ let data = match a.codec {
+ ACodec::LpcmDvd(f) if i + 1 < a.byte_starts.len() => {
+ // the sample groups starting in this unit (the last may continue in the next)
+ let g = crate::audio::dvd_lpcm_group_bytes(f.channels as usize, f.bits) as u64;
+ let (b0, b1) = (a.byte_starts[i], a.byte_starts[i + 1]);
+ let lo = b0.div_ceil(g) * g;
+ let hi = b1.div_ceil(g) * g;
+ let mut d = read(i)?;
+ if hi > b1
+ && let Ok(next) = read(i + 1)
+ {
+ d.extend_from_slice(&next);
+ }
+ let e = ((hi - b0) as usize).min(d.len());
+ d[((lo - b0) as usize).min(e)..e].to_vec()
+ }
+ _ => read(i)?,
+ };
+ let out = match dec.decode(&data) {
+ Ok(v) => v,
+ Err(_) => vec![vec![0.0; a.lens[i] as usize]; a.channels],
+ };
+ st.last = Some(i);
+ let p = Arc::new(out);
+ st.cache.insert(i, p.clone());
+ st.order.push_back(i);
+ if st.order.len() > 2048
+ && let Some(old) = st.order.pop_front()
+ {
+ st.cache.remove(&old);
+ }
+ Ok(p)
+ }
+}
+
+fn chroma_name(c: filmcraft_frame::Chroma) -> &'static str {
+ match c {
+ filmcraft_frame::Chroma::C420 => "4:2:0",
+ filmcraft_frame::Chroma::C422 => "4:2:2",
+ filmcraft_frame::Chroma::C444 => "4:4:4",
+ }
+}
+
+fn codec_is_ac3_unsupported(c: ACodec) -> bool {
+ matches!(c, ACodec::Ac3) && !crate::audio::AC3_DECODER
+}
+
+/// The audio decoders behind the TS/PS audio codecs.
+enum AudioDecoder {
+ Packet { dec: crate::audio::PacketDecoder, codec: ACodec, latm: Option<crate::audio::LatmConfig> },
+ Pcm { codec: ACodec, channels: usize },
+}
+
+impl AudioDecoder {
+ fn new(codec: ACodec, rate: u32, channels: usize, latm: Option<crate::audio::LatmConfig>) -> crate::Result<Self> {
+ use crate::audio::PacketDecoder;
+ Ok(match codec {
+ ACodec::Mpa(layer) => AudioDecoder::Packet { dec: PacketDecoder::mpeg_audio(layer, rate)?, codec, latm: None },
+ ACodec::Adts | ACodec::Latm => AudioDecoder::Packet { dec: PacketDecoder::lazy_aac(), codec, latm },
+ ACodec::Ac3 => AudioDecoder::Packet { dec: PacketDecoder::ac3()?, codec, latm: None },
+ ACodec::LpcmBluray | ACodec::LpcmDvd(_) => AudioDecoder::Pcm { codec, channels },
+ })
+ }
+ fn reset(&mut self) {
+ if let AudioDecoder::Packet { dec, .. } = self {
+ dec.reset();
+ }
+ }
+ fn decode(&mut self, data: &[u8]) -> crate::Result<Vec<Vec<f32>>> {
+ match self {
+ AudioDecoder::Packet { dec, codec: ACodec::Adts, .. } => {
+ let (asc, payload) = crate::audio::adts_split(data).ok_or_else(|| CodecError::Decode("bad ADTS frame".into()))?;
+ dec.ensure_aac(&asc)?;
+ dec.decode(payload, 0)
+ }
+ AudioDecoder::Packet { dec, codec: ACodec::Latm, latm } => {
+ let (asc, payload) = crate::audio::latm_split(data, latm).ok_or_else(|| CodecError::Decode("bad LATM frame".into()))?;
+ dec.ensure_aac(&asc)?;
+ dec.decode(&payload, 0)
+ }
+ AudioDecoder::Packet { dec, .. } => dec.decode(data, 0),
+ AudioDecoder::Pcm { codec: ACodec::LpcmBluray, .. } => {
+ crate::audio::decode_bluray_lpcm(data).ok_or_else(|| CodecError::Decode("bad LPCM packet".into()))
+ }
+ AudioDecoder::Pcm { codec: ACodec::LpcmDvd(f), channels } => Ok(crate::audio::decode_dvd_lpcm(data, *channels, f.bits)),
+ AudioDecoder::Pcm { .. } => Err(CodecError::Unsupported("PCM format".into())),
+ }
+ }
+}
+
+/// The video samples as a [`VideoSamples`] table.
+struct MpegVideo<'a> {
+ src: &'a MpegSource,
+ v: &'a VideoTrack,
+}
+
+impl VideoSamples for MpegVideo<'_> {
+ fn count(&self) -> usize {
+ self.v.units.len()
+ }
+ fn pts(&self, i: usize) -> i64 {
+ self.v.pts[i]
+ }
+ fn sync_before(&self, i: usize) -> usize {
+ let i = i.min(self.v.keys.len().saturating_sub(1));
+ let key = (0..=i).rev().find(|&k| self.v.keys[k]).unwrap_or(0);
+ // a leading picture of an open GOP (shown before its random-access picture) needs the
+ // previous GOP's pictures as references
+ if key > 0 && self.v.pts[i] < self.v.pts[key] { self.sync_before(key - 1) } else { key }
+ }
+ fn sample_at(&self, t: i64) -> Option<usize> {
+ usize::try_from(t).ok().and_then(|t| self.v.order.get(t).copied())
+ }
+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
+ self.src.read_unit(self.v, i)
+ }
+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
+ if let Some(why) = &self.src.unsupported_video {
+ return Err(CodecError::Unsupported(why.clone()));
+ }
+ Ok(match self.v.kind {
+ VKind::Mpeg2 => Box::new(Mpeg2Decoder::new(self.v.header.clone())),
+ VKind::H264 => Box::new(H264Decoder::annexb()),
+ VKind::Hevc => Box::new(HevcDecoder::annexb()),
+ })
+ }
+}
+
+impl MediaSource for MpegSource {
+ fn info(&self) -> &MediaInfo {
+ &self.info
+ }
+
+ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {
+ if let Some(why) = &self.unsupported_video {
+ return Err(MediaError::Unsupported(why.clone()));
+ }
+ let v = self.video.as_ref().ok_or(MediaError::NoStream("video"))?;
+ if v.order.is_empty() {
+ return Err(MediaError::Decode("no pictures".into()));
+ }
+ let rate = self.info.frame_rate();
+ let f = rate.frame_at(req.time.max(Tick::ZERO)).clamp(0, v.order.len() as i64 - 1);
+ let late = filmcraft_media::cancel::catch_up().map(|m| rate.frame_at(req.time - m));
+ Ok(self.gop.frame_late(&MpegVideo { src: self, v }, f, late)?)
+ }
+
+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer, MediaError> {
+ if let Some(why) = &self.unsupported_audio {
+ return Err(MediaError::Unsupported(why.clone()));
+ }
+ let a = self.audio.as_ref().ok_or(MediaError::NoStream("audio"))?;
+ let ch = a.channels;
+ let ratio = a.rate as f64 / sample_rate as f64;
+ let exact = a.rate == sample_rate;
+ let s0 = if exact { start } else { (start as f64 * ratio).floor() as i64 };
+ let need = if exact { frames as i64 } else { (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 = a.state.lock().unwrap_or_else(|e| e.into_inner());
+ // units overlapping [s0, s0 + need)
+ let mut i = a.starts.partition_point(|&s| s <= s0).saturating_sub(1);
+ while i < a.starts.len() && a.starts[i] < s0 + need {
+ if a.starts[i] + a.lens[i] as i64 > s0 {
+ let pk = self.audio_unit(a, &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 = a.starts[i] + k as i64 - s0;
+ if pos >= 0 && (pos as usize) < dst.len() {
+ dst[pos as usize] = *v;
+ }
+ }
+ }
+ }
+ i += 1;
+ }
+ drop(st);
+ let mut out = AudioBuffer::silence(sample_rate, ch, frames);
+ if exact {
+ for (c, s) in src.into_iter().enumerate() {
+ out.channels[c][..frames.min(s.len())].copy_from_slice(&s[..frames.min(s.len())]);
+ }
+ return Ok(out);
+ }
+ let frac = s0 as f64 - start as f64 * ratio;
+ 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 x = src[c].get(i0).copied().unwrap_or(0.0);
+ let y = src[c].get(i0 + 1).copied().unwrap_or(x);
+ out.channels[c][k] = x + (y - x) * f;
+ }
+ }
+ Ok(out)
+ }
+}
+
+pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {
+ if !sniff(&bytes[..bytes.len().min(65_536)]) {
+ return None;
+ }
+ Some(MpegSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
+}
+
+/// [`filmcraft_media::ReaderOpener`] for MPEG transport / program / video elementary streams.
+pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {
+ if !sniff(head) {
+ return None;
+ }
+ Some(MpegSource::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn presentation_drops_leading_pictures_and_orders_by_key() {
+ // decode order I(2) B(0) B(1) P(5) B(3) B(4): the leading B pictures are not presented
+ let keys = [2, 0, 1, 5, 3, 4];
+ let (pts, order) = presentation(&keys);
+ assert_eq!(order, vec![0, 4, 5, 3]);
+ assert_eq!(pts, vec![0, -2, -3, 3, 1, 2]);
+ }
+}
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index be39c6adb..756944935 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -250,6 +250,10 @@ impl HevcDecoder {
let highest_tid = hvcc.get(21).map(|b| (b >> 3) & 7).filter(|&n| n > 0).map(|n| n - 1);
Ok(Self { hvcc, dec, length_size, highest_tid })
}
+ /// A decoder for Annex B byte-stream samples (start codes, in-band parameter sets: TS).
+ pub fn annexb() -> Self {
+ Self { hvcc: Vec::new(), dec: filmcraft_hevc::Decoder::new(), length_size: 0, highest_tid: None }
+ }
fn convert(p: filmcraft_hevc::Picture) -> DecodedFrame {
use filmcraft_hevc::Plane;
use std::sync::Arc;
@@ -300,7 +304,9 @@ impl VideoDecoder for HevcDecoder {
self.dec.flush().into_iter().map(Self::convert).collect()
}
fn reset(&mut self) {
- if let Ok(d) = filmcraft_hevc::Decoder::from_hvcc(&self.hvcc) {
+ if self.hvcc.is_empty() {
+ self.dec = filmcraft_hevc::Decoder::new();
+ } else if let Ok(d) = filmcraft_hevc::Decoder::from_hvcc(&self.hvcc) {
self.dec = d;
}
}
@@ -310,6 +316,12 @@ impl VideoDecoder for HevcDecoder {
fn is_disposable(&self, sample: &[u8]) -> bool {
hevc_disposable(sample, self.length_size, self.highest_tid)
}
+ fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
+ // Annex B samples carry their parameter sets: an IDR / CRA / BLA access unit is a
+ // starting point.
+ (self.length_size == 0)
+ .then(|| filmcraft_bitstream::annexb_nals(sample).iter().any(|n| n.first().is_some_and(|h| (16..=21).contains(&((h >> 1) & 0x3F)))))
+ }
}
pub fn hevc_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
@@ -681,6 +693,172 @@ pub fn dnx_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
matches!(e.codec, CodecConfig::Dnx { .. }).then(|| Ok(Box::new(DnxDecoder) as Box<dyn VideoDecoder>))
}
+/// Our MPEG-1 / MPEG-2 video decoder (Main / 4:2:2 profile, field and frame pictures).
+pub struct Mpeg2Decoder {
+ dec: filmcraft_mpeg2v::Decoder,
+ /// Sequence header (and extensions) fed after a reset, so a random-access point without its
+ /// own sequence header decodes (MKV `CodecPrivate`, or the stream's first header).
+ header: Vec<u8>,
+}
+
+impl Mpeg2Decoder {
+ pub fn new(header: Vec<u8>) -> Self {
+ let mut d = Self { dec: filmcraft_mpeg2v::Decoder::new(), header };
+ d.prime();
+ d
+ }
+ fn prime(&mut self) {
+ if !self.header.is_empty() {
+ let _ = self.dec.decode(&self.header, 0);
+ }
+ }
+}
+
+/// The sequence header with its extensions at the start of an MPEG video sample (up to the first
+/// GOP or picture start code).
+pub fn mpeg2_sequence_header(sample: &[u8]) -> Option<Vec<u8>> {
+ let codes = filmcraft_mpeg2v::start_codes(sample);
+ let (start, _) = *codes.iter().find(|c| c.1 == 0xB3)?;
+ let end = codes.iter().find(|c| c.0 > start && matches!(c.1, 0x00 | 0xB8 | 0x01..=0xAF)).map_or(sample.len(), |c| c.0);
+ Some(sample[start..end].to_vec())
+}
+
+/// Convert a decoded MPEG-1/2 picture. Colour comes from the sequence display extension
+/// (defaults: BT.601 for SD, BT.709 for HD); the pixel aspect from the aspect ratio code.
+pub fn mpeg2_to_video_frame(p: filmcraft_mpeg2v::Picture) -> VideoFrame {
+ use std::sync::Arc;
+ let info = &p.info;
+ let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(p.width, p.height), ..filmcraft_color::ColorInfo::REC709 };
+ if info.width <= 1024 && info.height <= 576 {
+ color.primaries = if info.height == 576 || info.height == 608 { filmcraft_color::Primaries::Bt601_625 } else { filmcraft_color::Primaries::Bt601_525 };
+ }
+ if let Some((prim, transfer, matrix)) = info.colour {
+ if let Some(m) = filmcraft_color::Matrix::from_code(matrix) {
+ color.matrix = m;
+ }
+ if let Some(t) = filmcraft_color::Transfer::from_code(transfer) {
+ color.transfer = t;
+ }
+ if let Some(pr) = primaries_from_code(prim) {
+ color.primaries = pr;
+ }
+ }
+ let chroma = match p.chroma {
+ filmcraft_mpeg2v::ChromaFormat::Yuv420 => filmcraft_frame::Chroma::C420,
+ filmcraft_mpeg2v::ChromaFormat::Yuv422 => filmcraft_frame::Chroma::C422,
+ filmcraft_mpeg2v::ChromaFormat::Yuv444 => filmcraft_frame::Chroma::C444,
+ };
+ let par = info.sar;
+ VideoFrame {
+ width: p.width,
+ height: p.height,
+ data: filmcraft_frame::PixelData::Yuv8 { planes: [Arc::new(p.y), Arc::new(p.cb), Arc::new(p.cr)], chroma, alpha: None },
+ color,
+ par: if par.0 > 0 && par.1 > 0 { par } else { (1, 1) },
+ pts: filmcraft_time::Tick::ZERO,
+ }
+}
+
+/// "YUV 4:2:2 8-bit, interlaced (upper field first)" for the media info.
+pub fn mpeg2_pixel_format(info: &filmcraft_mpeg2v::SequenceInfo, field_order: Option<filmcraft_mpeg2v::FieldOrder>) -> String {
+ let sub = match info.chroma {
+ filmcraft_mpeg2v::ChromaFormat::Yuv420 => "4:2:0",
+ filmcraft_mpeg2v::ChromaFormat::Yuv422 => "4:2:2",
+ filmcraft_mpeg2v::ChromaFormat::Yuv444 => "4:4:4",
+ };
+ let scan = match field_order {
+ Some(filmcraft_mpeg2v::FieldOrder::TopFirst) => ", interlaced (upper field first)",
+ Some(filmcraft_mpeg2v::FieldOrder::BottomFirst) => ", interlaced (lower field first)",
+ None => ", progressive",
+ };
+ format!("YUV {sub} 8-bit{scan}")
+}
+
+impl VideoDecoder for Mpeg2Decoder {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
+ let pics = self.dec.decode(sample, pts).map_err(|e| CodecError::Decode(e.to_string()))?;
+ Ok(pics.into_iter().map(|p| DecodedFrame { pts: p.pts, frame: mpeg2_to_video_frame(p) }).collect())
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ self.dec.flush().into_iter().map(|p| DecodedFrame { pts: p.pts, frame: mpeg2_to_video_frame(p) }).collect()
+ }
+ fn reset(&mut self) {
+ self.dec.reset();
+ self.prime();
+ }
+ fn name(&self) -> &str {
+ "FilmCraft MPEG-2"
+ }
+ fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
+ Some(filmcraft_mpeg2v::scan_access_unit(sample).is_intra())
+ }
+ fn is_disposable(&self, sample: &[u8]) -> bool {
+ filmcraft_mpeg2v::scan_access_unit(sample).is_disposable()
+ }
+}
+
+/// QuickTime / MP4 sample entries carrying MPEG-1/2 video: XDCAM (EX/HD/HD422), IMX, HDV,
+/// generic `mp2v`/`mpg2`, and `mp4v` whose `esds` object type is MPEG-1/2 video (0x60-0x65, 0x6A).
+fn is_mpeg2_entry(fourcc: &[u8; 4], raw: &[u8]) -> bool {
+ match fourcc {
+ b"mp2v" | b"mpg2" | b"m2v1" | b"mpg1" | b"m1v " | b"m1v1" | b"mx3n" | b"mx4n" | b"mx5n" | b"mx3p" | b"mx4p" | b"mx5p" | b"xdhd" | b"xdh2" => true,
+ [b'x', b'd', b'v' | b'5', _] | [b'h', b'd', b'v', _] => true,
+ b"mp4v" => esds_object_type(raw).is_some_and(|t| (0x60..=0x65).contains(&t) || t == 0x6A),
+ _ => false,
+ }
+}
+
+/// objectTypeIndication of the DecoderConfigDescriptor inside an `esds` box in `raw`.
+fn esds_object_type(raw: &[u8]) -> Option<u8> {
+ let at = raw.windows(4).position(|w| w == b"esds")? + 8;
+ let mut p = at;
+ let size = |p: &mut usize| -> Option<usize> {
+ let mut n = 0usize;
+ for _ in 0..4 {
+ let b = *raw.get(*p)?;
+ *p += 1;
+ n = (n << 7) | (b & 0x7F) as usize;
+ if b & 0x80 == 0 {
+ break;
+ }
+ }
+ Some(n)
+ };
+ if *raw.get(p)? != 0x03 {
+ return None;
+ }
+ p += 1;
+ size(&mut p)?;
+ let flags = *raw.get(p + 2)?;
+ p += 3;
+ if flags & 0x80 != 0 {
+ p += 2;
+ }
+ if flags & 0x40 != 0 {
+ p += 1 + *raw.get(p)? as usize;
+ }
+ if flags & 0x20 != 0 {
+ p += 2;
+ }
+ if *raw.get(p)? != 0x04 {
+ return None;
+ }
+ p += 1;
+ size(&mut p)?;
+ raw.get(p).copied()
+}
+
+pub fn mpeg2_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
+ match &e.codec {
+ CodecConfig::Unknown { fourcc, raw } if is_mpeg2_entry(&fourcc.0, raw) => {
+ // MKV puts the sequence header in CodecPrivate (passed as `raw` for `mp2v`)
+ let header = if fourcc.0 == *b"mp2v" { mpeg2_sequence_header(raw).unwrap_or_default() } else { Vec::new() };
+ Some(Ok(Box::new(Mpeg2Decoder::new(header)) as Box<dyn VideoDecoder>))
+ }
+ _ => None,
+ }
+}
+
#[cfg(test)]
mod disposable_tests {
use super::{h264_disposable, hevc_disposable};
diff --git a/crates/codecs/tests/mpeg_oracle.rs b/crates/codecs/tests/mpeg_oracle.rs
new file mode 100644
index 000000000..0ed5498e5
--- /dev/null
+++ b/crates/codecs/tests/mpeg_oracle.rs
@@ -0,0 +1,463 @@
+//! MPEG transport / program streams against ffmpeg: ffmpeg writes the files and decodes them as
+//! the oracle. Video: frame count and display order exact, PTS exact against ffprobe, H.264 /
+//! HEVC bit-exact, MPEG-2 within the IDCT tolerance of `filmcraft-mpeg2v` (±4, PSNR ≥ 58 dB);
+//! random seeks give the frames of the sequential decode. Audio: LPCM sample-exact, MPEG audio
+//! and AAC within a float-decoder tolerance, starting at the same sample.
+
+mod common;
+
+use std::path::{Path, PathBuf};
+
+use common::*;
+use filmcraft_codecs::MpegSource;
+use filmcraft_media::{FrameRequest, MediaError, MediaSource};
+
+/// Stereo test audio with different content per channel (tones and a chirp).
+const NOISE: &[&str] =
+ &["-f", "lavfi", "-i", "aevalsrc=exprs=0.3*sin(2*PI*441*t)+0.1*sin(2*PI*3100*t)|0.25*sin(2*PI*660*t)+0.1*sin(2*PI*(500+4000*t)*t):s=48000"];
+
+fn spec(name: &str) -> Vec<String> {
+ let cat = |p: &[&[&str]]| p.concat().into_iter().map(String::from).collect::<Vec<_>>();
+ match name {
+ // broadcast-style SD: interlaced MPEG-2 + MPEG-1 layer II
+ "ts_mpeg2_mp2.ts" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=720x576:rate=50,tinterlace=mode=interleave_top,setfield=tff"],
+ NOISE,
+ &["-t", "1.2", "-c:v", "mpeg2video", "-flags", "+ilme+ildct", "-bf", "2", "-g", "12", "-b:v", "6M", "-c:a", "mp2", "-b:a", "192k", "-f", "mpegts"],
+ ]),
+ "ts_h264_aac.ts" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25"],
+ NOISE,
+ &["-t", "1.2", "-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac", "-aac_pns", "0", "-b:a", "128k", "-f", "mpegts"],
+ ]),
+ // AVCHD-style BDAV (192-byte packets): H.264 + Blu-ray LPCM
+ "m2ts_h264_lpcm.m2ts" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30000/1001"],
+ NOISE,
+ &[
+ "-t",
+ "1",
+ "-c:v",
+ "libx264",
+ "-bf",
+ "2",
+ "-g",
+ "15",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "pcm_bluray",
+ "-ac",
+ "2",
+ "-f",
+ "mpegts",
+ "-mpegts_m2ts_mode",
+ "1",
+ ],
+ ]),
+ // AVCHD audio is usually AC-3
+ "m2ts_h264_ac3.mts" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30000/1001"],
+ NOISE,
+ &[
+ "-t",
+ "1",
+ "-c:v",
+ "libx264",
+ "-bf",
+ "2",
+ "-g",
+ "15",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "ac3",
+ "-b:a",
+ "192k",
+ "-ac",
+ "2",
+ "-f",
+ "mpegts",
+ "-mpegts_m2ts_mode",
+ "1",
+ ],
+ ]),
+ "ts_hevc_latm.ts" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25"],
+ NOISE,
+ &[
+ "-t",
+ "1",
+ "-c:v",
+ "libx265",
+ "-x265-params",
+ "log-level=error:bframes=2:keyint=12",
+ "-c:a",
+ "aac",
+ "-aac_pns",
+ "0",
+ "-b:a",
+ "96k",
+ "-f",
+ "mpegts",
+ "-mpegts_flags",
+ "latm",
+ ],
+ ]),
+ // DVD-style program streams
+ "ps_mpeg2_mp2.vob" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=720x480:rate=30000/1001"],
+ NOISE,
+ &["-t", "1.2", "-c:v", "mpeg2video", "-bf", "2", "-g", "15", "-b:v", "5M", "-c:a", "mp2", "-b:a", "224k", "-f", "vob"],
+ ]),
+ "ps_mpeg2_lpcm.vob" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=720x576:rate=25"],
+ NOISE,
+ &["-t", "1", "-c:v", "mpeg2video", "-bf", "2", "-c:a", "pcm_dvd", "-ac", "2", "-f", "vob"],
+ ]),
+ "ps_mpeg2_lpcm16.vob" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25"],
+ NOISE,
+ &["-t", "0.6", "-c:v", "mpeg2video", "-c:a", "pcm_dvd", "-sample_fmt", "s16", "-ac", "2", "-f", "vob"],
+ ]),
+ "ps_mpeg2_ac3.vob" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=720x576:rate=25"],
+ NOISE,
+ &["-t", "1", "-c:v", "mpeg2video", "-bf", "2", "-c:a", "ac3", "-b:a", "192k", "-f", "vob"],
+ ]),
+ // ISO/IEC 11172-1 system stream
+ "mpeg1_system.mpg" => cat(&[
+ &["-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25"],
+ NOISE,
+ &["-t", "1.2", "-c:v", "mpeg1video", "-bf", "2", "-b:v", "1500k", "-c:a", "mp2", "-b:a", "128k", "-f", "mpeg"],
+ ]),
+ "es_mpeg2.m2v" => {
+ cat(&[&["-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25"], &["-t", "1", "-c:v", "mpeg2video", "-bf", "2", "-g", "9", "-f", "mpeg2video"]])
+ }
+ other => panic!("unknown fixture {other}"),
+ }
+}
+
+pub const ALL: &[&str] = &[
+ "ts_mpeg2_mp2.ts",
+ "ts_h264_aac.ts",
+ "m2ts_h264_lpcm.m2ts",
+ "m2ts_h264_ac3.mts",
+ "ts_hevc_latm.ts",
+ "ps_mpeg2_mp2.vob",
+ "ps_mpeg2_lpcm.vob",
+ "ps_mpeg2_lpcm16.vob",
+ "ps_mpeg2_ac3.vob",
+ "mpeg1_system.mpg",
+ "es_mpeg2.m2v",
+];
+
+fn make(ff: &Path, name: &str) -> PathBuf {
+ let args = spec(name);
+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();
+ fixture(ff, name, &refs).unwrap_or_else(|| panic!("could not generate {name}"))
+}
+
+fn open(p: &Path) -> MpegSource {
+ MpegSource::open(p.file_name().unwrap().to_str().unwrap(), bytes(p)).unwrap()
+}
+
+/// ffprobe's video frames in display order: pts (90 kHz).
+fn ffprobe_frame_pts(file: &Path) -> Option<Vec<i64>> {
+ let fp = filmcraft_testkit::ffprobe()?;
+ let o = std::process::Command::new(fp)
+ .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=pts", "-of", "csv=p=0"])
+ .arg(file)
+ .output()
+ .ok()?;
+ Some(String::from_utf8_lossy(&o.stdout).lines().filter_map(|l| l.trim().trim_end_matches(',').parse().ok()).collect())
+}
+
+/// Decode every frame in order and `seeks` random frames; compare with ffmpeg within `tol`.
+/// Returns (max difference, PSNR).
+fn check_video(ff: &Path, file: &Path, tol: u16, seeks: usize) -> (u16, f64) {
+ let src = open(file);
+ let v = src.info().video.clone().unwrap();
+ let (w, h) = (v.width as usize, v.height as usize);
+ let first = src.video_frame(FrameRequest::full(filmcraft_time::Tick::ZERO)).unwrap();
+ let (cw, ch, pix) = match &first.data {
+ filmcraft_frame::PixelData::Yuv8 { chroma: filmcraft_frame::Chroma::C422, .. } => (w / 2, h, "yuv422p"),
+ _ => (w.div_ceil(2), h.div_ceil(2), "yuv420p"),
+ };
+ let raw = ffmpeg_frames(ff, file, pix);
+ let fsize = w * h + 2 * cw * ch;
+ let n = raw.len() / fsize;
+ let rate = v.frame_rate;
+ assert_eq!(src.info().duration, rate.tick_of(n as i64), "{}: duration = ffmpeg's {n} frames", file.display());
+ let frame = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, cw, ch, 1);
+ let (mut worst, mut sse, mut cnt) = (0u16, 0f64, 0u64);
+ let mut ours = Vec::new();
+ for i in 0..n {
+ let f = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).unwrap();
+ let p = planes(&f);
+ let r = frame(i);
+ let d = max_diff(&p, &r);
+ for (a, b) in p.iter().zip(&r) {
+ for (x, y) in a.iter().zip(b) {
+ sse += (*x as f64 - *y as f64).powi(2);
+ cnt += 1;
+ }
+ }
+ worst = worst.max(d);
+ assert!(d <= tol, "{}: frame {i} differs by {d}", file.display());
+ ours.push(p);
+ }
+ // random access on a fresh source gives the same frames
+ let fresh = open(file);
+ let mut rng = Rng(0x5EED);
+ for _ in 0..seeks {
+ let i = rng.below(n as u64) as usize;
+ let f = fresh.video_frame(FrameRequest::full(rate.tick_of(i as i64))).unwrap();
+ assert!(planes(&f) == ours[i], "{}: seek to frame {i} differs from the sequential decode", file.display());
+ }
+ // presentation timestamps in display order = ffprobe's
+ if let Some(fp) = ffprobe_frame_pts(file) {
+ let pts = src.video_pts();
+ let missing: Vec<usize> = (0..pts.len()).filter(|&i| pts[i].is_none()).collect();
+ assert!(missing.is_empty(), "{}: frames without PTS: {missing:?} (ffprobe {:?})", file.display(), &fp[..fp.len().min(12)]);
+ let pts: Vec<i64> = pts.into_iter().flatten().collect();
+ assert_eq!(pts, fp, "{}: frame PTS", file.display());
+ }
+ let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (255f64 * 255.0 * cnt as f64 / sse).log10() };
+ (worst, psnr)
+}
+
+/// Our decoded audio from the first audio frame against ffmpeg's decode. Returns the max error.
+fn check_audio(ff: &Path, file: &Path, tol: f32) -> f32 {
+ let src = open(file);
+ let a = src.info().audio.clone().unwrap();
+ let (start, len) = src.audio_extent().unwrap();
+ let want = ffmpeg_audio_f32(ff, file, &[]);
+ let ch = a.channels as usize;
+ assert_eq!(want.len() % ch, 0);
+ let n = want.len() / ch;
+ assert_eq!(len as usize, n, "{}: audio samples = ffmpeg's", file.display());
+ let buf = src.audio(start, n, a.sample_rate).unwrap();
+ let mut worst = 0f32;
+ for i in 0..n {
+ for c in 0..ch {
+ worst = worst.max((buf.channels[c][i] - want[i * ch + c]).abs());
+ }
+ }
+ if worst > tol {
+ // where it starts, and the lag that best aligns the two (diagnostics)
+ let first_bad = (0..n * ch).find(|&k| (buf.channels[k % ch][k / ch] - want[k]).abs() > tol).map(|k| k / ch);
+ let best = (-4000i64..=4000)
+ .map(|lag| {
+ let e: f64 = (4000..n.min(20_000))
+ .map(|i| {
+ let j = i as i64 + lag;
+ if j < 0 || j as usize >= n { 0.0 } else { (buf.channels[0][i] as f64 - want[j as usize * ch] as f64).powi(2) }
+ })
+ .sum();
+ (e, lag)
+ })
+ .fold((f64::MAX, 0), |a, b| if b.0 < a.0 { b } else { a });
+ let per: Vec<String> = (0..n.min(16 * 1152))
+ .step_by(1152)
+ .map(|s| {
+ let e = (s..(s + 1152).min(n)).map(|i| (buf.channels[0][i] - want[i * ch]).abs()).fold(0f32, f32::max);
+ let ours = (s..(s + 1152).min(n)).map(|i| buf.channels[0][i].abs()).fold(0f32, f32::max);
+ format!("{e:.3}/{ours:.3}")
+ })
+ .collect();
+ panic!(
+ "{}: audio max error {worst}, first at sample {first_bad:?}, best lag {} (residual {:.3e}); per 1152 (err/peak): {per:?}",
+ file.display(),
+ best.1,
+ best.0
+ );
+ }
+ // a window read on a fresh source (random access) gives the same samples
+ let fresh = open(file);
+ let at = start + n as i64 / 3;
+ let win = fresh.audio(at, 4800.min(n / 2), a.sample_rate).unwrap();
+ for c in 0..ch {
+ for (k, v) in win.channels[c].iter().enumerate() {
+ let i = (at - start) as usize + k;
+ assert!((v - buf.channels[c][i]).abs() <= 1e-6, "{}: random-access audio differs at {i}", file.display());
+ }
+ }
+ worst
+}
+
+#[test]
+fn transport_stream_mpeg2_and_mp2() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "ts_mpeg2_mp2.ts");
+ let src = open(&f);
+ let v = src.info().video.clone().unwrap();
+ assert_eq!(src.info().container, "MPEG-2 TS");
+ assert!(v.codec.starts_with("MPEG-2 Video (Main@"), "{}", v.codec);
+ assert_eq!(v.pixel_format, "YUV 4:2:0 8-bit, interlaced (upper field first)");
+ assert_eq!((v.width, v.height, v.par), (720, 576, (1, 1)));
+ let (worst, psnr) = check_video(&ff, &f, 4, 12);
+ assert!(psnr >= 58.0, "PSNR {psnr}");
+ println!("ts_mpeg2_mp2: video max diff {worst}, PSNR {psnr:.2} dB");
+ let a = src.info().audio.clone().unwrap();
+ assert_eq!((a.codec.as_str(), a.sample_rate, a.channels), ("MPEG Audio", 48_000, 2));
+ let e = check_audio(&ff, &f, 2e-4);
+ println!("ts_mpeg2_mp2: MP2 audio max error {e:.2e}");
+}
+
+#[test]
+fn transport_stream_h264_and_aac() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "ts_h264_aac.ts");
+ let src = open(&f);
+ assert_eq!(src.info().video.as_ref().unwrap().codec, "H.264");
+ check_video(&ff, &f, 0, 10);
+ let e = check_audio(&ff, &f, 1e-4);
+ println!("ts_h264_aac: AAC max error {e:.2e}");
+}
+
+#[test]
+fn bdav_h264_with_lpcm_sample_exact() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "m2ts_h264_lpcm.m2ts");
+ let src = open(&f);
+ assert_eq!(src.info().container, "MPEG-2 TS (BDAV/AVCHD)");
+ let a = src.info().audio.clone().unwrap();
+ assert_eq!((a.codec.as_str(), a.channels, a.bits_per_sample), ("LPCM (Blu-ray)", 2, Some(24)));
+ check_video(&ff, &f, 0, 10);
+ assert_eq!(check_audio(&ff, &f, 0.0), 0.0);
+}
+
+#[test]
+fn avchd_ac3_audio() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "m2ts_h264_ac3.mts");
+ let src = open(&f);
+ check_video(&ff, &f, 0, 6);
+ let a = src.info().audio.clone().unwrap();
+ if filmcraft_codecs::audio::AC3_DECODER {
+ assert_eq!((a.codec.as_str(), a.channels), ("AC-3", 2));
+ let e = check_audio(&ff, &f, 1e-3);
+ println!("m2ts_h264_ac3: AC-3 max error {e:.2e}");
+ } else {
+ assert_eq!(a.codec, "AC-3 (unsupported)");
+ match src.audio(0, 100, 48_000) {
+ Err(MediaError::Unsupported(why)) => assert!(why.contains("AC-3"), "{why}"),
+ other => panic!("expected unsupported, got {:?}", other.map(|_| ())),
+ }
+ }
+}
+
+#[test]
+fn transport_stream_hevc_and_latm() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "ts_hevc_latm.ts");
+ let src = open(&f);
+ assert_eq!(src.info().video.as_ref().unwrap().codec, "HEVC");
+ assert_eq!(src.info().audio.as_ref().unwrap().codec, "AAC (LATM)");
+ check_video(&ff, &f, 0, 8);
+ let e = check_audio(&ff, &f, 1e-4);
+ println!("ts_hevc_latm: AAC (LATM) max error {e:.2e}");
+}
+
+#[test]
+fn program_streams() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "ps_mpeg2_mp2.vob");
+ let src = open(&f);
+ assert_eq!(src.info().container, "MPEG-2 PS");
+ let (worst, psnr) = check_video(&ff, &f, 4, 10);
+ assert!(psnr >= 58.0);
+ println!("ps_mpeg2_mp2: video max diff {worst}, PSNR {psnr:.2} dB");
+ check_audio(&ff, &f, 2e-4);
+ // DVD LPCM: sample-exact
+ let f = make(&ff, "ps_mpeg2_lpcm.vob");
+ let src = open(&f);
+ assert_eq!(src.info().audio.as_ref().unwrap().codec, "LPCM (DVD)");
+ assert_eq!(src.info().audio.as_ref().unwrap().bits_per_sample, Some(24));
+ assert_eq!(check_audio(&ff, &f, 0.0), 0.0);
+ check_video(&ff, &f, 4, 4);
+ let f = make(&ff, "ps_mpeg2_lpcm16.vob");
+ assert_eq!(open(&f).info().audio.as_ref().unwrap().bits_per_sample, Some(16));
+ assert_eq!(check_audio(&ff, &f, 0.0), 0.0);
+ // AC-3 in private stream 1
+ let f = make(&ff, "ps_mpeg2_ac3.vob");
+ let src = open(&f);
+ assert!(src.info().audio.as_ref().unwrap().codec.starts_with("AC-3"));
+ // MPEG-1 system stream
+ let f = make(&ff, "mpeg1_system.mpg");
+ let src = open(&f);
+ assert_eq!(src.info().container, "MPEG-1 System");
+ assert_eq!(src.info().video.as_ref().unwrap().codec, "MPEG-1 Video");
+ let (worst, psnr) = check_video(&ff, &f, 4, 6);
+ assert!(psnr >= 58.0);
+ println!("mpeg1_system: video max diff {worst}, PSNR {psnr:.2} dB");
+ check_audio(&ff, &f, 2e-4);
+}
+
+#[test]
+fn video_elementary_stream() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let f = make(&ff, "es_mpeg2.m2v");
+ let src = filmcraft_codecs::open_bytes("es_mpeg2.m2v", bytes(&f)).unwrap();
+ assert_eq!(src.info().container, "MPEG video elementary stream");
+ let raw = ffmpeg_frames(&ff, &f, "yuv420p");
+ let fsize = 352 * 288 * 3 / 2;
+ let n = raw.len() / fsize;
+ let rate = src.info().frame_rate();
+ assert_eq!(src.info().duration, rate.tick_of(n as i64));
+ for i in 0..n {
+ let fr = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).unwrap();
+ let d = max_diff(&planes(&fr), &raw_planes(&raw[i * fsize..(i + 1) * fsize], 352, 288, 176, 144, 1));
+ assert!(d <= 4, "frame {i}: {d}");
+ }
+}
+
+#[test]
+fn truncated_and_corrupt_files_never_panic() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ for name in ["ts_mpeg2_mp2.ts", "ps_mpeg2_mp2.vob", "ts_h264_aac.ts"] {
+ let f = make(&ff, name);
+ let full = std::fs::read(&f).unwrap();
+ let mut rng = Rng(0xC0FFEE);
+ let exercise = |data: Vec<u8>, rng: &mut Rng| {
+ let Ok(s) = MpegSource::open(name, data.into()) else { return };
+ let info = s.info().clone();
+ if let Some(v) = &info.video {
+ let frames = v.frame_rate.frame_at(info.duration).max(1);
+ for _ in 0..3 {
+ let i = rng.below(frames as u64) as i64;
+ let _ = s.video_frame(FrameRequest::full(v.frame_rate.tick_of(i)));
+ }
+ }
+ if let Some(a) = &info.audio {
+ let _ = s.audio(rng.below(48_000) as i64, 2048, a.sample_rate);
+ }
+ };
+ for k in 1..=8 {
+ exercise(full[..full.len() * k / 9].to_vec(), &mut rng);
+ }
+ for _ in 0..12 {
+ let mut m = full.clone();
+ for _ in 0..40 {
+ let i = rng.below(m.len() as u64) as usize;
+ m[i] = rng.below(256) as u8;
+ }
+ exercise(m, &mut rng);
+ }
+ }
+}
+
+#[test]
+#[ignore]
+fn generate_fixtures() {
+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("codecs mpeg fixtures") else { return };
+ for name in ALL {
+ let out = [dir().join(name)];
+ filmcraft_testkit::fixtures::generate_and_report(&format!("codecs/{name}"), &out, || {
+ let args = spec(name);
+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();
+ fixture(&ff, name, &refs)
+ });
+ }
+}
diff --git a/crates/mpegts/src/es.rs b/crates/mpegts/src/es.rs
index 901db0b31..ecc157071 100644
--- a/crates/mpegts/src/es.rs
+++ b/crates/mpegts/src/es.rs
@@ -161,6 +161,83 @@ pub(crate) fn mpa_header(b: &[u8]) -> Option<(usize, u32, u32)> {
(bytes >= 4).then_some((bytes, rate, samples))
}
+/// What an audio frame header says.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct FrameInfo {
+ pub sample_rate: u32,
+ pub channels: u32,
+ /// Samples per channel in the frame.
+ pub samples: u32,
+ /// MPEG audio layer (1-3); AC-3 bsid; ADTS object type (profile + 1).
+ pub variant: u8,
+}
+
+const ADTS_RATES: [u32; 13] = [96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000, 7_350];
+
+/// Parse the frame header at the start of `b` (MPEG audio, ADTS, AC-3, E-AC-3).
+pub fn frame_info(codec: &Codec, b: &[u8]) -> Option<FrameInfo> {
+ match codec {
+ Codec::MpegAudio => {
+ let (_, sample_rate, samples) = mpa_header(b)?;
+ let layer = 4 - ((b[1] >> 1) & 3);
+ Some(FrameInfo { sample_rate, channels: if b[3] >> 6 == 3 { 1 } else { 2 }, samples, variant: layer })
+ }
+ Codec::AacAdts => {
+ frame_len(AudioSync::Adts, b)?;
+ let sf = ((b[2] >> 2) & 15) as usize;
+ let ch = (((b[2] & 1) << 2) | (b[3] >> 6)) as u32;
+ Some(FrameInfo {
+ sample_rate: *ADTS_RATES.get(sf)?,
+ channels: if ch == 0 {
+ 2
+ } else if ch == 7 {
+ 8
+ } else {
+ ch
+ },
+ samples: 1024 * ((b[6] & 3) as u32 + 1),
+ variant: (b[2] >> 6) + 1,
+ })
+ }
+ Codec::Ac3 | Codec::Eac3 => {
+ frame_len(AudioSync::Ac3, b)?;
+ let bsid = b[5] >> 3;
+ if bsid > 10 {
+ // E-AC-3: fscod(2) numblkscod(2) acmod(3) lfeon(1)
+ let fscod = b[4] >> 6;
+ let (rate, blocks) = if fscod == 3 {
+ ([24_000, 22_050, 16_000, 0][((b[4] >> 4) & 3) as usize], 6)
+ } else {
+ ([48_000, 44_100, 32_000][fscod as usize], [1, 2, 3, 6][((b[4] >> 4) & 3) as usize])
+ };
+ let acmod = (b[4] >> 1) & 7;
+ return Some(FrameInfo { sample_rate: rate, channels: AC3_CHANNELS[acmod as usize] + (b[4] & 1) as u32, samples: 256 * blocks, variant: bsid });
+ }
+ let fscod = b[4] >> 6;
+ let rate = *[48_000u32, 44_100, 32_000].get(fscod as usize)?;
+ // bsi: bsid(5) bsmod(3) acmod(3) [cmixlev(2)] [surmixlev(2)] [dsurmod(2)] lfeon(1)
+ let acmod = b[6] >> 5;
+ let mut bit = 3; // bits of byte 6 consumed
+ if acmod & 1 != 0 && acmod != 1 {
+ bit += 2;
+ }
+ if acmod & 4 != 0 {
+ bit += 2;
+ }
+ if acmod == 2 {
+ bit += 2;
+ }
+ let word = u16::from_be_bytes([b[6], *b.get(7)?]);
+ let lfe = (word >> (15 - bit)) & 1;
+ Some(FrameInfo { sample_rate: rate, channels: AC3_CHANNELS[acmod as usize] + lfe as u32, samples: 1536, variant: bsid })
+ }
+ _ => None,
+ }
+}
+
+/// Full-bandwidth channels per AC-3 audio coding mode (A/52 Table 5.8).
+const AC3_CHANNELS: [u32; 8] = [2, 1, 2, 3, 3, 4, 4, 5];
+
/// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)`
/// is never returned).
fn frame_len(sync: AudioSync, b: &[u8]) -> Option<usize> {
diff --git a/crates/mpegts/src/lib.rs b/crates/mpegts/src/lib.rs
index 3a3c41431..226b20fac 100644
--- a/crates/mpegts/src/lib.rs
+++ b/crates/mpegts/src/lib.rs
@@ -19,6 +19,7 @@
//! The crate does no decoding; `filmcraft-codecs` pairs the streams with decoders.
mod es;
+pub use es::{FrameInfo, frame_info};
mod pes;
mod ps;
mod ts;