diff --git a/Cargo.lock b/Cargo.lock index d67fee5..5054fa5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1642,6 +1642,7 @@ dependencies = [ "libloading", "miniz_oxide", "mp4", + "opus-rs", "oxideav-ac3", "oxideav-ass", "oxideav-core", @@ -3934,6 +3935,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "opus-rs" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f1ce2826529746cac003d7338e9c0f47cdd2979ba769c61cc26fdebc402f4c" + [[package]] name = "ordered-stream" version = "0.2.0" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cb64763..d9da87f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -98,6 +98,23 @@ rusty_vorbis = "0.1.1" # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` # below, because a decoder is a bit-exactness dependency. ruopus = { version = "=0.1.2", default-features = false, features = ["std"] } +# The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus +# 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not +# taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h` +# or `.S` file in the crate). It is what lets an edited Opus source leave in a +# Matroska file as Opus instead of being downgraded to AAC on the way out. +# +# Used inside a measured envelope, and that envelope is the whole reason this +# line is not simply "the encoder": 48 kHz **stereo** at **at most** +# [`crate::export::OPUS_MAX_KBPS`]. Above roughly 165 kbps stereo this encoder +# writes packets that only its *own* decoder reads back -- `ruopus` decodes them +# as noise (correlation 0.06 at 256 kbps against the source, 0.9999 at 160), and +# `ruopus` is not the suspect: it decodes ffmpeg's own libopus at 256 kbps to +# correlation 1.00000 on the same signal. Mono is worse and at every rate, which +# is why a mono mix keeps the AAC path. Both measured in +# `tests/opus_export.rs`, which fails the day the crate is unpinned onto a +# version that has fixed it -- that is the upgrade signal. +opus-rs = "=0.1.26" # The Ogg container, and the only new *name* here that is not a new crate tree: # its one dependency is `oxideav-core`, which the AC-3 decoder above already # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 4c90ee5..86370fc 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -216,6 +216,14 @@ impl Format { matches!(self, Self::Hevc | Self::HevcMp4) } + /// Whether the file is a Matroska one. Only that container carries this + /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but + /// the crate that writes the mp4s here has no sample entry for it, so the + /// mp4 formats stay on AAC and say so. + fn is_mkv(self) -> bool { + matches!(self, Self::Av1 | Self::Hevc) + } + /// What the format is called where a refusal names it. pub fn name(self) -> &'static str { match self { @@ -537,6 +545,20 @@ fn audio_label( Format::Ogg => "Vorbis · SW (rusty_vorbis)", _ => match copied.unwrap_or(!forces_encode(project)) { true => "AAC copy", + // A Matroska file gets Opus where the mix allows it -- 48 kHz and + // stereo, which is every Opus source and most of everything else -- + // and AAC where it does not ([`encode_audio`]). Which of the two it + // will be cannot be known here: both answers need a source opened, + // and this function may be asked per repaint. So the card names the + // codec it will nearly always be, as a prediction like the copy above + // it, and the line the export publishes while it runs is the measured + // one ([`run`]) -- it says AAC when the fallback took it, so the + // fallback is visible rather than silent. + // + // It is one line and 76 characters wide (`summary_head` in the app + // has the test), which is why the condition is in this comment + // instead of in the string. + false if format.is_mkv() => "Opus · SW encode (opus-rs)", false => "AAC · SW encode (rusty_aac)", }, } @@ -800,6 +822,11 @@ pub(crate) struct ExportAudio { pub packets: Vec, /// Whether those packets are the source's, untouched. pub copied: bool, + /// The track's pre-skip in samples where those packets are **Opus** and not + /// AAC ([`encode_opus`]), which is what the Matroska track entry states in + /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is + /// every copy and every mp4. + pub opus_pre_skip: Option, } /// The timeline's audio track for a file that carries picture: copied packet for @@ -820,6 +847,7 @@ fn copy_audio( project: &Project, meta: &VideoMeta, kbps: u32, + mkv: bool, ) -> crate::Result> { // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning @@ -844,7 +872,7 @@ fn copy_audio( // whole comment is about. let lanes = project.audio_segments_from(0, meta.frame_rate); let [segments] = &lanes[..] else { - return encode_audio(project, meta, kbps); + return encode_audio(project, meta, kbps, mkv); }; // ...and the same list names *which* lane those clips sit on, which is the // only way to ask what has been done to them. @@ -882,7 +910,7 @@ fn copy_audio( // such a lane would write it at unity and unlimited, silently. let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); if speeded || equalized(project) || mastered(project) { - return encode_audio(project, meta, kbps); + return encode_audio(project, meta, kbps, mkv); } // What is left is a copy the *sources* may still not be able to give: AAC // inside a Matroska file (readable, but not out of a sample table this walks @@ -897,8 +925,12 @@ fn copy_audio( params, packets, copied: true, + // A copy is the source's own AAC packets: there is no Opus copy + // path here, since the packets an mkv source holds never reach this + // (they are not in a sample table) and every one of them re-encodes. + opus_pre_skip: None, })), - Err(_) => encode_audio(project, meta, kbps), + Err(_) => encode_audio(project, meta, kbps, mkv), } } @@ -1151,6 +1183,7 @@ fn encode_audio( project: &Project, meta: &VideoMeta, kbps: u32, + mkv: bool, ) -> crate::Result> { let sources = project.audio_sources(); let segs = project.audio_segments_from(0, meta.frame_rate); @@ -1189,6 +1222,34 @@ fn encode_audio( } samples.resize(total, 0.0); + // Opus where the container carries it and the mix is inside the envelope + // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file, + // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves + // as Opus instead of being turned into AAC on the way out, which is the one + // generation of loss an all-Opus timeline used to pay for being cut. + // + // Everything else falls through to the AAC below and is unchanged by this: + // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own -- + // there is no resampler on this path, and inventing one to reach 48 kHz + // would resample a whole timeline to satisfy a codec, which is a bigger + // change to the sound than the codec is. + if mkv + && audio.sample_rate == OPUS_RATE + && channels == 2 + && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)? + { + return Ok(Some(ExportAudio { + params: crate::AacTrackParams { + freq_index, + chan_conf: 2, + sample_rate: OPUS_RATE, + }, + packets, + copied: false, + opus_pre_skip: Some(pre_skip), + })); + } + // The caller's rate, never the encoder's own 128 default -- see // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256. let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig { @@ -1216,9 +1277,159 @@ fn encode_audio( }, packets, copied: false, + opus_pre_skip: None, })) } +/// The one rate Opus codes at. The container may state another one in its +/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a +/// timeline at any other rate is not "encoded at its own rate" here -- it is +/// resampled or it is not Opus, and [`encode_audio`] picks the second. +pub(crate) const OPUS_RATE: u32 = 48_000; + +/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes: +/// long enough that the per-packet overhead is nothing, short enough that a +/// Matroska block timestamp in whole milliseconds is exact. +const OPUS_FRAME: usize = 960; + +/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather +/// than the four rates the Sound row offers: this encoder falls off a cliff at a +/// rate that depends on the *content*, and above it a conformant decoder gets +/// noise back. Measured on three one-second spans of a real 5.1 Opus film, +/// encoded here and decoded with `ruopus` -- which is not the suspect, since it +/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same +/// material: +/// +/// ```text +/// kbps 120 128 136 144 152 160 +/// span A 0.945 0.937 0.452 0.206 0.223 0.163 +/// span B 0.986 0.989 0.697 0.153 0.114 0.149 +/// span C 0.999 0.994 0.951 0.335 0.266 0.326 +/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control) +/// ``` +/// +/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone +/// fixtures that first suggested a 165 kbps ceiling were simply easy material. +/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.998 +/// there on the worst of those spans), so the cap costs nothing a listener has. +/// It is still not *trusted*: every track is decoded again and measured before +/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the +/// material is not something a constant can be safe against on its own. +/// +/// ponytail: the ceiling is this encoder's, not the format's. Upgrade path is a +/// released `opus-rs` that survives its own high rates -- the unit test pins the +/// failure, so it fails the day the bug is fixed and this can be raised. +pub(crate) const OPUS_MAX_KBPS: u32 = 128; + +/// How well a track has to survive its own round trip to be written as Opus: +/// the correlation between the mix and the decode of what was encoded from it. +/// A good encoder scores 0.98-0.999 on this material (libopus, measured above); +/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap +/// with room on both sides, and what fails it is written as AAC -- the export's +/// own encoder line then says AAC, so the fallback is visible rather than +/// silent. +const OPUS_MIN_FIDELITY: f64 = 0.95; + +/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always +/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the +/// warm-up frame [`encode_opus`] throws away. Measured by +/// cross-correlating the decode against the source, not taken from the crate -- +/// it exposes no lookahead getter -- and asserted at both ends of the rate band +/// in `tests/opus_export.rs`, which is what catches a version that changes it. +const OPUS_PRE_SKIP: u16 = 120; + +/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has +/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller +/// checks both, because outside that pair this encoder is not one this project +/// is willing to write files with ([`OPUS_MAX_KBPS`]). +/// +/// The tail frame is padded with silence rather than dropped: Opus codes whole +/// frames and a track a few milliseconds short under a picture that is not is +/// the drift every other path here is written to avoid. The pre-skip trims the +/// front; the container's duration trims the back. +fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result, u16)>> { + let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio) + .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?; + encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32; + encoder.complexity = 10; + let mut packets = Vec::new(); + let mut frame = vec![0f32; OPUS_FRAME * 2]; + // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is + // that with room for the TOC and a padded frame, so `encode` never has to + // refuse for want of a buffer. + let mut out = vec![0u8; 1500]; + // The head, coded **twice**. An encoder's very first frame has no history + // behind it and comes out ramped and out of phase -- measured on a 440 Hz + // fixture, the first 20 ms of the export correlated 0.09 with the source + // where every later window correlated 0.9997 -- and 20 ms of wrong sound at + // the head of a file is the kind of thing nobody hears in a test and + // everybody hears in the first frame of a cut. So the first frame is fed in + // once to warm the encoder, and thrown away again by the pre-skip: exactly + // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet. + let warm = samples.len().min(OPUS_FRAME * 2); + // ...and one silent frame after the sound, for the same delay seen from the + // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so + // without a frame to push them out the last 2.5 ms of the timeline stay + // inside it and the track ends short under a picture that does not. + let blocks = std::iter::once(&samples[..warm]) + .chain(samples.chunks(OPUS_FRAME * 2)) + .chain(std::iter::once(&samples[..0])); + for block in blocks { + frame[..block.len()].copy_from_slice(block); + frame[block.len()..].fill(0.0); + let len = encoder + .encode(&frame, OPUS_FRAME, &mut out) + .map_err(|e| format!("Opus encode failed: {e}"))?; + packets.push(crate::AacPacket { + bytes: out[..len].to_vec(), + samples: OPUS_FRAME as u32, + }); + } + // ...and now the part that is not optimism: what was just written is + // decoded again and measured against what went in, and a track that does + // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller + // falls through to AAC, which is exactly where it stood before this seat + // existed -- a worse codec is a fair trade for a track that is the sound. + // + // ponytail: this costs one Opus decode of the whole track (a minute of + // sound in a few hundred milliseconds, against a video encode that is + // minutes). Upgrade path is deleting it, the day this encoder can be + // trusted at the rate it is asked for. + let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16; + let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip)); + Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip))) +} + +/// The correlation between `samples` and the decode of `packets` with the first +/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure +/// mode lands near 0.1. Streamed packet by packet -- the decode is never held, +/// only three running sums -- because the mix behind it is already the biggest +/// thing in an export ([`encode_audio`]'s ponytail). +/// +/// A packet the decoder refuses is 0.0 and no argument: a track this project +/// cannot read is exactly what this is here to catch. +fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 { + let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); + let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); + let mut drop = pre_skip * 2; + let mut at = 0; + for packet in packets { + let Ok(pcm) = decoder.decode_packet(&packet.bytes) else { + return 0.0; + }; + let pcm = &pcm[drop.min(pcm.len())..]; + drop = drop.saturating_sub(packet.samples as usize * 2); + for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) { + let (x, y) = (f64::from(*want), f64::from(*got)); + num += x * y; + da += x * x; + db += y * y; + at += 1; + } + } + num / (da.sqrt() * db.sqrt()).max(1e-12) +} + fn run( project: &Project, meta: &VideoMeta, @@ -1233,15 +1444,27 @@ fn run( // muxer wants the packets themselves that early too, because it interleaves // them into the clusters as it writes. Every video format gets the same // track: none of them is picture-only any more. - let audio = copy_audio(project, meta, audio_kbps_of(settings))?; + let audio = copy_audio( + project, + meta, + audio_kbps_of(settings), + settings.format.is_mkv(), + )?; let audio_params = audio.as_ref().map(|track| AudioParams { freq_index: track.params.freq_index, chan_conf: track.params.chan_conf, sample_rate: track.params.sample_rate, + opus_pre_skip: track.opus_pre_skip, }); // What the track *is*, kept before the packets are handed to a muxer: the // encoder line names a copy or an encode and only `copy_audio` knows which. let sound = audio.as_ref().map(|track| track.copied); + // ...and *which* encoder, for the same line: the card predicts Opus from the + // format alone and cannot know the mix's rate or width ([`audio_label`]), + // while this is after the mix was opened, so it is the measured answer. + let opus = audio + .as_ref() + .is_some_and(|track| track.opus_pre_skip.is_some()); // Taken by the Matroska muxer at creation; the mp4 one writes its track // after the picture, so for that path this is still `Some` at the end. let mut packets = audio.map(|track| track.packets); @@ -1316,7 +1539,10 @@ fn run( *shared.encoders.lock().unwrap() = Some(format!( "{} · {}", encoder.label(), - audio_label(project, settings.format, sound.is_some(), sound) + match opus { + true => "Opus · SW encode (opus-rs)", + false => audio_label(project, settings.format, sound.is_some(), sound), + } )); let mut muxer = None; let mut done = 0u32; @@ -2795,6 +3021,147 @@ impl SwDecoder { mod tests { use super::*; + /// Three seconds of two tones, one per channel, interleaved: enough shape + /// that a correlation says something and enough length that the encoder + /// settles into a mode. + fn two_tones(secs: usize) -> Vec { + (0..OPUS_RATE as usize * secs) + .flat_map(|i| { + let t = i as f32 / OPUS_RATE as f32; + let tau = std::f32::consts::TAU; + [ + 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(), + 0.25 * (tau * 880.0 * t).sin(), + ] + }) + .collect() + } + + /// The best correlation of one channel of `got` against `want`, and the + /// offset it sat at. + fn align(want: &[f32], got: &[f32]) -> (f64, usize) { + let (mut best, mut at) = (-2.0, 0); + let window = OPUS_RATE as usize; + for lag in 0..1400 { + let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); + for (x, y) in want[..window] + .iter() + .step_by(2) + .zip(got[lag * 2..].iter().step_by(2)) + { + num += f64::from(*x) * f64::from(*y); + da += f64::from(*x) * f64::from(*x); + db += f64::from(*y) * f64::from(*y); + } + let c = num / (da.sqrt() * db.sqrt()).max(1e-12); + if c > best { + (best, at) = (c, lag); + } + } + (best, at) + } + + fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec { + let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); + let mut pcm = Vec::new(); + for packet in packets { + pcm.extend( + decoder + .decode_packet(&packet.bytes) + .expect("a valid packet"), + ); + } + pcm + } + + /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and + /// why [`opus_fidelity`] exists at all -- all three measured here against + /// `ruopus`, the decoder this project reads every Opus file back with, and + /// which matches ffmpeg's libopus decode of a libopus file to correlation + /// 1.00000 on this very signal. + /// + /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26` + /// writes packets that only its own decoder reads back, and pinning that + /// here is what makes a version bump that fixes it *fail* -- which is the + /// signal to raise the cap rather than a reason to widen it quietly. + #[test] + fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() { + let pcm = two_tones(3); + for kbps in [96, OPUS_MAX_KBPS] { + let (packets, pre_skip) = encode_opus(&pcm, kbps) + .expect("the encoder opens") + .expect("and inside the band it passes its own round trip"); + assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); + assert_eq!( + packets.len(), + pcm.len().div_ceil(OPUS_FRAME * 2) + 2, + "one packet per 20 ms frame, plus the warm-up and the flush" + ); + let decoded = ruopus_decode(&packets); + let (c, lag) = align(&pcm, &decoded); + // From the first audible sample, head included -- and the head is + // why this is 0.98 and not the 0.999 below: the encoder's first + // audible 20 ms still comes out about 6 dB down whatever is fed in + // ahead of it (a second warm-up frame changes the numbers here in + // no decimal place), so that ramp is a property of `opus-rs 0.1.26` + // and is stated rather than hidden behind a loose threshold. + assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}"); + let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]); + assert!( + settled >= 0.999, + "{kbps} kbps past the first frame: correlation {settled:.4}" + ); + // The whole point of the number in the header: drop exactly that + // many samples and the sound starts where the timeline says. A lag + // that is not it is a file that plays late or eats its own head. + assert_eq!( + lag, + usize::from(pre_skip), + "{kbps} kbps: the declared pre-skip is not where the sound starts" + ); + // ...and the tail is all there: the flush frame pushed the last + // samples out, so what is left after the pre-skip covers the input. + assert!( + decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(), + "{kbps} kbps: the track ends {} samples short of the timeline", + (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2 + ); + // The gate the export runs before it writes anything, on a track + // that deserves to pass it. + let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip)); + assert!( + fidelity >= OPUS_MIN_FIDELITY, + "{kbps} kbps scored {fidelity:.4} on its own round trip" + ); + } + + // Above the band, straight at the crate, since `encode_opus` clamps: the + // packets come back as noise, and the gate says so. This is the check + // that the guard actually catches the failure it is built for -- and the + // one that fails, loudly, the day `opus-rs` fixes it. + let mut encoder = + opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap(); + encoder.bitrate_bps = 256_000; + encoder.complexity = 10; + let mut out = vec![0u8; 1500]; + let packets: Vec = pcm + .chunks_exact(OPUS_FRAME * 2) + .map(|block| { + let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap(); + crate::AacPacket { + bytes: out[..len].to_vec(), + samples: OPUS_FRAME as u32, + } + }) + .collect(); + let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP)); + assert!( + fidelity < OPUS_MIN_FIDELITY, + "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \ + back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half" + ); + } + /// The one rule that keeps a picture from being converted twice: a frame the /// tone map has already brought to BT.709 is never handed the 2020 matrix as /// well, on either canvas -- and everything else about the remap is diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index b9c0f82..7f1f563 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -65,6 +65,13 @@ pub struct AudioParams { pub freq_index: u8, pub chan_conf: u8, pub sample_rate: u32, + /// Set where the packets are **Opus** and not AAC, to the track's pre-skip + /// in samples at 48 kHz ([`crate::export`] writes those only for a Matroska + /// file). It is the whole difference between the two tracks a writer here + /// can declare: `A_OPUS` with an `OpusHead` in `CodecPrivate` + /// ([`opus_track_entry`]) against `A_AAC` with an `AudioSpecificConfig` + /// ([`aac_track_entry`]). `None` is AAC, which is every mp4 and every copy. + pub opus_pre_skip: Option, } /// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores @@ -262,6 +269,14 @@ impl Mp4Muxer { }), })?; if let Some(audio) = audio { + // The one thing this writer must never do quietly: an `mp4a` sample + // entry declares AAC, so Opus packets in it would be a file that + // says one codec and holds another. `export` never asks -- Opus is + // written for Matroska alone -- and this is the backstop that keeps + // that true if a format is ever added on the other side. + if audio.opus_pre_skip.is_some() { + return Err("an Opus track in an mp4: this writer declares `mp4a` only".into()); + } let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; // The index's own rate, not `audio.sample_rate`: this is the clock // an `stts` counts in and the `esds` states the index, so the two @@ -729,6 +744,7 @@ const AUDIO: u32 = 0xE1; const SAMPLING_FREQUENCY: u32 = 0xB5; const CHANNELS: u32 = 0x9F; const CODEC_DELAY: u32 = 0x56AA; +const SEEK_PRE_ROLL: u32 = 0x56BB; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; @@ -1086,7 +1102,11 @@ impl MkvMuxer { let mut tracks = Vec::new(); elem(&mut tracks, TRACK_ENTRY, &entry); if let Some((audio, _)) = &audio { - elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); + let entry = match audio.opus_pre_skip { + Some(pre_skip) => opus_track_entry(audio, pre_skip)?, + None => aac_track_entry(audio)?, + }; + elem(&mut tracks, TRACK_ENTRY, &entry); } // Declared even where the audio track is not: the picture is always 1 // and the sound always 2, so the text starts at 3 whether or not there @@ -1378,6 +1398,67 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result> { Ok(entry) } +/// The same track when the sound is Opus: `A_OPUS`, whose `CodecPrivate` is the +/// 19-byte `OpusHead` identification header of RFC 7845 §5.1 -- the very bytes +/// an Ogg Opus file opens with, which is why one writer serves both containers +/// and why this project's own reader configures itself from it unchanged +/// (`audio::opus_pre_skip` and `audio::opus_layout` parse exactly this). +/// +/// Mapping family 0: mono or stereo, no channel-mapping table, which is the only +/// shape [`crate::export::encode_opus`] writes. The rate field is what the +/// *input* was, not what the stream is coded at -- every Opus decoder runs at +/// 48 kHz whatever it says -- and the output gain is 0 because the mix is +/// already at the level the timeline asked for. +/// +/// Two elements no AAC track needs, and both are the difference between a file +/// that plays in sync and one that does not: +/// * `CodecDelay`, the pre-skip in nanoseconds. Matroska times an Opus block for +/// the *audible* stream while the decoder hands back the pre-skip in front of +/// it, so a reader that ignores this starts 2.5 ms early -- measured the other +/// way round on a real film remux (`audio::Track::samples_at`). +/// * `SeekPreRoll`, fixed at 80 ms for Opus by the Matroska spec: how much has +/// to be decoded and thrown away before a seek target for the decoder to be +/// warm. It is a constant of the codec, not of the file. +fn opus_track_entry(audio: &AudioParams, pre_skip: u16) -> crate::Result> { + let rate = audio.sample_rate; + if rate == 0 || !(1..=2).contains(&audio.chan_conf) { + return Err(format!( + "an Opus track at {rate} Hz with {} channels", + audio.chan_conf + ) + .into()); + } + let mut head = Vec::with_capacity(19); + head.extend_from_slice(b"OpusHead"); + head.push(1); // version + head.push(audio.chan_conf); + head.extend_from_slice(&pre_skip.to_le_bytes()); + head.extend_from_slice(&rate.to_le_bytes()); + head.extend_from_slice(&0i16.to_le_bytes()); // output gain + head.push(0); // mapping family + + let mut entry = Vec::new(); + uint(&mut entry, TRACK_NUMBER, 2); + uint(&mut entry, TRACK_UID, 2); + uint(&mut entry, TRACK_TYPE, 2); // audio + uint(&mut entry, FLAG_LACING, 0); + elem(&mut entry, CODEC_ID, b"A_OPUS"); + elem(&mut entry, CODEC_PRIVATE, &head); + uint( + &mut entry, + CODEC_DELAY, + u64::from(pre_skip) * 1_000_000_000 / u64::from(rate), + ); + uint(&mut entry, SEEK_PRE_ROLL, 80_000_000); + let mut audio_elem = Vec::new(); + put_id(&mut audio_elem, SAMPLING_FREQUENCY); + put_size(&mut audio_elem, 8); + audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes()); + uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf)); + elem(&mut entry, AUDIO, &audio_elem); + Ok(entry) +} + /// Which track the *first* subtitle block names, the picture's 1 and the sound's /// 2 being fixed: a file with no audio track still writes its first text track /// on 3, so nothing has to count the tracks before it to read a block. Each @@ -1898,6 +1979,7 @@ mod tests { freq_index: 4, // 44100 chan_conf: 2, sample_rate: 44_100, + opus_pre_skip: None, }), ) .unwrap(); @@ -2042,6 +2124,7 @@ mod tests { freq_index: 3, // 48000 chan_conf: 2, sample_rate: 48_000, + opus_pre_skip: None, }, packets, )), @@ -2113,6 +2196,7 @@ mod tests { freq_index: 3, chan_conf: 2, sample_rate: 48_000, + opus_pre_skip: None, }), ) .unwrap(); diff --git a/crates/engine/tests/opus_export.rs b/crates/engine/tests/opus_export.rs new file mode 100644 index 0000000..fda8cfc --- /dev/null +++ b/crates/engine/tests/opus_export.rs @@ -0,0 +1,401 @@ +//! Opus on the way *out*: an edited Opus source leaves a Matroska export as +//! Opus instead of being turned into AAC, and comes back in through this +//! project's own door -- symphonia's mkv reader for the container, `ruopus` for +//! the packets, which is the pair a film already plays through. +//! +//! Three claims, and each is measured rather than asserted from the code: +//! +//! * the file really carries an `A_OPUS` track with an `OpusHead` in its +//! `CodecPrivate`, and what comes back out of it correlates with the mix that +//! went in -- sample-aligned, so the pre-skip in that header is the encoder's +//! real lookahead and not a number somebody hoped for; +//! * a timeline nobody has touched still *copies* its AAC packets rather than +//! taking the new encoder: Opus is what an edit costs, never what a passthrough +//! costs; +//! * and the envelope itself -- 48 kHz, stereo, at most +//! `OPUS_MAX_KBPS` -- is a measurement of `opus-rs 0.1.26` and is pinned here, +//! so the day the crate is bumped past its high-rate bug this suite says so. +//! +//! Nothing here needs a GPU: the picture is 320x180 and HEVC's intra encoder is +//! software by construction, so the whole file runs anywhere. Add +//! `EDITH_OPUS_FILM=` to run the film case too +//! -- it is skipped without it, since no film lives in this repo. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::{LaneKind, Source, Speed}; +use engine::scale::FitPolicy; +use engine::scratch::Scratch; +use engine::{AudioSession, Clip, ExportHandle, Project}; + +/// The picture: 320x180 at 24 fps, 30 s (`scripts/gen_fixtures.sh`). Its own +/// sound is mono Opus and is deliberately left off the audio lane -- see +/// [`a_mono_mix_keeps_the_aac_path`]. +const VIDEO: &str = "test_seek_chirp.mkv"; +/// The sound: 5.1 Opus, 440 Hz in FL and 880 Hz in BR, folded to stereo on the +/// way to the timeline -- so the mix this export encodes *is* an Opus source's, +/// at the only rate Opus has. +const OPUS: &str = "test_opus_51.mka"; +/// One Opus frame, in samples per channel: what the tail of an export may be +/// padded by. +const OPUS_FRAME_SAMPLES: usize = 960; +/// The AAC source whose packets a copy must still win with. +const AAC: &str = "test_av.mp4"; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str) -> Scratch { + Scratch::file(&format!("ve_opus_{name}"), "mkv") +} + +fn pin_software() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + handle.result().expect("a finished export has an outcome") +} + +/// One second of picture with one second of `sound` under it, cut from +/// `sound_in` seconds into that file: an edit, so nothing here can be a copy. +fn project(video: &Path, sound: &Path, sound_in: u32) -> Project { + let clip = |source, in_frame, out_frame| Clip { + start: 0, + in_frame, + out_frame, + source, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + // The sound is source **0** on purpose: the timeline takes its rate and its + // width from the first source that has any, so a project whose first source + // is a mono-track video file is a mono timeline whatever plays on its audio + // lane -- which is the engine's rule, not this test's, and the one that + // decides whether Opus is reachable at all. + Project::from_parts( + vec![Source::new(sound, 0), Source::new(video, 0)], + vec![ + (LaneKind::Video, vec![clip(1, 0, 24)]), + ( + LaneKind::Audio, + vec![clip(0, sound_in * 24, sound_in * 24 + 24)], + ), + ], + Vec::new(), + Vec::new(), + ) + .expect("a picture lane and an audio lane") +} + +fn export(name: &str, project: Project, video: &Path) -> Scratch { + pin_software(); + let out = out_path(name); + let (meta, _) = engine::demux::Demuxer::open(video).expect("probe the picture"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Hevc, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(600)).expect("the export finishes"); + out +} + +/// Interleaved samples of a written file through the engine's own reader: the +/// door an import comes in through, and for an Opus track that is symphonia's +/// mkv reader handing `CodecPrivate` and blocks to `ruopus`. +fn decode(path: &Path) -> (engine::AudioMeta, Vec) { + let (meta, chunks) = AudioSession::open(path) + .expect("reopen the export") + .expect("the export has audio"); + let mut samples = Vec::new(); + for chunk in chunks { + samples.extend(chunk.samples); + } + (meta, samples) +} + +/// The best normalised correlation of `got` against `want` over the first +/// `lags` samples of offset, and the offset that reached it: a lossy codec +/// changes the samples, so what says "this is the same sound in the same place" +/// is the shape, and where the shape sits. +fn align(want: &[f32], got: &[f32], lags: usize) -> (f64, usize) { + let window = 12_000.min(want.len()).min(got.len().saturating_sub(lags)); + assert!(window > 1000, "not enough sound to correlate"); + let (mut best, mut at) = (-2.0, 0); + for lag in 0..lags { + let c = corr(&want[..window], &got[lag..lag + window]); + if c > best { + best = c; + at = lag; + } + } + (best, at) +} + +fn corr(a: &[f32], b: &[f32]) -> f64 { + let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); + for (x, y) in a.iter().zip(b) { + num += f64::from(*x) * f64::from(*y); + da += f64::from(*x) * f64::from(*x); + db += f64::from(*y) * f64::from(*y); + } + num / (da.sqrt() * db.sqrt()).max(1e-12) +} + +/// One channel of an interleaved buffer. +fn chan(samples: &[f32], channels: usize, which: usize) -> Vec { + samples + .iter() + .skip(which) + .step_by(channels) + .copied() + .collect() +} + +/// The claim: a cut of an Opus source, exported as a Matroska file, carries an +/// Opus track -- and that track is this project's own mix, in the right place. +#[test] +fn an_edited_opus_source_leaves_a_matroska_export_as_opus() { + let out = export( + "cut", + project(&asset(VIDEO), &asset(OPUS), 1), + &asset(VIDEO), + ); + + // The container, before any decoder: `A_OPUS` with an `OpusHead` in its + // `CodecPrivate`, and no AAC track anywhere near it. + let bytes = std::fs::read(&*out).expect("read the export back"); + let head = find(&bytes, b"OpusHead").expect("an OpusHead in the CodecPrivate"); + assert!(find(&bytes, b"A_OPUS").is_some(), "the track says A_OPUS"); + assert!(find(&bytes, b"A_AAC").is_none(), "and nothing says A_AAC"); + assert_eq!(bytes[head + 9], 2, "OpusHead: stereo"); + // The pre-skip: the encoder's lookahead plus the warm-up frame it throws + // away, which is what `export::tests` measures the sound starting at. + assert_eq!( + u16::from_le_bytes([bytes[head + 10], bytes[head + 11]]), + 1080, + "OpusHead: pre-skip" + ); + assert_eq!( + u32::from_le_bytes(bytes[head + 12..head + 16].try_into().unwrap()), + 48_000, + "OpusHead: 48 kHz" + ); + assert_eq!(bytes[head + 18], 0, "OpusHead: mapping family 0"); + + // ...and what a decoder makes of it, against the very second of the source + // the timeline cut out. The reader drops the pre-skip off the front, so a + // correct header lands the sound at zero: any leftover offset here is + // exactly the codec delay this file failed to declare. + let (meta, got) = decode(&out); + assert_eq!(meta.sample_rate, 48_000, "Opus reads back at 48 kHz"); + assert_eq!(meta.channels, 2); + let (_, want) = { + let (m, chunks) = AudioSession::open_segments(asset(OPUS), &[(1.0, 2.0)]) + .expect("open the source") + .expect("the source has sound"); + let mut s = Vec::new(); + for chunk in chunks { + s.extend(chunk.samples); + } + (m, s) + }; + // The fixture's two channels are *pure* sines, so a lag search on them is + // ambiguous by whole periods (440 Hz is 109.09 samples) and cannot be the + // alignment check -- that one is unambiguous in `export::tests`, on a signal + // with no period, and lands on the declared pre-skip exactly. What is + // checked here is the pair a periodic signal *can* answer: the sound is the + // source's, and it is in the right place to within a sample at lag zero. + assert!( + got.len() >= want.len() - 2 && got.len() <= want.len() + OPUS_FRAME_SAMPLES * 2, + "the track is {} samples where the timeline is {}", + got.len(), + want.len() + ); + for (which, name) in [(0, "left"), (1, "right")] { + let (w, g) = (chan(&want, 2, which), chan(&got, 2, which)); + let span = w.len().min(g.len()); + let aligned = corr(&w[..span], &g[..span]); + assert!( + aligned >= 0.98, + "{name}: correlation {aligned:.4} against the source at lag zero -- \ + the export is either not this sound or not in this place" + ); + // Past the first frame, where the encoder's cold start is behind it: + // 0.997 left and 0.993 right, measured, against 0.9948/0.9825 with the + // head in. That gap *is* the ramp the pre-skip cannot cover, and it is + // asserted from both sides so neither can drift unnoticed. + let settled = corr(&w[OPUS_FRAME_SAMPLES..span], &g[OPUS_FRAME_SAMPLES..span]); + assert!( + settled >= 0.99, + "{name}: correlation {settled:.4} past the first frame" + ); + // ...and the head specifically, which is what the pre-skip and the + // warm-up frame are for. Measured at 128 kbps: 0.990 left, 0.953 right, + // where the same export with no warm-up frame scored 0.9788 left and a + // mis-declared pre-skip would score far less than either. The gap to the + // 0.99 above is one frame of cold start -- `opus-rs 0.1.26` opens about + // 6 dB down whatever is fed in ahead of it (two warm-up frames change + // this in no decimal place) -- so this threshold is that ramp stated + // rather than a shrug. + let head = corr(&w[..12_000], &g[..12_000]); + assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}"); + } + + // A second implementation on the same bytes, where the box has one: ffmpeg + // decoding what we wrote is the check that the file is Opus by the format's + // rules and not merely by ours -- pre-skip included, since ffmpeg drops it + // off the front exactly as this project's reader does. + if let Some(pcm) = ffmpeg_decode(&out) { + let (w, g) = (chan(&want, 2, 0), chan(&pcm, 2, 0)); + let span = w.len().min(g.len()); + assert!( + span + 4 >= w.len(), + "ffmpeg read {span} samples of a {} sample track", + w.len() + ); + let c = corr(&w[..span], &g[..span]); + assert!( + c >= 0.99, + "ffmpeg's decode correlates {c:.4} with the source" + ); + } +} + +/// The other half of the seat: an untouched AAC timeline still *copies*, even +/// into the container that would otherwise encode Opus. A copy is bit-exact and +/// an encode is a generation of loss, so the new encoder must never be reached +/// where the old passthrough still applies. +#[test] +fn an_untouched_timeline_still_copies_its_aac_into_an_mkv() { + let source = asset(AAC); + let out = export("copy", project(&source, &source, 0), &source); + let bytes = std::fs::read(&*out).expect("read the export back"); + assert!(find(&bytes, b"A_AAC").is_some(), "the copy stays AAC"); + assert!( + find(&bytes, b"A_OPUS").is_none(), + "an untouched lane took the Opus encoder instead of copying" + ); +} + +/// A mono mix keeps AAC, and that is a *measurement* and not a preference: +/// `opus-rs 0.1.26` mis-encodes mono at rates it is asked for here (see the +/// envelope test in `export.rs`), so the file that would play back wrong is +/// never written. `test_seek_chirp.mkv` carries mono Opus, which is exactly the +/// source that would tempt this path. +#[test] +fn a_mono_mix_keeps_the_aac_path() { + let source = asset(VIDEO); + let out = export("mono", project(&source, &source, 1), &source); + let bytes = std::fs::read(&*out).expect("read the export back"); + assert!( + find(&bytes, b"A_AAC").is_some(), + "a mono mix is written as AAC" + ); + assert!(find(&bytes, b"A_OPUS").is_none()); +} + +/// A real library, not a fixture: a real Opus film, cut, exported, read back. +/// The path comes from the environment because no film's name belongs in this +/// repository; without it the test says so and passes. +#[test] +fn a_real_library_opus_film_exports_as_opus() { + let Some(film) = std::env::var_os("EDITH_OPUS_FILM").map(PathBuf::from) else { + eprintln!("EDITH_OPUS_FILM unset: the film case is skipped"); + return; + }; + // The fixture's picture under the film's *sound*: what is on trial here is + // an Opus track off a real library -- 5.1, folded to stereo on the way in + // -- and decoding a 1080p AV1 film would drag a VA-API plugin into a test + // about audio. + let out = export("film", project(&asset(VIDEO), &film, 600), &asset(VIDEO)); + let bytes = std::fs::read(&*out).expect("read the export back"); + assert!( + find(&bytes, b"A_OPUS").is_some(), + "the film's sound stays Opus" + ); + let (meta, got) = decode(&out); + assert_eq!((meta.sample_rate, meta.channels), (48_000, 2)); + let (_, want) = { + let (_, chunks) = AudioSession::open_segments(&film, &[(600.0, 601.0)]) + .expect("open the film") + .expect("the film has sound"); + let mut s = Vec::new(); + for chunk in chunks { + s.extend(chunk.samples); + } + ((), s) + }; + // Film sound is broadband and has no period, so unlike the tone fixture the + // lag here is unambiguous: the peak is where the sound is. + let (c, lag) = align(&chan(&want, 2, 0), &chan(&got, 2, 0), 400); + // What ffprobe makes of the same file, printed rather than parsed -- run + // with `--nocapture` and this is the line that says `Audio: opus`. + if let Ok(probe) = Command::new("ffprobe") + .args(["-hide_banner"]) + .arg(&*out) + .output() + { + eprint!("{}", String::from_utf8_lossy(&probe.stderr)); + } + eprintln!("the film's span: correlation {c:.4} at lag {lag}"); + assert!(c >= 0.99, "the film's span correlates {c:.4} at lag {lag}"); + assert!(lag <= 2, "the film's span starts {lag} samples late"); +} + +/// Where `needle` first sits in `hay`. +fn find(hay: &[u8], needle: &[u8]) -> Option { + hay.windows(needle.len()).position(|w| w == needle) +} + +/// ffmpeg's own decode of a file, interleaved f32 at 48 kHz stereo. `None` +/// where the box has no ffmpeg -- the test is about the file, not about this +/// machine's packages. +fn ffmpeg_decode(path: &Path) -> Option> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-map", "0:a:0", "-f", "f32le", "-ar", "48000", "-ac", "2", "-", + ]) + .output() + .ok()?; + assert!( + out.status.success(), + "ffmpeg refused the exported Opus track: {}", + String::from_utf8_lossy(&out.stderr) + ); + Some( + out.stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(), + ) +}