forge
Explore
Log in

Don't you dare go Hollow

OGG Vorbis is a row you can pick, not a note about missing encoders

Browse files at this commit

17d7d999a9b000a9da9bc9b6c9cb741853011a17Ahmet Kaan GümüşParent: 79fd658
  • feat
    • OGG Vorbis is a row you can pick, not a note about missing encoders
Show full message
✨ feat(export): OGG Vorbis is a row you can pick, not a note about missing encoders

The export card said "no pure-Rust Vorbis or Opus encoder" and that had stopped
being true. `rusty_vorbis` 0.1.1 (Apache-2.0, zero dependencies, same family as
the h264/aac/mp3 encoders already here) is the first permissively-licensed
pure-Rust Vorbis *encoder*; `oxideav-ogg` 0.1.8 pages it, and its only dependency
is the `oxideav-core` the AC-3 decoder already pulls in. No C, no FFI, no new
runtime system dependency -- `ldd` on the binary is unchanged, name for name.

The row is live, keyed `o`, and names its encoder like every other live row does.
VP9 stays refused with the reason it always had: AV1 replaces it.

What the bench found, and what the code does about it. Every number below was
measured by encoding this suite's own fixtures and decoding them back with
symphonia -- an independent decoder, and the one this engine reopens exports
with:

* The encoder numbers its granules a full block ahead of the samples it codes,
  so written straight through, every sample lands ~1024 early: a marker signal
  came back with its head at 36% amplitude and a full-scale burst 1500 samples
  before the real one, in silence. One hop of silent pre-roll puts it back --
  head 0.86 against an input peak of 0.80, the phantom burst down to 0.04.
* Its block grid overshoots the last sample, so the stream is padded and the
  last page's granule declares the timeline's own frame count. An `.ogg` is now
  exactly as long as the WAV of the same timeline, which is the promise every
  other audio row here keeps.
* Below quality 0.50 the encoder is *quiet*, not merely coarse (1-1.6 dB of
  level error, near-silence at 0.10), and the whole usable band tops out around
  200 kbps. So the file is written at one measured quality, 0.85, and the Sound
  row is refused by name rather than mapping 128/192/256/320 onto quality steps:
  the top two are rates this encoder cannot reach, and a card that printed them
  would be lying.
* The embedded setup header is a stereo profile -- a mono push is refused
  outright -- so a mono mix is written as dual mono, both channels bit-identical.

And one defect the round trip turned up on the way in: `SymTrack` subtracted
`Track::delay` on top of symphonia, which already drops those frames itself.
Every `.mp3` import was losing its first 1105 samples (25 ms) and reading 25 ms
short, every `.ogg` its first 128. Measured against `test_tone.flac` -- lossless,
and the only one of the three declaring no delay -- which the mp3 and the ogg of
the same tone now align with. WAV, FLAC and AAC-in-mp4 read hash-identical
across the change; only those two formats move, and both move to the length
their own container declares.
Cargo.lockmodified+17 -0
@@ -1645,11 +1645,13 @@ dependencies = [
16451645 "oxideav-ass",
16461646 "oxideav-core",
16471647 "oxideav-h265",
1648+ "oxideav-ogg",
16481649 "oxideav-subtitle",
16491650 "rav1e",
16501651 "rusty_aac",
16511652 "rusty_h264",
16521653 "rusty_mp3",
1654+ "rusty_vorbis",
16531655 "symphonia",
16541656 "symphonia-codec-aac",
16551657 "symphonia-core",
@@ -3976,6 +3978,15 @@ dependencies = [
39763978 "oxideav-core",
39773979 ]
39783980
3981+[[package]]
3982+name = "oxideav-ogg"
3983+version = "0.1.8"
3984+source = "registry+https://github.com/rust-lang/crates.io-index"
3985+checksum = "8a582af48d51a2a8d2d87958ca22a3a21f9029dcc828c1b4a5865fa00f952d3a"
3986+dependencies = [
3987+ "oxideav-core",
3988+]
3989+
39793990 [[package]]
39803991 name = "oxideav-otf"
39813992 version = "0.1.3"
@@ -5028,6 +5039,12 @@ version = "0.6.1"
50285039 source = "registry+https://github.com/rust-lang/crates.io-index"
50295040 checksum = "a99f339ec9a2d84eec8fc2a42baa92426966b25238c498e79d57b4e49b14fbad"
50305041
5042+[[package]]
5043+name = "rusty_vorbis"
5044+version = "0.1.1"
5045+source = "registry+https://github.com/rust-lang/crates.io-index"
5046+checksum = "6eddf79e697ce9279ef0e012432cd2889a7b6305a45efb5bb16e8a1d6338646f"
5047+
50315048 [[package]]
50325049 name = "rustybuzz"
50335050 version = "0.14.1"
crates/app/src/keymap.rsmodified+1 -1
@@ -379,7 +379,7 @@ pub const FIXED: [Fixed; 28] = [
379379 },
380380 Fixed {
381381 chord: "m / a / h / w / f / p",
382- label: "Pick the export codec: H.264, AV1, HEVC, WAV, FLAC or MP3",
382+ label: "Pick the export codec: H.264, AV1, HEVC, WAV, FLAC, MP3 or OGG",
383383 category: Category::File,
384384 },
385385 // The rest of the export card's own rows, each on the letter its row is
crates/app/src/main.rsmodified+44 -18
@@ -9792,7 +9792,12 @@ const FORMATS: [(&[Format], &str, &str, &str); 8] = [
97929792 (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"),
97939793 (&[Format::Flac], "f", "FLAC", "lossless — audio only"),
97949794 (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"),
9795- (&[], "", "OGG", "no pure-Rust Vorbis or Opus encoder"),
9795+ (
9796+ &[Format::Ogg],
9797+ "o",
9798+ "OGG",
9799+ "Vorbis (rusty_vorbis) — quality-coded, stereo",
9800+ ),
97969801 (&[], "", "VP9", "AV1 above replaces it"),
97979802 ];
97989803
@@ -9856,6 +9861,14 @@ fn bitrate_refusal(format: Format) -> Option<&'static str> {
98569861 match format {
98579862 Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"),
98589863 Format::Mp3 => Some("sound only — its rate is the Sound row"),
9864+ // The guard is the question and not a list of names: an audio format
9865+ // added without a line of its own above would otherwise show live
9866+ // quality rows over a file that has no picture to spend a bitrate on.
9867+ // OGG is exactly that format -- and it wants this sentence rather than
9868+ // one of its own, because its *Sound* row already says the Vorbis half
9869+ // ("quality-coded — Vorbis holds no rate to pick") and two rows saying
9870+ // the same thing is one of them wasted.
9871+ _ if !format.has_video() => Some("sound only — no picture to spend a bitrate on"),
98599872 _ => None,
98609873 }
98619874 }
@@ -10145,6 +10158,7 @@ fn format_line(format: Format) -> &'static str {
1014510158 Format::Wav => "16-bit PCM · WAV",
1014610159 Format::Flac => "FLAC · lossless",
1014710160 Format::Mp3 => "MP3 · lossy",
10161+ Format::Ogg => "Vorbis · OGG",
1014810162 }
1014910163 }
1015010164
@@ -10406,7 +10420,7 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
1040610420 match picture {
1040710421 true => None,
1040810422 false => Some(format!(
10409- "no picture — {} would be black; export WAV, FLAC or MP3",
10423+ "no picture — {} would be black; export WAV, FLAC, MP3 or OGG",
1041010424 format.name()
1041110425 )),
1041210426 }
@@ -11785,15 +11799,15 @@ mod tests {
1178511799 // and are never refused.
1178611800 assert_eq!(
1178711801 format_refusal(&session, Format::Mp4).as_deref(),
11788- Some("no picture — an mp4 would be black; export WAV, FLAC or MP3")
11802+ Some("no picture — an mp4 would be black; export WAV, FLAC, MP3 or OGG")
1178911803 );
1179011804 assert_eq!(
1179111805 format_refusal(&session, Format::Av1).as_deref(),
11792- Some("no picture — an AV1 Matroska would be black; export WAV, FLAC or MP3")
11806+ Some("no picture — an AV1 Matroska would be black; export WAV, FLAC, MP3 or OGG")
1179311807 );
1179411808 assert_eq!(
1179511809 format_refusal(&session, Format::Av1Mp4).as_deref(),
11796- Some("no picture — an AV1 mp4 would be black; export WAV, FLAC or MP3")
11810+ Some("no picture — an AV1 mp4 would be black; export WAV, FLAC, MP3 or OGG")
1179711811 );
1179811812 assert_eq!(format_refusal(&session, Format::Wav), None);
1179911813 assert_eq!(format_refusal(&session, Format::Flac), None);
@@ -14715,7 +14729,7 @@ mod tests {
1471514729 #[test]
1471614730 fn every_codec_row_is_offered_or_says_why_not() {
1471714731 // One row per codec, and the boxes it can go in are the container row's
14718- // business: six rows that pick, two that say why they cannot. A codec
14732+ // business: seven rows that pick, one that says why it cannot. A codec
1471914733 // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same
1472014734 // question, and five picture rows above the fold is what the card was
1472114735 // called unfriendly for.
@@ -14733,6 +14747,7 @@ mod tests {
1473314747 &[Format::Wav][..],
1473414748 &[Format::Flac][..],
1473514749 &[Format::Mp3][..],
14750+ &[Format::Ogg][..],
1473614751 ]
1473714752 );
1473814753 // Every format the engine writes is on exactly one row: one the card
@@ -14746,6 +14761,7 @@ mod tests {
1474614761 Format::Wav,
1474714762 Format::Flac,
1474814763 Format::Mp3,
14764+ Format::Ogg,
1474914765 ] {
1475014766 assert_eq!(
1475114767 FORMATS
@@ -14838,18 +14854,28 @@ mod tests {
1483814854 None,
1483914855 "a stroke no row carries"
1484014856 );
14841- // The codec this program reads and cannot write is a row of its own,
14842- // refused by name rather than absent: VP9, because AV1 is the row that
14843- // replaced it. Its reason travels with it, in the row or in the footer
14844- // line that collects them -- either way it is on screen without a click.
14845- for (label, word) in [("VP9", "replaces it"), ("OGG", "no pure-Rust")] {
14846- let (row, _, _, detail) = FORMATS
14847- .into_iter()
14848- .find(|(_, _, name, _)| *name == label)
14849- .unwrap_or_else(|| panic!("{label} has no row"));
14850- assert!(row.is_empty(), "{label} is not offered");
14851- assert!(detail.contains(word), "{label}: {detail}");
14852- }
14857+ assert_eq!(format_key("o", Format::Mp4), Some(Format::Ogg));
14858+ // The one codec left that this program reads and cannot write is a row
14859+ // of its own, refused by name rather than absent: VP9, because AV1 is
14860+ // the row that replaced it. Its reason travels with it, in the row or in
14861+ // the footer line that collects them -- either way it is on screen
14862+ // without a click. OGG was the other one until `rusty_vorbis` gave this
14863+ // project an encoder, and the row that says so is the row above.
14864+ let (row, _, _, detail) = FORMATS
14865+ .into_iter()
14866+ .find(|(_, _, name, _)| *name == "VP9")
14867+ .expect("VP9 has a row");
14868+ assert!(row.is_empty(), "VP9 is not offered");
14869+ assert!(detail.contains("replaces it"), "VP9: {detail}");
14870+ let (row, _, _, detail) = FORMATS
14871+ .into_iter()
14872+ .find(|(_, _, name, _)| *name == "OGG")
14873+ .expect("OGG has a row");
14874+ assert_eq!(row, [Format::Ogg], "OGG is a row that picks now");
14875+ assert!(
14876+ detail.contains("rusty_vorbis"),
14877+ "the row names the encoder like every other live one: {detail}"
14878+ );
1485314879 // Both AV1 boxes say they carry sound: the file used to be picture only,
1485414880 // and a line that still said so would be the lie a user plays the file
1485514881 // to find out about. HEVC says intra-only before anyone waits on one --
crates/engine/Cargo.tomlmodified+17 -0
@@ -40,6 +40,23 @@ rusty_aac = "0.5"
4040 # symphonia's below -- an mp3 has always been importable here, and until this it
4141 # was the one format the editor could read and never write.
4242 rusty_mp3 = "0.6"
43+# The Vorbis encoder, same family and the same reason as the three above: pure
44+# Rust, Apache-2.0, no C and no FFI. It is the *first* permissively-licensed
45+# pure-Rust Vorbis encoder -- `vorbis_rs` and `vorbis-encoder` are both bindings
46+# to Xiph's C library, which this project's no-install rule forbids, and
47+# `oxideav-vorbis` (whose own manifest calls itself an "orphan-rebuild scaffold")
48+# ships encoder-side *bitstream writers* with no analysis stage at all: no psy
49+# model, no floor fit, no residue quantiser, nothing that turns PCM into a
50+# packet. This one does the whole pipeline. Its quirks are measured and worked
51+# around in [`crate::export::write_ogg`] -- read that before touching this line.
52+rusty_vorbis = "0.1.1"
53+# The Ogg container, and the only new *name* here that is not a new crate tree:
54+# its one dependency is `oxideav-core`, which the AC-3 decoder above already
55+# pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the
56+# three-header blob and the muxer pages those ahead of the audio, which is the
57+# encapsulation order a Vorbis decoder needs and the part that is easy to get
58+# wrong by hand.
59+oxideav-ogg = "0.1.8"
4360 symphonia-core = "0.6"
4461 symphonia-codec-aac = "0.6"
4562 # The umbrella crate for the standalone audio files: one dependency instead of
crates/engine/src/audio.rsmodified+14 -4
@@ -1193,8 +1193,17 @@ struct SymTrack {
11931193 source_channels: u16,
11941194 /// Frames per channel of audible audio, `None` when the header does not say.
11951195 total_samples: Option<u64>,
1196- /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the
1197- /// container where it declares one (mp3's Xing/LAME tag, ALAC's edit list).
1196+ /// Encoder delay, and **always zero here**: symphonia 0.6 drops the leading
1197+ /// frames itself, so a reader that skipped `Track::delay` on top would skip
1198+ /// them twice. Kept as a field because [`Track::priming`] asks every track
1199+ /// for one and the AAC and AC-3 readers beside it do owe a real number.
1200+ ///
1201+ /// This used to carry `delay` and cost the double skip on the two formats
1202+ /// that declare one: a `.mp3` lost its first 1105 samples (25 ms) and read
1203+ /// 25 ms short, an `.ogg` its first 128. Measured 2026-08-11 against
1204+ /// `test_tone.flac` -- lossless, and the only one of the three whose
1205+ /// container declares no delay at all -- which the mp3 and the ogg of the
1206+ /// same tone align with sample for sample once this is not subtracted.
11981207 priming: u64,
11991208 time_base: TimeBase,
12001209 params: AudioCodecParameters,
@@ -1227,7 +1236,8 @@ impl SymTrack {
12271236 let Some(track) = reader.default_track(SymKind::Audio) else {
12281237 return Ok(None);
12291238 };
1230- let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);
1239+ // `track.delay` is deliberately not read: see the `priming` field.
1240+ let (track_id, num_frames) = (track.id, track.num_frames);
12311241 let time_base = track
12321242 .time_base
12331243 .ok_or_else(|| format!("{} declares no time base", path.display()))?;
@@ -1257,7 +1267,7 @@ impl SymTrack {
12571267 channels: if channels == 6 { 2 } else { channels },
12581268 source_channels: channels,
12591269 total_samples: num_frames,
1260- priming: u64::from(delay.unwrap_or(0)),
1270+ priming: 0,
12611271 time_base,
12621272 params,
12631273 codec,
crates/engine/src/caps.rsmodified+1 -1
@@ -35,7 +35,7 @@ const SW_CODECS: [(&str, &str, bool, bool); 10] = [
3535 ("FLAC", "symphonia / flacenc", true, true),
3636 ("PCM", "symphonia / hound", true, true),
3737 ("AC-3", "oxideav-ac3", true, false),
38- ("Vorbis", "symphonia", true, false),
38+ ("Vorbis", "symphonia / rusty_vorbis", true, true),
3939 ("ALAC", "symphonia", true, false),
4040 ];
4141
crates/engine/src/export.rsmodified+198 -11
@@ -1,6 +1,6 @@
11 //! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or
2-//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC
3-//! or MP3 of the timeline's audio alone.
2+//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC,
3+//! MP3 or Ogg Vorbis of the timeline's audio alone.
44 //!
55 //! The HEVC pair is **intra-only**, and says so wherever it is offered: every
66 //! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the
@@ -16,8 +16,8 @@
1616 //! equalized one, a source that is not AAC inside an mp4's own sample table —
1717 //! the sound is decoded, mixed and encoded again with `rusty_aac`
1818 //! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes
19-//! PCM, `flacenc` encodes FLAC and `rusty_mp3` encodes MP3, so those are always
20-//! *decoded* out of the timeline. The worker owns everything: the caller gets an
19+//! PCM, `flacenc` encodes FLAC, `rusty_mp3` encodes MP3 and `rusty_vorbis`
20+//! encodes Vorbis, so those are always *decoded* out of the timeline. The worker owns everything: the caller gets an
2121 //! [`ExportHandle`] and polls it from its render loop.
2222 //!
2323 //! **Every video format here carries the timeline's sound**, in whichever
@@ -36,8 +36,8 @@
3636 //! The sound is *copied* unless something forces a decode, and a packet carries
3737 //! no rate — so a speeded lane is one of the things that forces one
3838 //! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
39-//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate
40-//! like the picture does.
39+//! picture. The audio-only formats are decoded and resampled, so they honour a
40+//! rate like the picture does.
4141 //!
4242 //! Nothing partial survives a failure: the worker writes to `<out>.part` and
4343 //! renames it onto `out` only once the file is closed and complete, so the
@@ -58,6 +58,10 @@ use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
5858
5959 use flacenc::component::BitRepr;
6060 use flacenc::error::Verify;
61+// The trait the Ogg muxer's `write_header` / `write_packet` / `write_trailer`
62+// live on -- `oxideav_ogg::mux::open_concrete` hands back the concrete muxer
63+// (the only way to reach `set_page_target_bytes`), so the trait has to be here.
64+use oxideav_core::Muxer as _;
6165
6266 use crate::audio::{AudioMeta, AudioSession};
6367 use crate::demux::{Demuxer, VideoMeta};
@@ -112,10 +116,12 @@ const HEVC_QP_MAX: i32 = 40;
112116 /// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in
113117 /// Matroska or in mp4, the user's pick of container -- are the *video* pairs
114118 /// with both an encoder and a decoder under this project's no-install rule, and
115-/// WAV, FLAC and MP3 are the standalone audio formats with a pure-Rust encoder:
116-/// `hound`, `flacenc` and `rusty_mp3`. Vorbis and Opus have none. (AAC does --
117-/// `rusty_aac`, which is what a re-encoded video track's sound leaves through --
118-/// but AAC is a container's own audio, never a file of its own here.) VP9 is the
119+/// WAV, FLAC, MP3 and Ogg Vorbis are the standalone audio formats with a
120+/// pure-Rust encoder: `hound`, `flacenc`, `rusty_mp3` and `rusty_vorbis`. Opus
121+/// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec.
122+/// (AAC has one too -- `rusty_aac`, which is what a re-encoded video track's
123+/// sound leaves through -- but AAC is a container's own audio, never a file of
124+/// its own here.) VP9 is the
119125 /// one codec left that comes in through the plugin and stops there, HEVC having
120126 /// gained an encoder (an intra-only one, which the rows say). A front-end says
121127 /// so rather than hiding the row.
@@ -155,6 +161,11 @@ pub enum Format {
155161 /// The audio lanes alone, MPEG-1 Layer III CBR (`rusty_mp3`) at the rate
156162 /// [`ExportSettings::audio_kbps`] asks for.
157163 Mp3,
164+ /// The audio lanes alone, Vorbis I in an Ogg container -- `rusty_vorbis`
165+ /// encoding, `oxideav-ogg` paging. Quality-coded and not rate-coded, which
166+ /// is why [`audio_rate_refusal`] takes the Sound row away here: see
167+ /// [`VORBIS_QUALITY`] for the operating point and how it was measured.
168+ Ogg,
158169 }
159170
160171 impl Format {
@@ -167,6 +178,7 @@ impl Format {
167178 Self::Wav => "wav",
168179 Self::Flac => "flac",
169180 Self::Mp3 => "mp3",
181+ Self::Ogg => "ogg",
170182 }
171183 }
172184
@@ -203,6 +215,7 @@ impl Format {
203215 Self::Wav => "a WAV",
204216 Self::Flac => "a FLAC",
205217 Self::Mp3 => "an MP3",
218+ Self::Ogg => "an Ogg Vorbis",
206219 }
207220 }
208221 }
@@ -493,6 +506,7 @@ fn audio_label(
493506 Format::Wav => "PCM · SW (hound)",
494507 Format::Flac => "FLAC · SW (flacenc)",
495508 Format::Mp3 => "MP3 · SW (rusty_mp3)",
509+ Format::Ogg => "Vorbis · SW (rusty_vorbis)",
496510 _ => match copied.unwrap_or(!forces_encode(project)) {
497511 true => "AAC copy",
498512 false => "AAC · SW encode (rusty_aac)",
@@ -519,6 +533,13 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static
519533 match format {
520534 _ if !has_sound(project) => Some("no sound to write"),
521535 Format::Wav | Format::Flac => Some("lossless — the samples themselves, at no rate"),
536+ // Vorbis has a quality knob and no rate knob, and the two are not the
537+ // same control wearing different words: measured across this suite's
538+ // fixtures, the whole usable quality band lands between 55 and 175 kbps
539+ // ([`VORBIS_QUALITY`]), so two of the four rates on offer here are not
540+ // rates it can reach at all. A live row would print a figure the file
541+ // does not hold, which is the one thing this card is built not to do.
542+ Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"),
522543 Format::Mp3 => None,
523544 _ if forces_encode(project) => None,
524545 _ => Some("the source's own packets are copied — at the rate they hold"),
@@ -694,7 +715,7 @@ fn encode_audio(
694715 };
695716 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
696717 format!(
697- "{} Hz is not an AAC sample rate: export WAV, FLAC or MP3, which write it as \
718+ "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \
698719 it is",
699720 audio.sample_rate
700721 )
@@ -1069,6 +1090,7 @@ fn run_audio(
10691090 Format::Wav => write_wav(out, &samples, &audio)?,
10701091 Format::Flac => write_flac(out, &samples, &audio)?,
10711092 Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?,
1093+ Format::Ogg => write_ogg(out, &samples, &audio)?,
10721094 _ => unreachable!("the picture formats are `run`"),
10731095 }
10741096 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
@@ -1131,6 +1153,171 @@ fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate
11311153 Ok(())
11321154 }
11331155
1156+/// The Vorbis quality every `.ogg` this program writes is coded at, on
1157+/// `rusty_vorbis`'s normalised `[0, 1]` scale -- about `-q 8.35` on the scale
1158+/// Vorbis itself is spoken in (`quality01_from_vorbis_q`).
1159+///
1160+/// A measured number, not a taste. The 2026-08-11 bench encoded three of this
1161+/// suite's fixtures (`test_tone_48k.wav`, `test_av.mp4`, `test_tone.mp3`) at
1162+/// every quality from 0.40 to 0.95 and decoded each back with **symphonia** --
1163+/// an independent decoder, and the very one [`crate::audio`] reopens an export
1164+/// with. Two things came out of it:
1165+///
1166+/// * **Below 0.50 the encoder is quiet, not just coarse.** The decoded RMS
1167+/// against the source's runs 0.83-0.94 at quality 0.40 (a 1 to 1.6 dB level
1168+/// error), and at 0.10 and below the file decodes to near-silence -- the same
1169+/// class of failure the AC-3 mono downmix has in `crate::audio`. From 0.55 up
1170+/// the level sits at 1.000-1.009, which is what a lossy codec should do.
1171+/// * **The band tops out well under the rates the Sound row offers.** Quality
1172+/// 0.85 measured 176, 144 and 148 kbps on the three fixtures; 0.95 only
1173+/// reaches ~200. That is why [`audio_rate_refusal`] takes the row away rather
1174+/// than mapping 128/192/256/320 onto quality steps: the top two are numbers
1175+/// this encoder cannot produce, and a card that printed them would be lying.
1176+///
1177+/// 0.85 is the top of the band where every fixture still decoded to *exactly*
1178+/// its own length (0.95 overshot one by 820 samples), which is the property
1179+/// [`write_ogg`] is built around.
1180+const VORBIS_QUALITY: f32 = 0.85;
1181+
1182+/// The Vorbis block hop, and the size of the pre-roll [`write_ogg`] feeds the
1183+/// encoder. `rusty_vorbis` emits long blocks only (`N = 2048`, hop `N/2`).
1184+const VORBIS_HOP: usize = 1024;
1185+
1186+/// The same samples as Vorbis I in an Ogg container: `rusty_vorbis` encodes,
1187+/// `oxideav-ogg` pages. Pure Rust on both halves, like every other encoder here.
1188+///
1189+/// Two corrections stand between that library pair and a file this project would
1190+/// ship, and both are measured rather than guessed (2026-08-11, decoded back
1191+/// with symphonia every time):
1192+///
1193+/// 1. **One hop of pre-roll.** `rusty_vorbis` advances the granule by a full hop
1194+/// on its *first* audio packet, which its own doc comment says decodes to
1195+/// zero samples. Written straight through, every sample lands ~1024 early:
1196+/// a marker signal whose only energy was its first and last 1024 samples came
1197+/// back with the head at 36% of its amplitude and a full-scale burst 1500
1198+/// samples *before* the real one, in what should have been silence. Feeding
1199+/// [`VORBIS_HOP`] samples of silence ahead of the mix and subtracting the same
1200+/// from every granule puts it back: head 0.86 against an input peak of 0.80,
1201+/// the phantom burst down to 0.04, the real burst at its own place. The
1202+/// decoder drops the pre-roll itself -- a first page whose granule is under
1203+/// what its packets decode to is exactly how Ogg says "skip this much".
1204+/// 2. **The tail is declared, not encoded.** The block grid overshoots the last
1205+/// sample, so the stream is padded out and the *last* page's granule is set
1206+/// to the timeline's own frame count. A decoder trims to it, which is what
1207+/// makes an `.ogg` here exactly as long as the WAV of the same timeline --
1208+/// the promise [`run_audio`] makes for every other audio format.
1209+///
1210+/// **Stereo, always.** The embedded setup header `rusty_vorbis` ships is a
1211+/// stereo profile: a mono push is refused outright ("bad coupling channels"),
1212+/// and so is anything wider. A mono mix is therefore written as dual mono, both
1213+/// channels bit-identical (measured: `max|L-R|` is exactly 0, and Vorbis's own
1214+/// channel coupling codes the empty side channel for almost nothing). Wider than
1215+/// stereo cannot reach here -- [`crate::audio`] folds 5.1 to stereo when the
1216+/// source is opened -- but it is refused by name rather than left to the
1217+/// library's own message.
1218+///
1219+/// ponytail: one quality, [`VORBIS_QUALITY`], with no user control -- the Sound
1220+/// row is refused for this format because the rates it offers are not rates
1221+/// Vorbis reaches. Upgrade path is a quality picker of its own, worth building
1222+/// the day the card has a control that speaks in quality rather than kbps.
1223+fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
1224+ if audio.channels > 2 {
1225+ return Err(format!(
1226+ "Ogg Vorbis is written in stereo here and this mix has {} channels",
1227+ audio.channels
1228+ )
1229+ .into());
1230+ }
1231+ // The mp3 path's conversion, so the two files are one mix, plus the pre-roll
1232+ // and (for a mono mix) the dual-mono widening: the same sample in both
1233+ // channels is the same signal, not a widening of it, so what a player folds
1234+ // back down is what was mixed.
1235+ let mut pcm: Vec<i16> = vec![0; VORBIS_HOP * 2];
1236+ match audio.channels < 2 {
1237+ true => pcm.extend(samples.iter().flat_map(|&s| [s as i16, s as i16])),
1238+ false => pcm.extend(samples.iter().map(|&s| s as i16)),
1239+ }
1240+ // The block grid has to run past the last real sample or the tail is never
1241+ // coded at all; the granule below is what trims the padding back off.
1242+ let frames = samples.len() / usize::from(audio.channels).max(1);
1243+ pcm.resize(pcm.len() + VORBIS_HOP * 4 * 2, 0);
1244+
1245+ let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
1246+ bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
1247+ quality: VORBIS_QUALITY,
1248+ });
1249+ encoder
1250+ .push_pcm_s16(&pcm, 2, audio.sample_rate)
1251+ .map_err(|e| format!("vorbis encode: {e}"))?;
1252+ encoder.finish();
1253+ let mut packets = Vec::new();
1254+ loop {
1255+ match encoder.next_packet() {
1256+ Ok(packet) => packets.push(packet),
1257+ Err(rusty_vorbis::Error::Eof) => break,
1258+ Err(e) => return Err(format!("vorbis encode: {e}").into()),
1259+ }
1260+ }
1261+ // Identification, comment and setup, then at least one audio packet: fewer
1262+ // than four and there is no stream to page.
1263+ if packets.len() < 4 {
1264+ return Err(format!("vorbis encode: {} packets is not a stream", packets.len()).into());
1265+ }
1266+ let headers = [
1267+ &packets[0].data[..],
1268+ &packets[1].data[..],
1269+ &packets[2].data[..],
1270+ ];
1271+ let extradata = oxideav_ogg::mux::xiph_lace(&headers)
1272+ .ok_or("vorbis encode: the three headers would not lace")?;
1273+
1274+ let time_base = oxideav_core::TimeBase::new(1, i64::from(audio.sample_rate));
1275+ let mut params = oxideav_core::CodecParameters::audio(oxideav_core::CodecId::new("vorbis"));
1276+ params.sample_rate = Some(audio.sample_rate);
1277+ params.channels = Some(2);
1278+ params.extradata = extradata;
1279+ let stream = oxideav_core::StreamInfo {
1280+ index: 0,
1281+ time_base,
1282+ duration: Some(frames as i64),
1283+ start_time: Some(0),
1284+ params,
1285+ };
1286+ let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(File::create(out)?), &[stream])
1287+ .map_err(|e| format!("ogg mux: {e:?}"))?;
1288+ // Without this every audio packet of a short export lands on one page, and
1289+ // the muxer's own note records what that costs: a first-audio-page-is-also-
1290+ // EOS stream decodes short by half a small block in a reference decoder.
1291+ muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES));
1292+ muxer
1293+ .write_header()
1294+ .map_err(|e| format!("ogg mux: {e:?}"))?;
1295+ let last = packets.len() - 1;
1296+ for (i, packet) in packets.iter().enumerate().skip(3) {
1297+ // Correction 1 on every packet, correction 2 on the last one.
1298+ let granule = match i == last {
1299+ true => frames as i64,
1300+ false => (packet.pts - VORBIS_HOP as i64).max(0),
1301+ };
1302+ muxer
1303+ .write_packet(
1304+ &oxideav_core::Packet::new(0, time_base, packet.data.clone())
1305+ .with_pts(granule)
1306+ .with_duration(packet.duration),
1307+ )
1308+ .map_err(|e| format!("ogg mux: {e:?}"))?;
1309+ }
1310+ muxer
1311+ .write_trailer()
1312+ .map_err(|e| format!("ogg mux: {e:?}"))?;
1313+ Ok(())
1314+}
1315+
1316+/// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533
1317+/// describes pages as "usually 4-8 kB", which is also the muxer's own suggested
1318+/// general-purpose value.
1319+const OGG_PAGE_BYTES: usize = 4096;
1320+
11341321 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
11351322 /// text: they are not `Send + Sync`, and every one of them fails the export the
11361323 /// same way.
crates/engine/tests/audio_export.rsmodified+149 -4
@@ -141,7 +141,12 @@ fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 {
141141 /// timeline, silent where the timeline is empty, and audible where it is not --
142142 /// with the fixtures' 1 Hz pulse still in it, which is what says the samples are
143143 /// the *edit's* and not just noise of the right length.
144-fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) {
144+///
145+/// `gap_ceiling` is how loud the hole in the middle may be as a fraction of the
146+/// first second: `0.0` for a lossless format, where the silence is the samples
147+/// themselves, and a real fraction for a lossy one, where a block straddling the
148+/// cut rings into it. Never an absolute level -- the fixtures peak around 0.12.
149+fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32], gap_ceiling: f64) {
145150 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded");
146151 let channels = usize::from(meta.channels);
147152 // Three seconds of timeline, to the sample: the segments round their own
@@ -163,7 +168,10 @@ fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) {
163168 println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}");
164169 assert!(av > 0.01, "the first second is audible");
165170 assert!(tone > 0.01, "the mp3 second is audible");
166- assert_eq!(gap, 0.0, "the gap is exact silence");
171+ assert!(
172+ gap <= av * gap_ceiling,
173+ "the gap is silence: {gap:.6} against {av:.4} of first second"
174+ );
167175
168176 // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at
169177 // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level.
@@ -223,7 +231,7 @@ fn exports_the_timeline_as_a_wav() {
223231 assert!(!part_path(&out).exists(), "the .part was renamed away");
224232
225233 let (meta, samples) = decode(&out);
226- assert_timeline_shape(&meta, &samples);
234+ assert_timeline_shape(&meta, &samples, 0.0);
227235 assert_wav_header(&out, samples.len() / usize::from(meta.channels));
228236 std::fs::remove_file(&out).unwrap();
229237 }
@@ -248,7 +256,7 @@ fn exports_the_timeline_as_a_flac() {
248256 // Lossless is a claim about the samples, so it is checked on the samples:
249257 // the same shape the WAV of the same timeline has.
250258 let (meta, samples) = decode(&out);
251- assert_timeline_shape(&meta, &samples);
259+ assert_timeline_shape(&meta, &samples, 0.0);
252260 // Smaller than the PCM it encodes, or the whole point of the row is gone.
253261 let pcm = samples.len() * 2;
254262 println!("flac {} bytes for {pcm} bytes of PCM", bytes.len());
@@ -814,3 +822,140 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
814822 assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}");
815823 std::fs::remove_file(&out).unwrap();
816824 }
825+
826+/// The fourth audio row, and the one that used to be a refusal: Vorbis in an Ogg
827+/// container, `rusty_vorbis` encoding and `oxideav-ogg` paging, read straight
828+/// back through the engine's own reader like every other export here.
829+///
830+/// The shape is asserted *exactly* -- `assert_timeline_shape`, the same the WAV
831+/// and the FLAC are held to, and not the MP3's within-a-frame slack. That is the
832+/// whole point of the two corrections in `export::write_ogg`: the encoder's own
833+/// granule numbering puts every sample a block early and its block grid overruns
834+/// the tail, so written straight through, this file would be a hop out of step
835+/// and short of the timeline. The 1 Hz pulse is what proves the *timing* rather
836+/// than merely the length -- a stream shifted by a block lands its peak nearer
837+/// where the dip belongs.
838+#[test]
839+fn exports_the_timeline_as_an_ogg_vorbis() {
840+ let out = out_path("ogg", "ogg");
841+ let handle = engine::export::start(
842+ mixed_project(),
843+ meta(),
844+ &out,
845+ &ExportSettings {
846+ format: Format::Ogg,
847+ ..Default::default()
848+ },
849+ );
850+ wait(&handle, Duration::from_secs(180)).expect("ogg export");
851+ assert_eq!(handle.progress(), 1.0, "finished at full progress");
852+ assert!(!part_path(&out).exists(), "the .part was renamed away");
853+
854+ let bytes = std::fs::read(&out).expect("read the ogg back");
855+ assert_eq!(&bytes[0..4], b"OggS", "an Ogg stream, by its own magic");
856+ // Lossy, so a block straddling the cut rings into the hole: the same
857+ // 1/20-of-the-signal bar the MP3 row is held to.
858+ let (meta, samples) = decode(&out);
859+ assert_timeline_shape(&meta, &samples, 0.05);
860+ // Lossy, so it had better be well under the PCM it stands for: the
861+ // 2026-08-11 bench measured 144-176 kbps across this suite's fixtures at
862+ // this quality, against 1411 kbps of 44.1 kHz stereo PCM.
863+ let pcm = samples.len() * 2;
864+ println!("ogg {} bytes for {pcm} bytes of PCM", bytes.len());
865+ assert!(bytes.len() < pcm / 4, "lossy: {} vs {pcm}", bytes.len());
866+ std::fs::remove_file(&out).unwrap();
867+}
868+
869+/// A **mono** timeline through the same door. `rusty_vorbis` ships one embedded
870+/// setup header and it is a stereo profile -- a mono push is refused outright
871+/// ("bad coupling channels") -- so `export::write_ogg` writes the mix as dual
872+/// mono. This is the test that it is *dual mono* and not a widening: both
873+/// channels come back bit-identical, so folding the file back down gives exactly
874+/// what was mixed.
875+#[test]
876+fn a_mono_timeline_exports_as_dual_mono_ogg() {
877+ // A mono fixture, written here because the suite has none: one second of
878+ // 440 Hz at -6 dBFS, 44.1 kHz, as plain a RIFF header as hound writes.
879+ let src = out_path("mono_src", "wav");
880+ let frames = RATE as usize;
881+ let data = (frames * 2) as u32;
882+ let mut wav = Vec::with_capacity(44 + frames * 2);
883+ wav.extend_from_slice(b"RIFF");
884+ wav.extend_from_slice(&(36 + data).to_le_bytes());
885+ wav.extend_from_slice(b"WAVEfmt ");
886+ wav.extend_from_slice(&16u32.to_le_bytes());
887+ wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
888+ wav.extend_from_slice(&1u16.to_le_bytes()); // one channel
889+ wav.extend_from_slice(&RATE.to_le_bytes());
890+ wav.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate
891+ wav.extend_from_slice(&2u16.to_le_bytes()); // block align
892+ wav.extend_from_slice(&16u16.to_le_bytes());
893+ wav.extend_from_slice(b"data");
894+ wav.extend_from_slice(&data.to_le_bytes());
895+ for i in 0..frames {
896+ let t = i as f64 / f64::from(RATE);
897+ let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
898+ wav.extend_from_slice(&s.to_le_bytes());
899+ }
900+ std::fs::write(&src, &wav).expect("write the mono fixture");
901+
902+ let project = Project::from_parts(
903+ vec![Source::new(src.clone(), 0)],
904+ vec![(
905+ LaneKind::Audio,
906+ vec![Clip {
907+ start: 0,
908+ in_frame: 0,
909+ out_frame: 30,
910+ source: 0,
911+ link: None,
912+ eq: None,
913+ color: None,
914+ fit: FitPolicy::default(),
915+ speed: Speed::NORMAL,
916+ }],
917+ )],
918+ Vec::new(),
919+ Vec::new(),
920+ )
921+ .expect("a one-source mono project");
922+
923+ let out = out_path("mono", "ogg");
924+ let handle = engine::export::start(
925+ project,
926+ meta(),
927+ &out,
928+ &ExportSettings {
929+ format: Format::Ogg,
930+ ..Default::default()
931+ },
932+ );
933+ wait(&handle, Duration::from_secs(180)).expect("ogg export of a mono timeline");
934+
935+ let (meta, samples) = decode(&out);
936+ assert_eq!(meta.channels, 2, "written as stereo, since Vorbis must be");
937+ assert_eq!(meta.sample_rate, RATE);
938+ // One second of clip, to the sample: the mono path gets the same trim the
939+ // stereo one does.
940+ assert_eq!(
941+ samples.len() / 2,
942+ RATE as usize,
943+ "one second, to the sample"
944+ );
945+ let worst = samples
946+ .chunks_exact(2)
947+ .map(|lr| f64::from(lr[0] - lr[1]).abs())
948+ .fold(0.0f64, f64::max);
949+ println!("dual mono: worst |L-R| = {worst:e}");
950+ assert_eq!(worst, 0.0, "both channels are the same signal, to the bit");
951+ let energy = (samples
952+ .iter()
953+ .map(|s| f64::from(*s) * f64::from(*s))
954+ .sum::<f64>()
955+ / samples.len() as f64)
956+ .sqrt();
957+ println!("dual mono rms {energy:.4} (the source's own is 0.354)");
958+ assert!(energy > 0.25, "the mono export is silence: RMS {energy:.6}");
959+ std::fs::remove_file(&out).unwrap();
960+ std::fs::remove_file(&src).unwrap();
961+}
crates/engine/tests/backends.rsmodified+1 -1
@@ -163,7 +163,7 @@ fn the_planned_encoders_are_the_ones_the_job_opens() {
163163 /// export is not a progress line with nothing to say.
164164 #[test]
165165 fn an_audio_only_job_names_its_encoder() {
166- for format in [Format::Wav, Format::Flac, Format::Mp3] {
166+ for format in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg] {
167167 audio_only_job_names_its_encoder(format);
168168 }
169169 }