Skip to content

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

M9.13: Opus in WebM/MKV and MP4 import

Brandon Thomas608a83f33e29
diff --git a/Cargo.lock b/Cargo.lock
index 571be195e..f1044aa2e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1361,6 +1361,7 @@ dependencies = [
"filmcraft-isobmff",
"filmcraft-matroska",
"filmcraft-media",
+ "filmcraft-opus",
"filmcraft-prores",
"filmcraft-time",
"image",
diff --git a/README.md b/README.md
index bb0576d08..7bac706c0 100644
--- a/README.md
+++ b/README.md
@@ -103,7 +103,7 @@ FilmCraft is a non-linear editor for people who know Premiere: the same panels,
## Formats and codecs
-No FFmpeg inside. The video codecs, AAC and the containers are our own Rust code, implemented from the public ITU-T, ISO and IETF specifications and tested frame by frame against ffmpeg as an external oracle.
+No FFmpeg inside. The video codecs, AAC, Opus and the containers are our own Rust code, implemented from the public ITU-T, ISO and IETF specifications and tested frame by frame against ffmpeg as an external oracle.
| | Decode | Encode | Notes |
|---|:---:|:---:|---|
@@ -111,13 +111,14 @@ No FFmpeg inside. The video codecs, AAC and the containers are our own Rust code
| **HEVC / H.265** | ✓ | | Main and Main 10, bit-exact on 41 streams (tiles, WPP, PCM, long-term references), about 225 fps at 1080p |
| **Apple ProRes** | ✓ | ✓ | Decodes 422 Proxy to 4444 XQ; export writes 422 HQ |
| **AAC-LC** | ✓ | ✓ | |
+| **Opus** | ✓ | | SILK, CELT, hybrid and multistream surround; range-exact on every RFC 8251 conformance vector; in WebM/Matroska and MP4 |
| **MJPEG, PCM** | ✓ | ✓ | |
| **MP3, FLAC, ALAC, Vorbis** | ✓ | | Via the [symphonia](https://github.com/pdeljanov/Symphonia) crate (MPL-2.0) for now, to be replaced by our own |
| **MP4 / MOV** | ✓ | ✓ | Fragmented MP4, edit lists, timecode tracks |
| **Matroska / WebM** | ✓ | | Lacing, Cues, header stripping, HDR colour metadata |
| **Stills** | ✓ | ✓ | Import PNG, JPEG, GIF, WebP, TIFF and BMP; export PNG sequences and animated GIF |
-VP9, Opus, AV1, DNxHR and MXF are next ([roadmap](ROADMAP.md)).
+VP9, AV1, DNxHR and MXF are next ([roadmap](ROADMAP.md)).
<br>
diff --git a/ROADMAP.md b/ROADMAP.md
index 245a1e2d3..d239015e6 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -37,7 +37,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining
| M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 |
| M7 | Audio | 🟡 | Mixer basics, peak meters, BS.1770 loudness meters (M/S/I LUFS, true peak; matches ffmpeg), DSP crate, 12 clip audio effects running on it (EQ, filters, dynamics, limiter, delay, reverb, DeNoise, DeHum, pitch) with keyframes | Effects UI polish (EQ curve), remaining effects (multiband, convolution reverb), track effects/mixers with automation, Essential Sound, audio transitions, 5.1 | 6–10 |
| M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette; basic scopes | LUT import UI, colour match, colour management + HDR (PQ/HLG, log, tone mapping) | 8–12 |
-| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), Matroska/WebM import (H.264/HEVC/ProRes/MJPEG + AAC/FLAC/MP3/Vorbis/PCM) | VP9 and Opus (in progress), AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
+| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), Matroska/WebM import (H.264/HEVC/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4) | VP9 (in progress), Ogg Opus files, AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
| M10 | Graphics & captions | ⬜ | — | Text engine, Type tool, Essential Graphics, captions (SRT/VTT/SCC), speech-to-text | 20–30 |
| M11 | Interchange & project management | 🟡 | `.fcproj` save/open | Autosave/recovery, FCP7 XML, FCPXML, EDL, OTIO, relink, project manager, proxies | 15 |
| M12–M16 | Web (WASM), platform, long tail | 🟡 | L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), ~850 remaining commands and dialogs, performance hardening | 40–65 |
@@ -45,11 +45,11 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining
## Running now
- VP9 decoder (`crates/vp9`), from the public VP9 bitstream spec
-- Opus decoder (`crates/opus`), from RFC 6716/8251
- Interchange (`crates/interchange`): CMX 3600 EDL, FCP7 XML, FCPXML, OTIO import and export
## Log
+- **2026-09-30 (evening):** Opus decoder (RFC 6716/8251, range-exact on every conformance vector, ~80–110× realtime 48 kHz stereo) wired into WebM/MKV and MP4 import.
- **2026-09-30 (afternoon):** Matroska/WebM import; LUFS meters; clip audio effects on the DSP crate.
- **2026-09-30 (midday):** HEVC decoder, Matroska/WebM demuxer and audio DSP merged; HEVC import wired; asset rules (AGENTS.md, ATTRIBUTION.md, `cargo xtask assets`); README with hero screenshot and the Craft family.
- **2026-09-30 (late morning):** keyframe value/velocity graphs; xtask gates; H.264 MP4 export; Lumetri curves, wheels, looks, HSL secondary.
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index 9b98df6a1..ee250a8c5 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -21,6 +21,7 @@ filmcraft-h264 = { workspace = true }
filmcraft-hevc = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-aac = { workspace = true }
+filmcraft-opus = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rs
index 48c48f4e0..ab7aa7d4f 100644
--- a/crates/codecs/src/audio.rs
+++ b/crates/codecs/src/audio.rs
@@ -17,10 +17,51 @@ use crate::{CodecError, Result};
enum Inner {
/// Our own AAC-LC decoder.
Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8> },
+ /// 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]> },
/// Bootstrap decoders (MP3, ALAC, FLAC, HE-AAC…) via symphonia.
Symphonia(Box<dyn Decoder>),
}
+/// Opus always decodes at 48 kHz (RFC 7845 §5.1: the input rate in the header is informational).
+pub const OPUS_RATE: u32 = 48_000;
+
+/// Opus pre-roll decoded before a random-access target, in 48 kHz frames: 320 ms.
+///
+/// The containers' 80 ms (RFC 7845 §4.6, Matroska `SeekPreRoll`) is enough to sound right, but the
+/// CELT energy predictor converges only ~24 dB per 80 ms: measured against a continuous decode, a
+/// cold start 80 ms early is ~26 dB off, 320 ms early ~89 dB (float-exact). Seeking must give the
+/// same samples as playback (render caches, scrubbing), so we pay the extra few packets.
+pub const OPUS_PRE_ROLL: u32 = 4 * 3840;
+
+/// Channel order for Vorbis-ordered surround (Opus mapping family 1, RFC 7845 §5.1.1.2): output
+/// channel → decoded channel, giving the WAV/SMPTE order (L R C LFE back… side…) used elsewhere.
+fn vorbis_to_wav_order(channels: usize) -> Option<&'static [usize]> {
+ Some(match channels {
+ 3 => &[0, 2, 1],
+ 5 => &[0, 2, 1, 3, 4],
+ 6 => &[0, 2, 1, 5, 3, 4],
+ 7 => &[0, 2, 1, 6, 5, 3, 4],
+ 8 => &[0, 2, 1, 7, 5, 6, 3, 4],
+ _ => return None,
+ })
+}
+
+/// Duration of an Opus packet in 48 kHz samples from its TOC and frame count (RFC 6716 §3.1),
+/// without parsing frame lengths. For a multistream packet this is the first stream's TOC, which
+/// every stream shares. `None` for an empty or invalid (> 120 ms) packet.
+pub fn opus_packet_samples(data: &[u8]) -> Option<usize> {
+ let toc = filmcraft_opus::Toc::parse(*data.first()?);
+ let frames = match data[0] & 3 {
+ 0 => 1,
+ 1 | 2 => 2,
+ _ => (*data.get(1)? & 0x3F) as usize,
+ };
+ let n = toc.frame_samples_48k() * frames;
+ (n > 0 && n <= 5760).then_some(n)
+}
+
/// A packet decoder producing planar f32.
pub struct PacketDecoder {
inner: Inner,
@@ -45,6 +86,18 @@ impl PacketDecoder {
}
Self::new(CODEC_TYPE_AAC, sample_rate, Some(asc.to_vec()))
}
+ /// Opus from an `OpusHead` (Matroska `CodecPrivate`, Ogg) or a `dOps` box payload. Output is
+ /// 48 kHz; pre-skip is *not* trimmed here (Matroska `CodecDelay` / MP4 edit lists do that).
+ pub fn opus(head: filmcraft_opus::OpusHead) -> Result<Self> {
+ let dec = filmcraft_opus::Decoder::from_head(head, OPUS_RATE).map_err(|e| CodecError::Unsupported(format!("Opus: {e}")))?;
+ let channels = dec.channels();
+ 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 })
+ }
+ /// 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 { .. })
+ }
pub fn for_isobmff(c: &filmcraft_isobmff::CodecConfig, rate: u32) -> Result<Self> {
use filmcraft_isobmff::CodecConfig as C;
match c {
@@ -52,6 +105,7 @@ impl PacketDecoder {
C::Mp3 => Self::new(CODEC_TYPE_MP3, rate, None),
C::Alac { cookie } => Self::new(CODEC_TYPE_ALAC, rate, Some(cookie.clone())),
C::Flac(_) => Self::new(CODEC_TYPE_FLAC, rate, None),
+ C::Opus(o) => Self::opus(filmcraft_opus::OpusHead::from_dops(&o.to_bytes()).map_err(|e| CodecError::Unsupported(format!("Opus: {e}")))?),
other => Err(CodecError::Unsupported(format!("{} audio", other.name()))),
}
}
@@ -63,6 +117,18 @@ impl PacketDecoder {
self.channels = out.len();
return Ok(out);
}
+ Inner::Opus { dec, order } => {
+ // A corrupt packet is concealed like a lost one (keeps timing and decoder state).
+ let mut out = match dec.decode(Some(data)) {
+ Ok(o) => o,
+ Err(_) => dec.decode(None).map_err(|e| CodecError::Decode(e.to_string()))?,
+ };
+ if let Some(order) = order {
+ out = order.iter().map(|&c| std::mem::take(&mut out[c])).collect();
+ }
+ self.channels = out.len();
+ return Ok(out);
+ }
Inner::Symphonia(d) => d,
};
let pkt = Packet::new_from_slice(0, ts, 0, data);
@@ -89,6 +155,7 @@ impl PacketDecoder {
**dec = d;
}
}
+ Inner::Opus { dec, .. } => dec.reset(),
Inner::Symphonia(d) => d.reset(),
}
}
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index 90abae2b8..e5134fd95 100644
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@ -1,8 +1,13 @@
//! 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.
+//! containers (H.264, HEVC, ProRes, MJPEG; VP9/AV1 once their decoders land). Audio: AAC and Opus
+//! via our decoders, PCM directly, MP3/FLAC/Vorbis via the bootstrap decoders.
+//!
+//! Opus (`A_OPUS`): `CodecPrivate` is the `OpusHead`; output is always 48 kHz. The demuxer
+//! subtracts `CodecDelay` from timestamps, so the pre-skip samples land before zero and are never
+//! read; random access decodes `SeekPreRoll` (at least [`crate::audio::OPUS_PRE_ROLL`]) of preceding
+//! packets before the target. Packet starts are accumulated from TOC durations (see [`opus_starts`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -42,6 +47,47 @@ pub struct MkvSource {
audio: Mutex<AudioState>,
/// Audio packet start positions in source sample frames.
audio_starts: Vec<i64>,
+ /// Decoder pre-roll after a seek, in source sample frames (0: prime with one packet).
+ audio_preroll: i64,
+}
+
+/// Sample-exact Opus packet start positions (48 kHz frames, pre-skip removed).
+///
+/// Block timestamps are quantised to `TimestampScale` (usually 1 ms) and the demuxer subtracts a
+/// rounded `CodecDelay`, so they are only accurate to a tick. Starts are therefore accumulated from
+/// each packet's TOC duration, resynchronising to the timestamp only across real gaps (more than
+/// two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is absent).
+fn opus_starts(file: &MkvFile, bytes: &[u8], ti: usize, head: &filmcraft_opus::OpusHead, rate: i64) -> Vec<i64> {
+ let t = &file.tracks[ti];
+ let (n, d) = tb(t);
+ let scale_ns = (n as i128 * 1_000_000_000 / d as i128).max(1);
+ let delay_ns = t.codec_delay_ns as i128;
+ // The demuxer's rounding of CodecDelay to ticks (half away from zero), undone here.
+ let delay_ticks = ((delay_ns + scale_ns / 2) / scale_ns) as i64;
+ let skip = if t.codec_delay_ns > 0 { (delay_ns * rate as i128 / 1_000_000_000) as i64 } else { head.pre_skip as i64 };
+ let at = |pts: i64| ((pts + delay_ticks) as i128 * n as i128 * rate as i128 / d as i128) as i64 - skip;
+ let tolerance = (2 * scale_ns * rate as i128 / 1_000_000_000) as i64 + 1;
+ let mut starts = Vec::with_capacity(t.samples.len());
+ let mut next: Option<i64> = None;
+ for (i, s) in t.samples.iter().enumerate() {
+ let stamped = at(s.pts);
+ let start = match next {
+ Some(p) if (p - stamped).abs() <= tolerance => p,
+ _ => stamped,
+ };
+ starts.push(start);
+ let dur = file.read_sample(bytes, ti, i).ok().and_then(|p| crate::audio::opus_packet_samples(&p));
+ next = dur.map(|k| start + k as i64);
+ }
+ starts
+}
+
+/// The parsed `OpusHead` of an `A_OPUS` track.
+fn opus_head(c: &Codec) -> Option<filmcraft_opus::OpusHead> {
+ match c {
+ Codec::Opus { head } => filmcraft_opus::OpusHead::parse(head).ok(),
+ _ => None,
+ }
}
/// Seconds per track timestamp unit as a rational.
@@ -162,13 +208,13 @@ impl MkvSource {
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 mut rate = a.output_sampling_frequency.unwrap_or(a.sampling_frequency).round().max(1.0) as u32;
+ let mut channels = (a.channels as u32).max(1);
+ if let Some(h) = opus_head(&t.codec) {
+ rate = crate::audio::OPUS_RATE;
+ channels = h.channels as u32;
}
+ AudioStreamInfo { sample_rate: rate, channels, 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),
@@ -196,9 +242,26 @@ impl MkvSource {
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()
+ let at = |pts: i64| (pts as i128 * n as i128 * rate as i128 / d as i128) as i64;
+ match opus_head(&t.codec) {
+ Some(h) => opus_starts(&file, &bytes, i, &h, rate),
+ None => t.samples.iter().map(|s| at(s.pts)).collect(),
+ }
})
.unwrap_or_default();
+ let audio_preroll = atrack
+ .map(|i| {
+ let t = &file.tracks[i];
+ let rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64;
+ match t.codec {
+ Codec::Opus { .. } => {
+ let container = (t.seek_pre_roll_ns as u128 * rate as u128).div_ceil(1_000_000_000) as i64;
+ container.max(crate::audio::OPUS_PRE_ROLL as i64 * rate / 48_000)
+ }
+ _ => 0,
+ }
+ })
+ .unwrap_or(0);
Ok(Self {
info,
bytes,
@@ -209,6 +272,7 @@ impl MkvSource {
video: GopCache::new(explicit_color),
audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),
audio_starts,
+ audio_preroll,
})
}
@@ -220,6 +284,7 @@ impl MkvSource {
use symphonia::core::codecs::{CODEC_TYPE_FLAC, CODEC_TYPE_MP3, CODEC_TYPE_VORBIS};
match c {
Codec::Aac { asc } => PacketDecoder::aac(asc, rate),
+ Codec::Opus { head } => PacketDecoder::opus(filmcraft_opus::OpusHead::parse(head).map_err(|e| CodecError::Unsupported(format!("Opus: {e}")))?),
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)),
@@ -256,14 +321,20 @@ impl MkvSource {
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).
+ // Non-sequential access: reset and prime with the preceding packets (codec pre-roll:
+ // one packet, or `SeekPreRoll` worth for Opus).
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 from = if self.audio_preroll > 0 {
+ self.audio_starts.partition_point(|&x| x <= self.audio_starts[i] - self.audio_preroll).saturating_sub(1)
+ } else {
+ i.saturating_sub(1)
+ };
+ for j in from..i {
+ if let Ok(prev) = self.read(ti, j) {
+ let _ = d.decode(&prev, 0);
+ }
}
}
let r = st.decoder.as_mut().expect("decoder").decode(&data, self.audio_starts[i].max(0) as u64);
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 4497bc2f2..3cc08b874 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -1,4 +1,8 @@
//! MP4/MOV media source with GOP-aware random access (see [`crate::gop`]).
+//!
+//! Opus (`Opus` sample entry + `dOps`): always 48 kHz output. Pre-skip is removed by the edit list
+//! (`media_time` = pre-skip), or applied from `dOps` when a file has no edit list; random access
+//! decodes [`crate::audio::OPUS_PRE_ROLL`] of preceding packets first (≥ the 80 ms `roll` distance).
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -32,6 +36,10 @@ pub struct Mp4Source {
audio: Mutex<AudioState>,
/// Cumulative sample start frames for the audio track (for packet lookup).
audio_starts: Vec<i64>,
+ /// Presentation offset of the audio track in its timescale (edit list, or Opus pre-skip).
+ audio_offset: i64,
+ /// Decoder pre-roll after a seek, in audio track timescale units (0: prime with one packet).
+ audio_preroll: i64,
}
pub fn sniff(b: &[u8]) -> bool {
@@ -120,6 +128,7 @@ impl Mp4Source {
None,
),
CodecConfig::Pcm(p) => (p.sample_rate as u32, p.channels, Some(p.bits as u32)),
+ CodecConfig::Opus(o) => (crate::audio::OPUS_RATE, (o.output_channels as u32).max(1), None),
_ => (if ap.sample_rate > 0.0 { ap.sample_rate as u32 } else { t.timescale }, ap.channels.max(1), None),
};
AudioStreamInfo { sample_rate: rate.max(1), channels: ch.max(1), codec: codec_label(&entry.codec), bits_per_sample: bits }
@@ -163,6 +172,19 @@ impl Mp4Source {
.collect()
})
.unwrap_or_default();
+ let (audio_offset, audio_preroll) = atrack
+ .map(|i| {
+ let t = &file.tracks[i];
+ let ts = t.timescale.max(1) as i64;
+ match &t.entries[0].codec {
+ CodecConfig::Opus(o) => {
+ let off = if t.edit_offset != 0 { t.edit_offset } else { -(o.pre_skip as i64) * ts / 48_000 };
+ (off, (crate::audio::OPUS_PRE_ROLL as u64 * ts as u64).div_ceil(48_000) as i64)
+ }
+ _ => (t.edit_offset, 0),
+ }
+ })
+ .unwrap_or((0, 0));
Ok(Self {
info,
bytes,
@@ -172,6 +194,8 @@ impl Mp4Source {
video: GopCache::new(explicit_color),
audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),
audio_starts,
+ audio_offset,
+ audio_preroll,
})
}
@@ -199,14 +223,20 @@ impl Mp4Source {
if st.decoder.is_none() {
st.decoder = Some(PacketDecoder::for_isobmff(c, self.info.audio.as_ref().map_or(48_000, |a| a.sample_rate))?);
}
- // Non-sequential access: reset and prime with the previous packet (codec pre-roll).
+ // Non-sequential access: reset and prime with the preceding packets (codec pre-roll:
+ // one packet, or `OPUS_PRE_ROLL` worth for Opus).
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 from = if self.audio_preroll > 0 {
+ self.audio_starts.partition_point(|&x| x <= self.audio_starts[i] - self.audio_preroll).saturating_sub(1)
+ } else {
+ i.saturating_sub(1)
+ };
+ for j in from..i {
+ if let Ok(prev) = self.read(ti, j) {
+ let _ = d.decode(&prev, 0);
+ }
}
}
let r = st.decoder.as_mut().expect("decoder").decode(&data, self.audio_starts[i].max(0) as u64);
@@ -273,7 +303,7 @@ impl MediaSource for Mp4Source {
let ch = ainfo.channels.max(1) as usize;
// Map the requested window to source samples (edit list offset applied: presentation = pts + edit_offset).
let ratio = src_rate as f64 / sample_rate as f64;
- let s0 = (start as f64 * ratio).floor() as i64 - track.edit_offset * src_rate as i64 / track.timescale.max(1) as i64;
+ let s0 = (start as f64 * ratio).floor() as i64 - self.audio_offset * src_rate as i64 / track.timescale.max(1) as i64;
let need = (frames as f64 * ratio).ceil() as i64 + 2;
// Samples-per-unit: the track timescale is usually the sample rate for audio.
let unit = src_rate as f64 / track.timescale.max(1) as f64;
@@ -356,6 +386,7 @@ fn codec_label(c: &CodecConfig) -> String {
}
}
CodecConfig::Pcm(p) => format!("PCM {}-bit{}", p.bits, if p.float { " float" } else { "" }),
+ CodecConfig::Opus(_) => "Opus".into(),
other => other.name().to_string(),
}
}
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index 1adfdb3c9..601f2048b 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -178,3 +178,126 @@ fn matroska_hevc_flac() {
fn matroska_prores_pcm() {
check_mkv("blue_prores_pcm.mkv", &["-c:v", "prores_ks", "-profile:v", "2"], &["-c:a", "pcm_s16le"]);
}
+
+/// ffmpeg + libopus decode of a container fixture (pre-skip / codec delay / edit list applied) as
+/// interleaved f32 at 48 kHz: the reference for our Opus path.
+fn opus_reference(name: &str) -> Option<Vec<f32>> {
+ let ff = ffmpeg()?;
+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/codecs");
+ let out = dir.join(format!("{name}.ref.f32"));
+ let st = Command::new(ff)
+ .args(["-y", "-v", "error", "-c:a", "libopus", "-i"])
+ .arg(dir.join(name))
+ .args(["-f", "f32le", "-ar", "48000"])
+ .arg(&out)
+ .status()
+ .ok()?;
+ if !st.success() {
+ return None;
+ }
+ Some(std::fs::read(out).ok()?.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
+}
+
+fn snr_db(reference: &[f32], test: &[f32]) -> f64 {
+ let (mut s, mut e) = (0f64, 0f64);
+ for (r, t) in reference.iter().zip(test) {
+ s += (*r as f64).powi(2);
+ e += (*r as f64 - *t as f64).powi(2);
+ }
+ if e == 0.0 { 200.0 } else { 10.0 * (s.max(1e-20) / e).log10() }
+}
+
+/// Interleaves `frames` of `src.audio` from `start` (48 kHz).
+fn read_interleaved(src: &filmcraft_media::SharedSource, start: i64, frames: usize) -> Vec<f32> {
+ let a = src.audio(start, frames, 48_000).expect("audio");
+ let ch = a.channels.len();
+ let mut v = vec![0f32; frames * ch];
+ for (c, chan) in a.channels.iter().enumerate() {
+ for (i, s) in chan.iter().enumerate() {
+ v[i * ch + c] = *s;
+ }
+ }
+ v
+}
+
+/// Opus in a container: metadata, sample-exact alignment (pre-skip honoured) against libopus for a
+/// sequential read, and the same samples after random access (pre-roll).
+fn check_opus(name: &str, channels: usize, expr: &str, extra: &[&str], container: &str) {
+ let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", expr, "-t", "3", "-c:a", "libopus"];
+ args.extend_from_slice(extra);
+ let Some(b) = fixture(name, &args) else { return };
+ let Some(reference) = opus_reference(name) else {
+ eprintln!("libopus decoder unavailable; skipping {name}");
+ return;
+ };
+ let src = crate::open_bytes(name, b).expect("open");
+ let info = src.info().clone();
+ assert_eq!(info.container, container);
+ let a = info.audio.as_ref().expect("audio");
+ assert_eq!((a.codec.as_str(), a.sample_rate, a.channels as usize), ("Opus", 48_000, channels));
+ let d = info.duration.seconds();
+ assert!((d - 3.0).abs() < 0.03, "{name}: duration {d}");
+ let total = reference.len() / channels;
+ assert!((total as i64 - 144_000).abs() < 960, "{name}: reference length {total}");
+
+ // Sequential read in 100 ms blocks.
+ let mut ours = Vec::with_capacity(reference.len());
+ let mut pos = 0;
+ while pos < total {
+ let n = 4800.min(total - pos);
+ ours.extend(read_interleaved(&src, pos as i64, n));
+ pos += n;
+ }
+ let snr = snr_db(&reference, &ours);
+ eprintln!("{name}: sequential SNR vs libopus {snr:.1} dB");
+ assert!(snr > 40.0, "{name}: sequential SNR {snr:.1} dB");
+
+ // Random access on a fresh source (cold decoder): 100 ms at 1.7 s, then back to 0.5 s.
+ let src = crate::open_bytes(name, fixture(name, &args).expect("fixture")).expect("open");
+ for start in [81_600usize, 24_000] {
+ let got = read_interleaved(&src, start as i64, 4800);
+ let want = &reference[start * channels..(start + 4800) * channels];
+ let snr = snr_db(want, &got);
+ eprintln!("{name}: random access at {start}: SNR {snr:.1} dB");
+ assert!(snr > 40.0, "{name}: random access at {start}: SNR {snr:.1} dB");
+ }
+}
+
+#[test]
+fn opus_webm_stereo() {
+ check_opus(
+ "tones_opus.webm",
+ 2,
+ "aevalsrc=0.4*sin(2*PI*440*t)+0.1*sin(2*PI*5000*t)|0.3*sin(2*PI*660*t)+0.1*sin(2*PI*3100*t):s=48000",
+ &["-b:a", "128k"],
+ "WebM",
+ );
+}
+
+#[test]
+fn opus_mkv_mono_speechlike_16k() {
+ // Low bitrate VoIP mode exercises SILK/hybrid; the input rate is 16 kHz but Opus still outputs 48 kHz.
+ check_opus("tones_opus_voip.mkv", 1, "aevalsrc=0.4*sin(2*PI*220*t)*(0.6+0.4*sin(2*PI*3*t)):s=16000", &["-b:a", "16k", "-application", "voip"], "Matroska");
+}
+
+#[test]
+fn opus_mkv_surround_51() {
+ check_opus(
+ "tones_opus_51.mkv",
+ 6,
+ "aevalsrc=0.3*sin(2*PI*300*t)|0.3*sin(2*PI*400*t)|0.3*sin(2*PI*500*t)|0.3*sin(2*PI*60*t)|0.3*sin(2*PI*700*t)|0.3*sin(2*PI*800*t):s=48000:c=5.1",
+ &["-b:a", "256k"],
+ "Matroska",
+ );
+}
+
+#[test]
+fn opus_mp4_stereo() {
+ check_opus(
+ "tones_opus.mp4",
+ 2,
+ "aevalsrc=0.4*sin(2*PI*440*t)+0.1*sin(2*PI*5000*t)|0.3*sin(2*PI*660*t)+0.1*sin(2*PI*3100*t):s=48000",
+ &["-b:a", "128k"],
+ "MPEG-4",
+ );
+}