forge
Explore
Log in

Don't you dare go Hollow

An edited Opus source leaves an mkv as Opus

Browse files at this commit

76ede8e1832bd2200d15e946dcb606c3cdb2dd80Ahmet Kaan GümüşParent: ada6ac5
  • feat
    • an edited Opus source leaves an mkv as Opus
Show full message
🔊 feat(export): an edited Opus source leaves an mkv as Opus

Opus could be read here since `ruopus` landed and could not be written at
all, so every cut of an Opus film came out as AAC in a Matroska file: a
codec downgrade nobody asked for, paid on every edit. `opus-rs 0.1.26` is
the encoder half -- a pure-Rust port of libopus 1.6, BSD-3, no `build.rs`,
not one `.c` in the crate and no dependencies at all (checked, not read off
the README) -- and a Matroska export now writes `A_OPUS` with an `OpusHead`
in its `CodecPrivate`, `CodecDelay` and the codec's fixed 80 ms
`SeekPreRoll` beside it. An mp4 still says AAC and the mp4 writer now
refuses an Opus track by name rather than declaring `mp4a` over it.

Only where an *encode* was going to happen anyway. An untouched timeline
still copies its packets, bit for bit, into the same container: Opus is what
an edit costs, never what a passthrough costs.

The envelope is measured and it is narrow, which is the whole story of this
crate. On three one-second spans of a 5.1 Opus film, encoded here and
decoded with `ruopus` -- not the suspect, it reads ffmpeg's libopus at 256
kbps back at correlation 1.00000 -- the encoder is usable to 128 kbps
(0.937/0.989/0.994) and ruined by 136 (0.452/0.697/0.951), against libopus
at 0.997/0.998 on the same material. Pure-tone fixtures put that cliff at
165 kbps, so its edge moves with the content and no constant is safe on its
own: the cap is 128 kbps *and* every track is decoded again and correlated
with the mix before it is written. Below 0.95 the export writes AAC instead,
and the encoder line the export publishes says AAC, so the fallback is
visible rather than silent. Mono keeps AAC outright -- this encoder mis-codes
it at every rate asked for here -- and so does any timeline that is not
48 kHz, since Opus has one rate and resampling a whole timeline to reach it
is a bigger change to the sound than the codec is.

Two delays, both measured rather than hoped for. The pre-skip is 1080
samples: the encoder's 2.5 ms lookahead plus one warm-up frame, because a
cold first frame comes out ramped and out of phase (the head of the fixture
went 0.9788 -> 0.988 correlated once it was fed its own first 20 ms first),
and one silent frame is pushed in at the end so the last 2.5 ms leave the
encoder instead of ending the track short under a picture that is not.
ffmpeg's decode of the file agrees with this project's own reader sample for
sample, which is what says the header describes the stream.

`tests/opus_export.rs` exports a cut and reads it back through symphonia's
mkv reader and `ruopus` -- 0.9948 left and 0.9825 right against the source,
0.997/0.993 past the first frame -- proves the AAC copy still wins where it
applies and that a mono mix takes the AAC path, and, with `EDITH_OPUS_FILM`
pointing at a real-library Opus mkv, cuts a span out of the film itself:
correlation 0.9914 at a lag of one sample. The unit test in `export.rs` pins
the 256 kbps failure, so the day the crate fixes it this suite fails and the
cap can be raised.
Cargo.lockmodified+7 -0
@@ -1642,6 +1642,7 @@ dependencies = [
1642 "libloading",1642 "libloading",
1643 "miniz_oxide",1643 "miniz_oxide",
1644 "mp4",1644 "mp4",
1645+ "opus-rs",
1645 "oxideav-ac3",1646 "oxideav-ac3",
1646 "oxideav-ass",1647 "oxideav-ass",
1647 "oxideav-core",1648 "oxideav-core",
@@ -3934,6 +3935,12 @@ version = "0.2.0"
3934 source = "registry+https://github.com/rust-lang/crates.io-index"3935 source = "registry+https://github.com/rust-lang/crates.io-index"
3935 checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"3936 checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
3936 3937
3938+[[package]]
3939+name = "opus-rs"
3940+version = "0.1.26"
3941+source = "registry+https://github.com/rust-lang/crates.io-index"
3942+checksum = "b7f1ce2826529746cac003d7338e9c0f47cdd2979ba769c61cc26fdebc402f4c"
3943+
3937 [[package]]3944 [[package]]
3938 name = "ordered-stream"3945 name = "ordered-stream"
3939 version = "0.2.0"3946 version = "0.2.0"
crates/engine/Cargo.tomlmodified+17 -0
@@ -98,6 +98,23 @@ rusty_vorbis = "0.1.1"
98 # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`98 # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`
99 # below, because a decoder is a bit-exactness dependency.99 # below, because a decoder is a bit-exactness dependency.
100 ruopus = { version = "=0.1.2", default-features = false, features = ["std"] }100 ruopus = { version = "=0.1.2", default-features = false, features = ["std"] }
101+# The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus
102+# 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not
103+# taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h`
104+# or `.S` file in the crate). It is what lets an edited Opus source leave in a
105+# Matroska file as Opus instead of being downgraded to AAC on the way out.
106+#
107+# Used inside a measured envelope, and that envelope is the whole reason this
108+# line is not simply "the encoder": 48 kHz **stereo** at **at most**
109+# [`crate::export::OPUS_MAX_KBPS`]. Above roughly 165 kbps stereo this encoder
110+# writes packets that only its *own* decoder reads back -- `ruopus` decodes them
111+# as noise (correlation 0.06 at 256 kbps against the source, 0.9999 at 160), and
112+# `ruopus` is not the suspect: it decodes ffmpeg's own libopus at 256 kbps to
113+# correlation 1.00000 on the same signal. Mono is worse and at every rate, which
114+# is why a mono mix keeps the AAC path. Both measured in
115+# `tests/opus_export.rs`, which fails the day the crate is unpinned onto a
116+# version that has fixed it -- that is the upgrade signal.
117+opus-rs = "=0.1.26"
101 # The Ogg container, and the only new *name* here that is not a new crate tree:118 # The Ogg container, and the only new *name* here that is not a new crate tree:
102 # its one dependency is `oxideav-core`, which the AC-3 decoder above already119 # its one dependency is `oxideav-core`, which the AC-3 decoder above already
103 # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the120 # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the
crates/engine/src/export.rsmodified+372 -5
@@ -216,6 +216,14 @@ impl Format {
216 matches!(self, Self::Hevc | Self::HevcMp4)216 matches!(self, Self::Hevc | Self::HevcMp4)
217 }217 }
218 218
219+ /// Whether the file is a Matroska one. Only that container carries this
220+ /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but
221+ /// the crate that writes the mp4s here has no sample entry for it, so the
222+ /// mp4 formats stay on AAC and say so.
223+ fn is_mkv(self) -> bool {
224+ matches!(self, Self::Av1 | Self::Hevc)
225+ }
226+
219 /// What the format is called where a refusal names it.227 /// What the format is called where a refusal names it.
220 pub fn name(self) -> &'static str {228 pub fn name(self) -> &'static str {
221 match self {229 match self {
@@ -537,6 +545,20 @@ fn audio_label(
537 Format::Ogg => "Vorbis · SW (rusty_vorbis)",545 Format::Ogg => "Vorbis · SW (rusty_vorbis)",
538 _ => match copied.unwrap_or(!forces_encode(project)) {546 _ => match copied.unwrap_or(!forces_encode(project)) {
539 true => "AAC copy",547 true => "AAC copy",
548+ // A Matroska file gets Opus where the mix allows it -- 48 kHz and
549+ // stereo, which is every Opus source and most of everything else --
550+ // and AAC where it does not ([`encode_audio`]). Which of the two it
551+ // will be cannot be known here: both answers need a source opened,
552+ // and this function may be asked per repaint. So the card names the
553+ // codec it will nearly always be, as a prediction like the copy above
554+ // it, and the line the export publishes while it runs is the measured
555+ // one ([`run`]) -- it says AAC when the fallback took it, so the
556+ // fallback is visible rather than silent.
557+ //
558+ // It is one line and 76 characters wide (`summary_head` in the app
559+ // has the test), which is why the condition is in this comment
560+ // instead of in the string.
561+ false if format.is_mkv() => "Opus · SW encode (opus-rs)",
540 false => "AAC · SW encode (rusty_aac)",562 false => "AAC · SW encode (rusty_aac)",
541 },563 },
542 }564 }
@@ -800,6 +822,11 @@ pub(crate) struct ExportAudio {
800 pub packets: Vec<crate::AacPacket>,822 pub packets: Vec<crate::AacPacket>,
801 /// Whether those packets are the source's, untouched.823 /// Whether those packets are the source's, untouched.
802 pub copied: bool,824 pub copied: bool,
825+ /// The track's pre-skip in samples where those packets are **Opus** and not
826+ /// AAC ([`encode_opus`]), which is what the Matroska track entry states in
827+ /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is
828+ /// every copy and every mp4.
829+ pub opus_pre_skip: Option<u16>,
803 }830 }
804 831
805 /// The timeline's audio track for a file that carries picture: copied packet for832 /// The timeline's audio track for a file that carries picture: copied packet for
@@ -820,6 +847,7 @@ fn copy_audio(
820 project: &Project,847 project: &Project,
821 meta: &VideoMeta,848 meta: &VideoMeta,
822 kbps: u32,849 kbps: u32,
850+ mkv: bool,
823 ) -> crate::Result<Option<ExportAudio>> {851 ) -> crate::Result<Option<ExportAudio>> {
824 // The segments name their source, and the copy carries its packet-rounding852 // The segments name their source, and the copy carries its packet-rounding
825 // debt across a source join exactly as across a cut, so a timeline spanning853 // debt across a source join exactly as across a cut, so a timeline spanning
@@ -844,7 +872,7 @@ fn copy_audio(
844 // whole comment is about.872 // whole comment is about.
845 let lanes = project.audio_segments_from(0, meta.frame_rate);873 let lanes = project.audio_segments_from(0, meta.frame_rate);
846 let [segments] = &lanes[..] else {874 let [segments] = &lanes[..] else {
847- return encode_audio(project, meta, kbps);875+ return encode_audio(project, meta, kbps, mkv);
848 };876 };
849 // ...and the same list names *which* lane those clips sit on, which is the877 // ...and the same list names *which* lane those clips sit on, which is the
850 // only way to ask what has been done to them.878 // only way to ask what has been done to them.
@@ -882,7 +910,7 @@ fn copy_audio(
882 // such a lane would write it at unity and unlimited, silently.910 // such a lane would write it at unity and unlimited, silently.
883 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());911 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
884 if speeded || equalized(project) || mastered(project) {912 if speeded || equalized(project) || mastered(project) {
885- return encode_audio(project, meta, kbps);913+ return encode_audio(project, meta, kbps, mkv);
886 }914 }
887 // What is left is a copy the *sources* may still not be able to give: AAC915 // What is left is a copy the *sources* may still not be able to give: AAC
888 // inside a Matroska file (readable, but not out of a sample table this walks916 // inside a Matroska file (readable, but not out of a sample table this walks
@@ -897,8 +925,12 @@ fn copy_audio(
897 params,925 params,
898 packets,926 packets,
899 copied: true,927 copied: true,
928+ // A copy is the source's own AAC packets: there is no Opus copy
929+ // path here, since the packets an mkv source holds never reach this
930+ // (they are not in a sample table) and every one of them re-encodes.
931+ opus_pre_skip: None,
900 })),932 })),
901- Err(_) => encode_audio(project, meta, kbps),933+ Err(_) => encode_audio(project, meta, kbps, mkv),
902 }934 }
903 }935 }
904 936
@@ -1151,6 +1183,7 @@ fn encode_audio(
1151 project: &Project,1183 project: &Project,
1152 meta: &VideoMeta,1184 meta: &VideoMeta,
1153 kbps: u32,1185 kbps: u32,
1186+ mkv: bool,
1154 ) -> crate::Result<Option<ExportAudio>> {1187 ) -> crate::Result<Option<ExportAudio>> {
1155 let sources = project.audio_sources();1188 let sources = project.audio_sources();
1156 let segs = project.audio_segments_from(0, meta.frame_rate);1189 let segs = project.audio_segments_from(0, meta.frame_rate);
@@ -1189,6 +1222,34 @@ fn encode_audio(
1189 }1222 }
1190 samples.resize(total, 0.0);1223 samples.resize(total, 0.0);
1191 1224
1225+ // Opus where the container carries it and the mix is inside the envelope
1226+ // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,
1227+ // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves
1228+ // as Opus instead of being turned into AAC on the way out, which is the one
1229+ // generation of loss an all-Opus timeline used to pay for being cut.
1230+ //
1231+ // Everything else falls through to the AAC below and is unchanged by this:
1232+ // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own --
1233+ // there is no resampler on this path, and inventing one to reach 48 kHz
1234+ // would resample a whole timeline to satisfy a codec, which is a bigger
1235+ // change to the sound than the codec is.
1236+ if mkv
1237+ && audio.sample_rate == OPUS_RATE
1238+ && channels == 2
1239+ && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)?
1240+ {
1241+ return Ok(Some(ExportAudio {
1242+ params: crate::AacTrackParams {
1243+ freq_index,
1244+ chan_conf: 2,
1245+ sample_rate: OPUS_RATE,
1246+ },
1247+ packets,
1248+ copied: false,
1249+ opus_pre_skip: Some(pre_skip),
1250+ }));
1251+ }
1252+
1192 // The caller's rate, never the encoder's own 128 default -- see1253 // The caller's rate, never the encoder's own 128 default -- see
1193 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.1254 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.
1194 let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {1255 let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
@@ -1216,9 +1277,159 @@ fn encode_audio(
1216 },1277 },
1217 packets,1278 packets,
1218 copied: false,1279 copied: false,
1280+ opus_pre_skip: None,
1219 }))1281 }))
1220 }1282 }
1221 1283
1284+/// The one rate Opus codes at. The container may state another one in its
1285+/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a
1286+/// timeline at any other rate is not "encoded at its own rate" here -- it is
1287+/// resampled or it is not Opus, and [`encode_audio`] picks the second.
1288+pub(crate) const OPUS_RATE: u32 = 48_000;
1289+
1290+/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes:
1291+/// long enough that the per-packet overhead is nothing, short enough that a
1292+/// Matroska block timestamp in whole milliseconds is exact.
1293+const OPUS_FRAME: usize = 960;
1294+
1295+/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather
1296+/// than the four rates the Sound row offers: this encoder falls off a cliff at a
1297+/// rate that depends on the *content*, and above it a conformant decoder gets
1298+/// noise back. Measured on three one-second spans of a real 5.1 Opus film,
1299+/// encoded here and decoded with `ruopus` -- which is not the suspect, since it
1300+/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same
1301+/// material:
1302+///
1303+/// ```text
1304+/// kbps 120 128 136 144 152 160
1305+/// span A 0.945 0.937 0.452 0.206 0.223 0.163
1306+/// span B 0.986 0.989 0.697 0.153 0.114 0.149
1307+/// span C 0.999 0.994 0.951 0.335 0.266 0.326
1308+/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
1309+/// ```
1310+///
1311+/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone
1312+/// fixtures that first suggested a 165 kbps ceiling were simply easy material.
1313+/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.998
1314+/// there on the worst of those spans), so the cap costs nothing a listener has.
1315+/// It is still not *trusted*: every track is decoded again and measured before
1316+/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the
1317+/// material is not something a constant can be safe against on its own.
1318+///
1319+/// ponytail: the ceiling is this encoder's, not the format's. Upgrade path is a
1320+/// released `opus-rs` that survives its own high rates -- the unit test pins the
1321+/// failure, so it fails the day the bug is fixed and this can be raised.
1322+pub(crate) const OPUS_MAX_KBPS: u32 = 128;
1323+
1324+/// How well a track has to survive its own round trip to be written as Opus:
1325+/// the correlation between the mix and the decode of what was encoded from it.
1326+/// A good encoder scores 0.98-0.999 on this material (libopus, measured above);
1327+/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap
1328+/// with room on both sides, and what fails it is written as AAC -- the export's
1329+/// own encoder line then says AAC, so the fallback is visible rather than
1330+/// silent.
1331+const OPUS_MIN_FIDELITY: f64 = 0.95;
1332+
1333+/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always
1334+/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the
1335+/// warm-up frame [`encode_opus`] throws away. Measured by
1336+/// cross-correlating the decode against the source, not taken from the crate --
1337+/// it exposes no lookahead getter -- and asserted at both ends of the rate band
1338+/// in `tests/opus_export.rs`, which is what catches a version that changes it.
1339+const OPUS_PRE_SKIP: u16 = 120;
1340+
1341+/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
1342+/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller
1343+/// checks both, because outside that pair this encoder is not one this project
1344+/// is willing to write files with ([`OPUS_MAX_KBPS`]).
1345+///
1346+/// The tail frame is padded with silence rather than dropped: Opus codes whole
1347+/// frames and a track a few milliseconds short under a picture that is not is
1348+/// the drift every other path here is written to avoid. The pre-skip trims the
1349+/// front; the container's duration trims the back.
1350+fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
1351+ let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio)
1352+ .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?;
1353+ encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32;
1354+ encoder.complexity = 10;
1355+ let mut packets = Vec::new();
1356+ let mut frame = vec![0f32; OPUS_FRAME * 2];
1357+ // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
1358+ // that with room for the TOC and a padded frame, so `encode` never has to
1359+ // refuse for want of a buffer.
1360+ let mut out = vec![0u8; 1500];
1361+ // The head, coded **twice**. An encoder's very first frame has no history
1362+ // behind it and comes out ramped and out of phase -- measured on a 440 Hz
1363+ // fixture, the first 20 ms of the export correlated 0.09 with the source
1364+ // where every later window correlated 0.9997 -- and 20 ms of wrong sound at
1365+ // the head of a file is the kind of thing nobody hears in a test and
1366+ // everybody hears in the first frame of a cut. So the first frame is fed in
1367+ // once to warm the encoder, and thrown away again by the pre-skip: exactly
1368+ // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
1369+ let warm = samples.len().min(OPUS_FRAME * 2);
1370+ // ...and one silent frame after the sound, for the same delay seen from the
1371+ // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
1372+ // without a frame to push them out the last 2.5 ms of the timeline stay
1373+ // inside it and the track ends short under a picture that does not.
1374+ let blocks = std::iter::once(&samples[..warm])
1375+ .chain(samples.chunks(OPUS_FRAME * 2))
1376+ .chain(std::iter::once(&samples[..0]));
1377+ for block in blocks {
1378+ frame[..block.len()].copy_from_slice(block);
1379+ frame[block.len()..].fill(0.0);
1380+ let len = encoder
1381+ .encode(&frame, OPUS_FRAME, &mut out)
1382+ .map_err(|e| format!("Opus encode failed: {e}"))?;
1383+ packets.push(crate::AacPacket {
1384+ bytes: out[..len].to_vec(),
1385+ samples: OPUS_FRAME as u32,
1386+ });
1387+ }
1388+ // ...and now the part that is not optimism: what was just written is
1389+ // decoded again and measured against what went in, and a track that does
1390+ // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller
1391+ // falls through to AAC, which is exactly where it stood before this seat
1392+ // existed -- a worse codec is a fair trade for a track that is the sound.
1393+ //
1394+ // ponytail: this costs one Opus decode of the whole track (a minute of
1395+ // sound in a few hundred milliseconds, against a video encode that is
1396+ // minutes). Upgrade path is deleting it, the day this encoder can be
1397+ // trusted at the rate it is asked for.
1398+ let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
1399+ let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));
1400+ Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
1401+}
1402+
1403+/// The correlation between `samples` and the decode of `packets` with the first
1404+/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
1405+/// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
1406+/// only three running sums -- because the mix behind it is already the biggest
1407+/// thing in an export ([`encode_audio`]'s ponytail).
1408+///
1409+/// A packet the decoder refuses is 0.0 and no argument: a track this project
1410+/// cannot read is exactly what this is here to catch.
1411+fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {
1412+ let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
1413+ let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1414+ let mut drop = pre_skip * 2;
1415+ let mut at = 0;
1416+ for packet in packets {
1417+ let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
1418+ return 0.0;
1419+ };
1420+ let pcm = &pcm[drop.min(pcm.len())..];
1421+ drop = drop.saturating_sub(packet.samples as usize * 2);
1422+ for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
1423+ let (x, y) = (f64::from(*want), f64::from(*got));
1424+ num += x * y;
1425+ da += x * x;
1426+ db += y * y;
1427+ at += 1;
1428+ }
1429+ }
1430+ num / (da.sqrt() * db.sqrt()).max(1e-12)
1431+}
1432+
1222 fn run(1433 fn run(
1223 project: &Project,1434 project: &Project,
1224 meta: &VideoMeta,1435 meta: &VideoMeta,
@@ -1233,15 +1444,27 @@ fn run(
1233 // muxer wants the packets themselves that early too, because it interleaves1444 // muxer wants the packets themselves that early too, because it interleaves
1234 // them into the clusters as it writes. Every video format gets the same1445 // them into the clusters as it writes. Every video format gets the same
1235 // track: none of them is picture-only any more.1446 // track: none of them is picture-only any more.
1236- let audio = copy_audio(project, meta, audio_kbps_of(settings))?;1447+ let audio = copy_audio(
1448+ project,
1449+ meta,
1450+ audio_kbps_of(settings),
1451+ settings.format.is_mkv(),
1452+ )?;
1237 let audio_params = audio.as_ref().map(|track| AudioParams {1453 let audio_params = audio.as_ref().map(|track| AudioParams {
1238 freq_index: track.params.freq_index,1454 freq_index: track.params.freq_index,
1239 chan_conf: track.params.chan_conf,1455 chan_conf: track.params.chan_conf,
1240 sample_rate: track.params.sample_rate,1456 sample_rate: track.params.sample_rate,
1457+ opus_pre_skip: track.opus_pre_skip,
1241 });1458 });
1242 // What the track *is*, kept before the packets are handed to a muxer: the1459 // What the track *is*, kept before the packets are handed to a muxer: the
1243 // encoder line names a copy or an encode and only `copy_audio` knows which.1460 // encoder line names a copy or an encode and only `copy_audio` knows which.
1244 let sound = audio.as_ref().map(|track| track.copied);1461 let sound = audio.as_ref().map(|track| track.copied);
1462+ // ...and *which* encoder, for the same line: the card predicts Opus from the
1463+ // format alone and cannot know the mix's rate or width ([`audio_label`]),
1464+ // while this is after the mix was opened, so it is the measured answer.
1465+ let opus = audio
1466+ .as_ref()
1467+ .is_some_and(|track| track.opus_pre_skip.is_some());
1245 // Taken by the Matroska muxer at creation; the mp4 one writes its track1468 // Taken by the Matroska muxer at creation; the mp4 one writes its track
1246 // after the picture, so for that path this is still `Some` at the end.1469 // after the picture, so for that path this is still `Some` at the end.
1247 let mut packets = audio.map(|track| track.packets);1470 let mut packets = audio.map(|track| track.packets);
@@ -1316,7 +1539,10 @@ fn run(
1316 *shared.encoders.lock().unwrap() = Some(format!(1539 *shared.encoders.lock().unwrap() = Some(format!(
1317 "{} · {}",1540 "{} · {}",
1318 encoder.label(),1541 encoder.label(),
1319- audio_label(project, settings.format, sound.is_some(), sound)1542+ match opus {
1543+ true => "Opus · SW encode (opus-rs)",
1544+ false => audio_label(project, settings.format, sound.is_some(), sound),
1545+ }
1320 ));1546 ));
1321 let mut muxer = None;1547 let mut muxer = None;
1322 let mut done = 0u32;1548 let mut done = 0u32;
@@ -2795,6 +3021,147 @@ impl SwDecoder {
2795 mod tests {3021 mod tests {
2796 use super::*;3022 use super::*;
2797 3023
3024+ /// Three seconds of two tones, one per channel, interleaved: enough shape
3025+ /// that a correlation says something and enough length that the encoder
3026+ /// settles into a mode.
3027+ fn two_tones(secs: usize) -> Vec<f32> {
3028+ (0..OPUS_RATE as usize * secs)
3029+ .flat_map(|i| {
3030+ let t = i as f32 / OPUS_RATE as f32;
3031+ let tau = std::f32::consts::TAU;
3032+ [
3033+ 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(),
3034+ 0.25 * (tau * 880.0 * t).sin(),
3035+ ]
3036+ })
3037+ .collect()
3038+ }
3039+
3040+ /// The best correlation of one channel of `got` against `want`, and the
3041+ /// offset it sat at.
3042+ fn align(want: &[f32], got: &[f32]) -> (f64, usize) {
3043+ let (mut best, mut at) = (-2.0, 0);
3044+ let window = OPUS_RATE as usize;
3045+ for lag in 0..1400 {
3046+ let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
3047+ for (x, y) in want[..window]
3048+ .iter()
3049+ .step_by(2)
3050+ .zip(got[lag * 2..].iter().step_by(2))
3051+ {
3052+ num += f64::from(*x) * f64::from(*y);
3053+ da += f64::from(*x) * f64::from(*x);
3054+ db += f64::from(*y) * f64::from(*y);
3055+ }
3056+ let c = num / (da.sqrt() * db.sqrt()).max(1e-12);
3057+ if c > best {
3058+ (best, at) = (c, lag);
3059+ }
3060+ }
3061+ (best, at)
3062+ }
3063+
3064+ fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
3065+ let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
3066+ let mut pcm = Vec::new();
3067+ for packet in packets {
3068+ pcm.extend(
3069+ decoder
3070+ .decode_packet(&packet.bytes)
3071+ .expect("a valid packet"),
3072+ );
3073+ }
3074+ pcm
3075+ }
3076+
3077+ /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
3078+ /// why [`opus_fidelity`] exists at all -- all three measured here against
3079+ /// `ruopus`, the decoder this project reads every Opus file back with, and
3080+ /// which matches ffmpeg's libopus decode of a libopus file to correlation
3081+ /// 1.00000 on this very signal.
3082+ ///
3083+ /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26`
3084+ /// writes packets that only its own decoder reads back, and pinning that
3085+ /// here is what makes a version bump that fixes it *fail* -- which is the
3086+ /// signal to raise the cap rather than a reason to widen it quietly.
3087+ #[test]
3088+ fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
3089+ let pcm = two_tones(3);
3090+ for kbps in [96, OPUS_MAX_KBPS] {
3091+ let (packets, pre_skip) = encode_opus(&pcm, kbps)
3092+ .expect("the encoder opens")
3093+ .expect("and inside the band it passes its own round trip");
3094+ assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
3095+ assert_eq!(
3096+ packets.len(),
3097+ pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
3098+ "one packet per 20 ms frame, plus the warm-up and the flush"
3099+ );
3100+ let decoded = ruopus_decode(&packets);
3101+ let (c, lag) = align(&pcm, &decoded);
3102+ // From the first audible sample, head included -- and the head is
3103+ // why this is 0.98 and not the 0.999 below: the encoder's first
3104+ // audible 20 ms still comes out about 6 dB down whatever is fed in
3105+ // ahead of it (a second warm-up frame changes the numbers here in
3106+ // no decimal place), so that ramp is a property of `opus-rs 0.1.26`
3107+ // and is stated rather than hidden behind a loose threshold.
3108+ assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
3109+ let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]);
3110+ assert!(
3111+ settled >= 0.999,
3112+ "{kbps} kbps past the first frame: correlation {settled:.4}"
3113+ );
3114+ // The whole point of the number in the header: drop exactly that
3115+ // many samples and the sound starts where the timeline says. A lag
3116+ // that is not it is a file that plays late or eats its own head.
3117+ assert_eq!(
3118+ lag,
3119+ usize::from(pre_skip),
3120+ "{kbps} kbps: the declared pre-skip is not where the sound starts"
3121+ );
3122+ // ...and the tail is all there: the flush frame pushed the last
3123+ // samples out, so what is left after the pre-skip covers the input.
3124+ assert!(
3125+ decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(),
3126+ "{kbps} kbps: the track ends {} samples short of the timeline",
3127+ (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2
3128+ );
3129+ // The gate the export runs before it writes anything, on a track
3130+ // that deserves to pass it.
3131+ let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip));
3132+ assert!(
3133+ fidelity >= OPUS_MIN_FIDELITY,
3134+ "{kbps} kbps scored {fidelity:.4} on its own round trip"
3135+ );
3136+ }
3137+
3138+ // Above the band, straight at the crate, since `encode_opus` clamps: the
3139+ // packets come back as noise, and the gate says so. This is the check
3140+ // that the guard actually catches the failure it is built for -- and the
3141+ // one that fails, loudly, the day `opus-rs` fixes it.
3142+ let mut encoder =
3143+ opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap();
3144+ encoder.bitrate_bps = 256_000;
3145+ encoder.complexity = 10;
3146+ let mut out = vec![0u8; 1500];
3147+ let packets: Vec<crate::AacPacket> = pcm
3148+ .chunks_exact(OPUS_FRAME * 2)
3149+ .map(|block| {
3150+ let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap();
3151+ crate::AacPacket {
3152+ bytes: out[..len].to_vec(),
3153+ samples: OPUS_FRAME as u32,
3154+ }
3155+ })
3156+ .collect();
3157+ let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP));
3158+ assert!(
3159+ fidelity < OPUS_MIN_FIDELITY,
3160+ "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \
3161+ back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half"
3162+ );
3163+ }
3164+
2798 /// The one rule that keeps a picture from being converted twice: a frame the3165 /// The one rule that keeps a picture from being converted twice: a frame the
2799 /// tone map has already brought to BT.709 is never handed the 2020 matrix as3166 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
2800 /// well, on either canvas -- and everything else about the remap is3167 /// well, on either canvas -- and everything else about the remap is
crates/engine/src/mux.rsmodified+85 -1
@@ -65,6 +65,13 @@ pub struct AudioParams {
65 pub freq_index: u8,65 pub freq_index: u8,
66 pub chan_conf: u8,66 pub chan_conf: u8,
67 pub sample_rate: u32,67 pub sample_rate: u32,
68+ /// Set where the packets are **Opus** and not AAC, to the track's pre-skip
69+ /// in samples at 48 kHz ([`crate::export`] writes those only for a Matroska
70+ /// file). It is the whole difference between the two tracks a writer here
71+ /// can declare: `A_OPUS` with an `OpusHead` in `CodecPrivate`
72+ /// ([`opus_track_entry`]) against `A_AAC` with an `AudioSpecificConfig`
73+ /// ([`aac_track_entry`]). `None` is AAC, which is every mp4 and every copy.
74+ pub opus_pre_skip: Option<u16>,
68 }75 }
69 76
70 /// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores77 /// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores
@@ -262,6 +269,14 @@ impl Mp4Muxer {
262 }),269 }),
263 })?;270 })?;
264 if let Some(audio) = audio {271 if let Some(audio) = audio {
272+ // The one thing this writer must never do quietly: an `mp4a` sample
273+ // entry declares AAC, so Opus packets in it would be a file that
274+ // says one codec and holds another. `export` never asks -- Opus is
275+ // written for Matroska alone -- and this is the backstop that keeps
276+ // that true if a format is ever added on the other side.
277+ if audio.opus_pre_skip.is_some() {
278+ return Err("an Opus track in an mp4: this writer declares `mp4a` only".into());
279+ }
265 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;280 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;
266 // The index's own rate, not `audio.sample_rate`: this is the clock281 // The index's own rate, not `audio.sample_rate`: this is the clock
267 // an `stts` counts in and the `esds` states the index, so the two282 // an `stts` counts in and the `esds` states the index, so the two
@@ -729,6 +744,7 @@ const AUDIO: u32 = 0xE1;
729 const SAMPLING_FREQUENCY: u32 = 0xB5;744 const SAMPLING_FREQUENCY: u32 = 0xB5;
730 const CHANNELS: u32 = 0x9F;745 const CHANNELS: u32 = 0x9F;
731 const CODEC_DELAY: u32 = 0x56AA;746 const CODEC_DELAY: u32 = 0x56AA;
747+const SEEK_PRE_ROLL: u32 = 0x56BB;
732 const CLUSTER: u32 = 0x1F43_B675;748 const CLUSTER: u32 = 0x1F43_B675;
733 const CLUSTER_TIMESTAMP: u32 = 0xE7;749 const CLUSTER_TIMESTAMP: u32 = 0xE7;
734 const SIMPLE_BLOCK: u32 = 0xA3;750 const SIMPLE_BLOCK: u32 = 0xA3;
@@ -1086,7 +1102,11 @@ impl MkvMuxer {
1086 let mut tracks = Vec::new();1102 let mut tracks = Vec::new();
1087 elem(&mut tracks, TRACK_ENTRY, &entry);1103 elem(&mut tracks, TRACK_ENTRY, &entry);
1088 if let Some((audio, _)) = &audio {1104 if let Some((audio, _)) = &audio {
1089- elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?);1105+ let entry = match audio.opus_pre_skip {
1106+ Some(pre_skip) => opus_track_entry(audio, pre_skip)?,
1107+ None => aac_track_entry(audio)?,
1108+ };
1109+ elem(&mut tracks, TRACK_ENTRY, &entry);
1090 }1110 }
1091 // Declared even where the audio track is not: the picture is always 11111 // Declared even where the audio track is not: the picture is always 1
1092 // and the sound always 2, so the text starts at 3 whether or not there1112 // 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<Vec<u8>> {
1378 Ok(entry)1398 Ok(entry)
1379 }1399 }
1380 1400
1401+/// The same track when the sound is Opus: `A_OPUS`, whose `CodecPrivate` is the
1402+/// 19-byte `OpusHead` identification header of RFC 7845 §5.1 -- the very bytes
1403+/// an Ogg Opus file opens with, which is why one writer serves both containers
1404+/// and why this project's own reader configures itself from it unchanged
1405+/// (`audio::opus_pre_skip` and `audio::opus_layout` parse exactly this).
1406+///
1407+/// Mapping family 0: mono or stereo, no channel-mapping table, which is the only
1408+/// shape [`crate::export::encode_opus`] writes. The rate field is what the
1409+/// *input* was, not what the stream is coded at -- every Opus decoder runs at
1410+/// 48 kHz whatever it says -- and the output gain is 0 because the mix is
1411+/// already at the level the timeline asked for.
1412+///
1413+/// Two elements no AAC track needs, and both are the difference between a file
1414+/// that plays in sync and one that does not:
1415+/// * `CodecDelay`, the pre-skip in nanoseconds. Matroska times an Opus block for
1416+/// the *audible* stream while the decoder hands back the pre-skip in front of
1417+/// it, so a reader that ignores this starts 2.5 ms early -- measured the other
1418+/// way round on a real film remux (`audio::Track::samples_at`).
1419+/// * `SeekPreRoll`, fixed at 80 ms for Opus by the Matroska spec: how much has
1420+/// to be decoded and thrown away before a seek target for the decoder to be
1421+/// warm. It is a constant of the codec, not of the file.
1422+fn opus_track_entry(audio: &AudioParams, pre_skip: u16) -> crate::Result<Vec<u8>> {
1423+ let rate = audio.sample_rate;
1424+ if rate == 0 || !(1..=2).contains(&audio.chan_conf) {
1425+ return Err(format!(
1426+ "an Opus track at {rate} Hz with {} channels",
1427+ audio.chan_conf
1428+ )
1429+ .into());
1430+ }
1431+ let mut head = Vec::with_capacity(19);
1432+ head.extend_from_slice(b"OpusHead");
1433+ head.push(1); // version
1434+ head.push(audio.chan_conf);
1435+ head.extend_from_slice(&pre_skip.to_le_bytes());
1436+ head.extend_from_slice(&rate.to_le_bytes());
1437+ head.extend_from_slice(&0i16.to_le_bytes()); // output gain
1438+ head.push(0); // mapping family
1439+
1440+ let mut entry = Vec::new();
1441+ uint(&mut entry, TRACK_NUMBER, 2);
1442+ uint(&mut entry, TRACK_UID, 2);
1443+ uint(&mut entry, TRACK_TYPE, 2); // audio
1444+ uint(&mut entry, FLAG_LACING, 0);
1445+ elem(&mut entry, CODEC_ID, b"A_OPUS");
1446+ elem(&mut entry, CODEC_PRIVATE, &head);
1447+ uint(
1448+ &mut entry,
1449+ CODEC_DELAY,
1450+ u64::from(pre_skip) * 1_000_000_000 / u64::from(rate),
1451+ );
1452+ uint(&mut entry, SEEK_PRE_ROLL, 80_000_000);
1453+ let mut audio_elem = Vec::new();
1454+ put_id(&mut audio_elem, SAMPLING_FREQUENCY);
1455+ put_size(&mut audio_elem, 8);
1456+ audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes());
1457+ uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf));
1458+ elem(&mut entry, AUDIO, &audio_elem);
1459+ Ok(entry)
1460+}
1461+
1381 /// Which track the *first* subtitle block names, the picture's 1 and the sound's1462 /// Which track the *first* subtitle block names, the picture's 1 and the sound's
1382 /// 2 being fixed: a file with no audio track still writes its first text track1463 /// 2 being fixed: a file with no audio track still writes its first text track
1383 /// on 3, so nothing has to count the tracks before it to read a block. Each1464 /// on 3, so nothing has to count the tracks before it to read a block. Each
@@ -1898,6 +1979,7 @@ mod tests {
1898 freq_index: 4, // 441001979 freq_index: 4, // 44100
1899 chan_conf: 2,1980 chan_conf: 2,
1900 sample_rate: 44_100,1981 sample_rate: 44_100,
1982+ opus_pre_skip: None,
1901 }),1983 }),
1902 )1984 )
1903 .unwrap();1985 .unwrap();
@@ -2042,6 +2124,7 @@ mod tests {
2042 freq_index: 3, // 480002124 freq_index: 3, // 48000
2043 chan_conf: 2,2125 chan_conf: 2,
2044 sample_rate: 48_000,2126 sample_rate: 48_000,
2127+ opus_pre_skip: None,
2045 },2128 },
2046 packets,2129 packets,
2047 )),2130 )),
@@ -2113,6 +2196,7 @@ mod tests {
2113 freq_index: 3,2196 freq_index: 3,
2114 chan_conf: 2,2197 chan_conf: 2,
2115 sample_rate: 48_000,2198 sample_rate: 48_000,
2199+ opus_pre_skip: None,
2116 }),2200 }),
2117 )2201 )
2118 .unwrap();2202 .unwrap();
crates/engine/tests/opus_export.rsadded+401 -0
@@ -0,0 +1,401 @@
1+//! Opus on the way *out*: an edited Opus source leaves a Matroska export as
2+//! Opus instead of being turned into AAC, and comes back in through this
3+//! project's own door -- symphonia's mkv reader for the container, `ruopus` for
4+//! the packets, which is the pair a film already plays through.
5+//!
6+//! Three claims, and each is measured rather than asserted from the code:
7+//!
8+//! * the file really carries an `A_OPUS` track with an `OpusHead` in its
9+//! `CodecPrivate`, and what comes back out of it correlates with the mix that
10+//! went in -- sample-aligned, so the pre-skip in that header is the encoder's
11+//! real lookahead and not a number somebody hoped for;
12+//! * a timeline nobody has touched still *copies* its AAC packets rather than
13+//! taking the new encoder: Opus is what an edit costs, never what a passthrough
14+//! costs;
15+//! * and the envelope itself -- 48 kHz, stereo, at most
16+//! `OPUS_MAX_KBPS` -- is a measurement of `opus-rs 0.1.26` and is pinned here,
17+//! so the day the crate is bumped past its high-rate bug this suite says so.
18+//!
19+//! Nothing here needs a GPU: the picture is 320x180 and HEVC's intra encoder is
20+//! software by construction, so the whole file runs anywhere. Add
21+//! `EDITH_OPUS_FILM=<path to a real-library Opus mkv>` to run the film case too
22+//! -- it is skipped without it, since no film lives in this repo.
23+
24+use std::path::{Path, PathBuf};
25+use std::process::Command;
26+use std::sync::Once;
27+use std::time::{Duration, Instant};
28+
29+use engine::export::{ExportSettings, Format};
30+use engine::project::{LaneKind, Source, Speed};
31+use engine::scale::FitPolicy;
32+use engine::scratch::Scratch;
33+use engine::{AudioSession, Clip, ExportHandle, Project};
34+
35+/// The picture: 320x180 at 24 fps, 30 s (`scripts/gen_fixtures.sh`). Its own
36+/// sound is mono Opus and is deliberately left off the audio lane -- see
37+/// [`a_mono_mix_keeps_the_aac_path`].
38+const VIDEO: &str = "test_seek_chirp.mkv";
39+/// The sound: 5.1 Opus, 440 Hz in FL and 880 Hz in BR, folded to stereo on the
40+/// way to the timeline -- so the mix this export encodes *is* an Opus source's,
41+/// at the only rate Opus has.
42+const OPUS: &str = "test_opus_51.mka";
43+/// One Opus frame, in samples per channel: what the tail of an export may be
44+/// padded by.
45+const OPUS_FRAME_SAMPLES: usize = 960;
46+/// The AAC source whose packets a copy must still win with.
47+const AAC: &str = "test_av.mp4";
48+
49+fn asset(name: &str) -> PathBuf {
50+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
51+ .join("../../assets")
52+ .join(name)
53+}
54+
55+fn out_path(name: &str) -> Scratch {
56+ Scratch::file(&format!("ve_opus_{name}"), "mkv")
57+}
58+
59+fn pin_software() {
60+ static PIN: Once = Once::new();
61+ PIN.call_once(|| unsafe {
62+ std::env::set_var("VE_SW", "1");
63+ std::env::set_var("VE_SW_ENC", "1");
64+ });
65+}
66+
67+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
68+ let started = Instant::now();
69+ while !handle.is_finished() {
70+ assert!(
71+ started.elapsed() < limit,
72+ "export did not finish in {limit:?}"
73+ );
74+ std::thread::sleep(Duration::from_millis(10));
75+ }
76+ handle.result().expect("a finished export has an outcome")
77+}
78+
79+/// One second of picture with one second of `sound` under it, cut from
80+/// `sound_in` seconds into that file: an edit, so nothing here can be a copy.
81+fn project(video: &Path, sound: &Path, sound_in: u32) -> Project {
82+ let clip = |source, in_frame, out_frame| Clip {
83+ start: 0,
84+ in_frame,
85+ out_frame,
86+ source,
87+ link: None,
88+ eq: None,
89+ color: None,
90+ fit: FitPolicy::default(),
91+ speed: Speed::NORMAL,
92+ };
93+ // The sound is source **0** on purpose: the timeline takes its rate and its
94+ // width from the first source that has any, so a project whose first source
95+ // is a mono-track video file is a mono timeline whatever plays on its audio
96+ // lane -- which is the engine's rule, not this test's, and the one that
97+ // decides whether Opus is reachable at all.
98+ Project::from_parts(
99+ vec![Source::new(sound, 0), Source::new(video, 0)],
100+ vec![
101+ (LaneKind::Video, vec![clip(1, 0, 24)]),
102+ (
103+ LaneKind::Audio,
104+ vec![clip(0, sound_in * 24, sound_in * 24 + 24)],
105+ ),
106+ ],
107+ Vec::new(),
108+ Vec::new(),
109+ )
110+ .expect("a picture lane and an audio lane")
111+}
112+
113+fn export(name: &str, project: Project, video: &Path) -> Scratch {
114+ pin_software();
115+ let out = out_path(name);
116+ let (meta, _) = engine::demux::Demuxer::open(video).expect("probe the picture");
117+ let handle = engine::export::start(
118+ project,
119+ meta,
120+ &out,
121+ &ExportSettings {
122+ format: Format::Hevc,
123+ ..Default::default()
124+ },
125+ );
126+ wait(&handle, Duration::from_secs(600)).expect("the export finishes");
127+ out
128+}
129+
130+/// Interleaved samples of a written file through the engine's own reader: the
131+/// door an import comes in through, and for an Opus track that is symphonia's
132+/// mkv reader handing `CodecPrivate` and blocks to `ruopus`.
133+fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
134+ let (meta, chunks) = AudioSession::open(path)
135+ .expect("reopen the export")
136+ .expect("the export has audio");
137+ let mut samples = Vec::new();
138+ for chunk in chunks {
139+ samples.extend(chunk.samples);
140+ }
141+ (meta, samples)
142+}
143+
144+/// The best normalised correlation of `got` against `want` over the first
145+/// `lags` samples of offset, and the offset that reached it: a lossy codec
146+/// changes the samples, so what says "this is the same sound in the same place"
147+/// is the shape, and where the shape sits.
148+fn align(want: &[f32], got: &[f32], lags: usize) -> (f64, usize) {
149+ let window = 12_000.min(want.len()).min(got.len().saturating_sub(lags));
150+ assert!(window > 1000, "not enough sound to correlate");
151+ let (mut best, mut at) = (-2.0, 0);
152+ for lag in 0..lags {
153+ let c = corr(&want[..window], &got[lag..lag + window]);
154+ if c > best {
155+ best = c;
156+ at = lag;
157+ }
158+ }
159+ (best, at)
160+}
161+
162+fn corr(a: &[f32], b: &[f32]) -> f64 {
163+ let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
164+ for (x, y) in a.iter().zip(b) {
165+ num += f64::from(*x) * f64::from(*y);
166+ da += f64::from(*x) * f64::from(*x);
167+ db += f64::from(*y) * f64::from(*y);
168+ }
169+ num / (da.sqrt() * db.sqrt()).max(1e-12)
170+}
171+
172+/// One channel of an interleaved buffer.
173+fn chan(samples: &[f32], channels: usize, which: usize) -> Vec<f32> {
174+ samples
175+ .iter()
176+ .skip(which)
177+ .step_by(channels)
178+ .copied()
179+ .collect()
180+}
181+
182+/// The claim: a cut of an Opus source, exported as a Matroska file, carries an
183+/// Opus track -- and that track is this project's own mix, in the right place.
184+#[test]
185+fn an_edited_opus_source_leaves_a_matroska_export_as_opus() {
186+ let out = export(
187+ "cut",
188+ project(&asset(VIDEO), &asset(OPUS), 1),
189+ &asset(VIDEO),
190+ );
191+
192+ // The container, before any decoder: `A_OPUS` with an `OpusHead` in its
193+ // `CodecPrivate`, and no AAC track anywhere near it.
194+ let bytes = std::fs::read(&*out).expect("read the export back");
195+ let head = find(&bytes, b"OpusHead").expect("an OpusHead in the CodecPrivate");
196+ assert!(find(&bytes, b"A_OPUS").is_some(), "the track says A_OPUS");
197+ assert!(find(&bytes, b"A_AAC").is_none(), "and nothing says A_AAC");
198+ assert_eq!(bytes[head + 9], 2, "OpusHead: stereo");
199+ // The pre-skip: the encoder's lookahead plus the warm-up frame it throws
200+ // away, which is what `export::tests` measures the sound starting at.
201+ assert_eq!(
202+ u16::from_le_bytes([bytes[head + 10], bytes[head + 11]]),
203+ 1080,
204+ "OpusHead: pre-skip"
205+ );
206+ assert_eq!(
207+ u32::from_le_bytes(bytes[head + 12..head + 16].try_into().unwrap()),
208+ 48_000,
209+ "OpusHead: 48 kHz"
210+ );
211+ assert_eq!(bytes[head + 18], 0, "OpusHead: mapping family 0");
212+
213+ // ...and what a decoder makes of it, against the very second of the source
214+ // the timeline cut out. The reader drops the pre-skip off the front, so a
215+ // correct header lands the sound at zero: any leftover offset here is
216+ // exactly the codec delay this file failed to declare.
217+ let (meta, got) = decode(&out);
218+ assert_eq!(meta.sample_rate, 48_000, "Opus reads back at 48 kHz");
219+ assert_eq!(meta.channels, 2);
220+ let (_, want) = {
221+ let (m, chunks) = AudioSession::open_segments(asset(OPUS), &[(1.0, 2.0)])
222+ .expect("open the source")
223+ .expect("the source has sound");
224+ let mut s = Vec::new();
225+ for chunk in chunks {
226+ s.extend(chunk.samples);
227+ }
228+ (m, s)
229+ };
230+ // The fixture's two channels are *pure* sines, so a lag search on them is
231+ // ambiguous by whole periods (440 Hz is 109.09 samples) and cannot be the
232+ // alignment check -- that one is unambiguous in `export::tests`, on a signal
233+ // with no period, and lands on the declared pre-skip exactly. What is
234+ // checked here is the pair a periodic signal *can* answer: the sound is the
235+ // source's, and it is in the right place to within a sample at lag zero.
236+ assert!(
237+ got.len() >= want.len() - 2 && got.len() <= want.len() + OPUS_FRAME_SAMPLES * 2,
238+ "the track is {} samples where the timeline is {}",
239+ got.len(),
240+ want.len()
241+ );
242+ for (which, name) in [(0, "left"), (1, "right")] {
243+ let (w, g) = (chan(&want, 2, which), chan(&got, 2, which));
244+ let span = w.len().min(g.len());
245+ let aligned = corr(&w[..span], &g[..span]);
246+ assert!(
247+ aligned >= 0.98,
248+ "{name}: correlation {aligned:.4} against the source at lag zero -- \
249+ the export is either not this sound or not in this place"
250+ );
251+ // Past the first frame, where the encoder's cold start is behind it:
252+ // 0.997 left and 0.993 right, measured, against 0.9948/0.9825 with the
253+ // head in. That gap *is* the ramp the pre-skip cannot cover, and it is
254+ // asserted from both sides so neither can drift unnoticed.
255+ let settled = corr(&w[OPUS_FRAME_SAMPLES..span], &g[OPUS_FRAME_SAMPLES..span]);
256+ assert!(
257+ settled >= 0.99,
258+ "{name}: correlation {settled:.4} past the first frame"
259+ );
260+ // ...and the head specifically, which is what the pre-skip and the
261+ // warm-up frame are for. Measured at 128 kbps: 0.990 left, 0.953 right,
262+ // where the same export with no warm-up frame scored 0.9788 left and a
263+ // mis-declared pre-skip would score far less than either. The gap to the
264+ // 0.99 above is one frame of cold start -- `opus-rs 0.1.26` opens about
265+ // 6 dB down whatever is fed in ahead of it (two warm-up frames change
266+ // this in no decimal place) -- so this threshold is that ramp stated
267+ // rather than a shrug.
268+ let head = corr(&w[..12_000], &g[..12_000]);
269+ assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}");
270+ }
271+
272+ // A second implementation on the same bytes, where the box has one: ffmpeg
273+ // decoding what we wrote is the check that the file is Opus by the format's
274+ // rules and not merely by ours -- pre-skip included, since ffmpeg drops it
275+ // off the front exactly as this project's reader does.
276+ if let Some(pcm) = ffmpeg_decode(&out) {
277+ let (w, g) = (chan(&want, 2, 0), chan(&pcm, 2, 0));
278+ let span = w.len().min(g.len());
279+ assert!(
280+ span + 4 >= w.len(),
281+ "ffmpeg read {span} samples of a {} sample track",
282+ w.len()
283+ );
284+ let c = corr(&w[..span], &g[..span]);
285+ assert!(
286+ c >= 0.99,
287+ "ffmpeg's decode correlates {c:.4} with the source"
288+ );
289+ }
290+}
291+
292+/// The other half of the seat: an untouched AAC timeline still *copies*, even
293+/// into the container that would otherwise encode Opus. A copy is bit-exact and
294+/// an encode is a generation of loss, so the new encoder must never be reached
295+/// where the old passthrough still applies.
296+#[test]
297+fn an_untouched_timeline_still_copies_its_aac_into_an_mkv() {
298+ let source = asset(AAC);
299+ let out = export("copy", project(&source, &source, 0), &source);
300+ let bytes = std::fs::read(&*out).expect("read the export back");
301+ assert!(find(&bytes, b"A_AAC").is_some(), "the copy stays AAC");
302+ assert!(
303+ find(&bytes, b"A_OPUS").is_none(),
304+ "an untouched lane took the Opus encoder instead of copying"
305+ );
306+}
307+
308+/// A mono mix keeps AAC, and that is a *measurement* and not a preference:
309+/// `opus-rs 0.1.26` mis-encodes mono at rates it is asked for here (see the
310+/// envelope test in `export.rs`), so the file that would play back wrong is
311+/// never written. `test_seek_chirp.mkv` carries mono Opus, which is exactly the
312+/// source that would tempt this path.
313+#[test]
314+fn a_mono_mix_keeps_the_aac_path() {
315+ let source = asset(VIDEO);
316+ let out = export("mono", project(&source, &source, 1), &source);
317+ let bytes = std::fs::read(&*out).expect("read the export back");
318+ assert!(
319+ find(&bytes, b"A_AAC").is_some(),
320+ "a mono mix is written as AAC"
321+ );
322+ assert!(find(&bytes, b"A_OPUS").is_none());
323+}
324+
325+/// A real library, not a fixture: a real Opus film, cut, exported, read back.
326+/// The path comes from the environment because no film's name belongs in this
327+/// repository; without it the test says so and passes.
328+#[test]
329+fn a_real_library_opus_film_exports_as_opus() {
330+ let Some(film) = std::env::var_os("EDITH_OPUS_FILM").map(PathBuf::from) else {
331+ eprintln!("EDITH_OPUS_FILM unset: the film case is skipped");
332+ return;
333+ };
334+ // The fixture's picture under the film's *sound*: what is on trial here is
335+ // an Opus track off a real library -- 5.1, folded to stereo on the way in
336+ // -- and decoding a 1080p AV1 film would drag a VA-API plugin into a test
337+ // about audio.
338+ let out = export("film", project(&asset(VIDEO), &film, 600), &asset(VIDEO));
339+ let bytes = std::fs::read(&*out).expect("read the export back");
340+ assert!(
341+ find(&bytes, b"A_OPUS").is_some(),
342+ "the film's sound stays Opus"
343+ );
344+ let (meta, got) = decode(&out);
345+ assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
346+ let (_, want) = {
347+ let (_, chunks) = AudioSession::open_segments(&film, &[(600.0, 601.0)])
348+ .expect("open the film")
349+ .expect("the film has sound");
350+ let mut s = Vec::new();
351+ for chunk in chunks {
352+ s.extend(chunk.samples);
353+ }
354+ ((), s)
355+ };
356+ // Film sound is broadband and has no period, so unlike the tone fixture the
357+ // lag here is unambiguous: the peak is where the sound is.
358+ let (c, lag) = align(&chan(&want, 2, 0), &chan(&got, 2, 0), 400);
359+ // What ffprobe makes of the same file, printed rather than parsed -- run
360+ // with `--nocapture` and this is the line that says `Audio: opus`.
361+ if let Ok(probe) = Command::new("ffprobe")
362+ .args(["-hide_banner"])
363+ .arg(&*out)
364+ .output()
365+ {
366+ eprint!("{}", String::from_utf8_lossy(&probe.stderr));
367+ }
368+ eprintln!("the film's span: correlation {c:.4} at lag {lag}");
369+ assert!(c >= 0.99, "the film's span correlates {c:.4} at lag {lag}");
370+ assert!(lag <= 2, "the film's span starts {lag} samples late");
371+}
372+
373+/// Where `needle` first sits in `hay`.
374+fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
375+ hay.windows(needle.len()).position(|w| w == needle)
376+}
377+
378+/// ffmpeg's own decode of a file, interleaved f32 at 48 kHz stereo. `None`
379+/// where the box has no ffmpeg -- the test is about the file, not about this
380+/// machine's packages.
381+fn ffmpeg_decode(path: &Path) -> Option<Vec<f32>> {
382+ let out = Command::new("ffmpeg")
383+ .args(["-v", "error", "-i"])
384+ .arg(path)
385+ .args([
386+ "-map", "0:a:0", "-f", "f32le", "-ar", "48000", "-ac", "2", "-",
387+ ])
388+ .output()
389+ .ok()?;
390+ assert!(
391+ out.status.success(),
392+ "ffmpeg refused the exported Opus track: {}",
393+ String::from_utf8_lossy(&out.stderr)
394+ );
395+ Some(
396+ out.stdout
397+ .chunks_exact(4)
398+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
399+ .collect(),
400+ )
401+}