forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(T4): every export carries its sound — mp3, av1-in-mp4, refusals lifted

Browse files at this commit

59c74e83c640928ca0cfbafc33965a6bb004de4dAhmet Kaan GümüşParent: e9589fbcf10a7c

16 changed files +1399 -462

Cargo.lockmodified+7 -0
@@ -1640,6 +1640,7 @@ dependencies = [
16401640 "rav1e",
16411641 "rusty_aac",
16421642 "rusty_h264",
1643+ "rusty_mp3",
16431644 "symphonia",
16441645 "symphonia-codec-aac",
16451646 "symphonia-core",
@@ -4924,6 +4925,12 @@ dependencies = [
49244925 "rusty_h264-common",
49254926 ]
49264927
4928+[[package]]
4929+name = "rusty_mp3"
4930+version = "0.6.1"
4931+source = "registry+https://github.com/rust-lang/crates.io-index"
4932+checksum = "a99f339ec9a2d84eec8fc2a42baa92426966b25238c498e79d57b4e49b14fbad"
4933+
49274934 [[package]]
49284935 name = "rustybuzz"
49294936 version = "0.14.1"
crates/app/src/keymap.rsmodified+2 -2
@@ -337,8 +337,8 @@ pub const FIXED: [Fixed; 16] = [
337337 category: Category::File,
338338 },
339339 Fixed {
340- chord: "m / a / w / f",
341- label: "Pick the export format: MP4, AV1, WAV or FLAC",
340+ chord: "m / a / v / w / f / p",
341+ label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, WAV, FLAC or MP3",
342342 category: Category::File,
343343 },
344344 Fixed {
crates/app/src/main.rsmodified+137 -115
@@ -2090,7 +2090,15 @@ impl Player {
20902090 return;
20912091 };
20922092 let settings = export_settings(self.quality, self.custom_mbps, self.format);
2093- if !self.export_open || !settings.format.has_video() {
2093+ if !self.export_open {
2094+ return;
2095+ }
2096+ // A format with no picture has no seat to probe -- and the *last*
2097+ // format's is not its answer: cleared rather than left standing, or
2098+ // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW
2099+ // (rusty_mp3)", which names an encoder that will not run.
2100+ if !settings.format.has_video() {
2101+ self.export_seat = None;
20942102 return;
20952103 }
20962104 let meta = *session.meta();
@@ -4710,7 +4718,7 @@ impl Player {
47104718 let formats: Vec<_> = FORMATS
47114719 .into_iter()
47124720 .enumerate()
4713- .map(|(i, (format, label, detail))| {
4721+ .map(|(i, (format, _, label, detail))| {
47144722 // Per row, because the two picture formats are refused by
47154723 // different things: an audio-only timeline greys both, a second
47164724 // audio lane only the mp4.
@@ -4794,7 +4802,7 @@ impl Player {
47944802 .text_size(px(11.))
47954803 .text_color(rgb(INK_DIM))
47964804 .child(self.notice.clone().unwrap_or_else(|| {
4797- "pick a format (m/a/w/f), then Export — esc closes".into()
4805+ "pick a format (m/a/v/w/f/p), then Export — esc closes".into()
47984806 })),
47994807 )
48004808 // Capped and scrolling like the keybindings list: the
@@ -6927,48 +6935,67 @@ impl Quality {
69276935 }
69286936 }
69296937
6930-/// The export card's format rows: what this program can write, and what it
6931-/// cannot with the reason it cannot. A format with no entry at all would read
6932-/// as an oversight, and a menu of three as a claim that nothing else exists --
6933-/// so the refusals are rows too, dimmed and unclickable.
6938+/// The export card's format rows: the key that picks one, its name, and what it
6939+/// writes -- or, where this program cannot write it, the reason it cannot. A
6940+/// format with no entry at all would read as an oversight, and a menu of three
6941+/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
6942+/// and unclickable.
69346943 ///
6935-/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a
6936-/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a
6937-/// decision about this project rather than about the code, and the row says so
6938-/// instead of pretending the encoder does not exist. HEVC and VP9 are the two
6939-/// this program *reads* and cannot write -- the plugin decodes both and there is
6940-/// no encoder for either here -- so they are rows for the same reason: a codec
6941-/// that opens but never comes back out is exactly the gap a user would other-
6942-/// wise go looking for.
6943-const FORMATS: [(Option<Format>, &str, &str); 9] = [
6944- (Some(Format::Mp4), "MP4", "H.264 picture + AAC sound"),
6944+/// `None` is exactly that kind of row, and there are three left. MP3 stopped
6945+/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
6946+/// `shine-rs` was the licence question, and it is not the only encoder any
6947+/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the
6948+/// plugin decodes both and there is no encoder for either here -- so they are
6949+/// rows for the same reason: a codec that opens but never comes back out is
6950+/// exactly the gap a user would otherwise go looking for. AAC is not a row at
6951+/// all: it is what both containers' sound *is*, never a file of its own.
6952+///
6953+/// AV1 is two rows because a codec and a container are two choices: the same
6954+/// picture and the same AAC track go into a Matroska file or into an mp4, and
6955+/// which one a user needs is about what has to play the file, not about the
6956+/// encode.
6957+const FORMATS: [(Option<Format>, &str, &str, &str); 9] = [
6958+ (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"),
69456959 (
69466960 Some(Format::Av1),
6947- "AV1",
6948- "AV1 picture in .mkv — no sound: export WAV or FLAC for that",
6961+ "a",
6962+ "AV1 · MKV",
6963+ "AV1 picture + AAC sound in .mkv",
6964+ ),
6965+ (
6966+ Some(Format::Av1Mp4),
6967+ "v",
6968+ "AV1 · MP4",
6969+ "the same AV1 picture and sound in .mp4",
6970+ ),
6971+ (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"),
6972+ (Some(Format::Flac), "f", "FLAC", "lossless — audio only"),
6973+ (
6974+ Some(Format::Mp3),
6975+ "p",
6976+ "MP3",
6977+ "MPEG-1 Layer III, 256 kbps — audio only",
69496978 ),
6950- (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),
6951- (Some(Format::Flac), "FLAC", "lossless — audio only"),
6952- (None, "MP3", "encoder is LGPL — licence decision pending"),
6953- (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),
6954- (None, "AAC", "an MP4's sound here, not a file of its own"),
6979+ (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"),
69556980 (
69566981 None,
6982+ "",
69576983 "HEVC",
69586984 "no encoder in this stack, and patent-encumbered",
69596985 ),
6960- (None, "VP9", "superseded by AV1, which is the row above"),
6986+ (None, "", "VP9", "superseded by AV1, which is the row above"),
69616987 ];
69626988
6963-/// The format a key picks while the export card is up: the row's own initial,
6964-/// which is unambiguous across the three that can be picked. `None` for
6965-/// everything else, digits included -- those are the bitrate's.
6989+/// The format a key picks while the export card is up. A letter of the row's
6990+/// own name, spelled out in the table rather than taken from the initial: `MP4`
6991+/// and `MP3` share one, and so do the two AV1 containers, so an initial cannot
6992+/// tell six rows apart. Never a digit -- those are the bitrate's. `None` for
6993+/// everything else, the rows that cannot be picked included.
69666994 fn format_key(key: &str) -> Option<Format> {
69676995 FORMATS
69686996 .into_iter()
6969- .filter_map(|(format, label, _)| format.zip(label.get(..1)))
6970- .find(|(_, initial)| initial.eq_ignore_ascii_case(key))
6971- .map(|(format, _)| format)
6997+ .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key))
6998+ .find_map(|(format, ..)| format)
69726999 }
69737000
69747001 /// What one of the colour card's own strokes does. Its keys are card-local --
@@ -7138,9 +7165,11 @@ fn export_line(
71387165 fn format_line(format: Format) -> &'static str {
71397166 match format {
71407167 Format::Mp4 => "H.264 · MP4 · moov at end",
7141- Format::Av1 => "AV1 · Matroska · picture only, no audio track",
7168+ Format::Av1 => "AV1 · Matroska · picture and sound",
7169+ Format::Av1Mp4 => "AV1 · MP4 · picture and sound",
71427170 Format::Wav => "16-bit PCM · WAV · timeline audio only",
71437171 Format::Flac => "FLAC · lossless · timeline audio only",
7172+ Format::Mp3 => "MP3 · 256 kbps · timeline audio only",
71447173 }
71457174 }
71467175
@@ -7150,7 +7179,7 @@ fn format_label(format: Format) -> &'static str {
71507179 FORMATS
71517180 .iter()
71527181 .find(|(row, ..)| *row == Some(format))
7153- .map_or("EXPORT", |(_, label, _)| *label)
7182+ .map_or("EXPORT", |(_, _, label, _)| *label)
71547183 }
71557184
71567185 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
@@ -7270,11 +7299,12 @@ fn is_bare_modifier(key: &str) -> bool {
72707299 /// refuses it too (`export::start`); this is what greys the row before a
72717300 /// destination has been picked.
72727301 ///
7273-/// The second reason is the mp4 path's alone: it *copies* one AAC track and
7274-/// there is no encoder here to mix several with, so a timeline whose sound is
7275-/// spread over more than one audio lane is refused by the engine
7276-/// (`export::run`). An AV1 export carries no sound at all -- said on its row as
7277-/// its detail, not as a refusal -- so no count of audio lanes stops it.
7302+/// It is the *only* reason left. A second audio lane, a speeded clip, a source
7303+/// no mp4 sample table holds: each of those used to grey the MP4 row, because
7304+/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
7305+/// cannot say what the timeline says (`export::copy_audio`), so none of them is
7306+/// a refusal any more -- and every video format carries the sound, so there is
7307+/// nothing here that is one format's alone.
72787308 fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
72797309 if !format.has_video() {
72807310 return None;
@@ -7283,43 +7313,13 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
72837313 .lanes()
72847314 .into_iter()
72857315 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
7286- if !picture {
7287- return Some(format!(
7288- "no picture — {} would be black; export WAV or FLAC",
7316+ match picture {
7317+ true => None,
7318+ false => Some(format!(
7319+ "no picture — {} would be black; export WAV, FLAC or MP3",
72897320 format.name()
7290- ));
7291- }
7292- if format != Format::Mp4 {
7293- return None;
7321+ )),
72947322 }
7295- let audio: Vec<Lane> = session
7296- .lanes()
7297- .into_iter()
7298- .filter(|&lane| lane.kind == LaneKind::Audio && !session.lane_clips(lane).is_empty())
7299- .collect();
7300- if audio.len() > 1 {
7301- return Some(format!("{} audio lanes — an mp4 copies one", audio.len()));
7302- }
7303- // ...and the third reason, the same path's: a copied AAC packet carries no
7304- // rate, so a speeded clip on the lane being copied would come back at 1.00x
7305- // under a picture the export *does* re-time. The engine refuses it by name
7306- // (`export::copy_audio`); this greys the row before anyone picks a
7307- // destination. The picture's own rate is no reason at all -- the export walk
7308- // honours that -- so only this one lane is asked.
7309- audio
7310- .first()
7311- .and_then(|&lane| {
7312- session
7313- .lane_clips(lane)
7314- .iter()
7315- .find(|c| !c.speed.is_normal())
7316- })
7317- .map(|c| {
7318- format!(
7319- "sound at {} — an mp4 copies packets, which carry no rate",
7320- c.speed
7321- )
7322- })
73237323 }
73247324
73257325 /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap
@@ -8302,14 +8302,19 @@ mod tests {
83028302 // and are never refused.
83038303 assert_eq!(
83048304 format_refusal(&session, Format::Mp4).as_deref(),
8305- Some("no picture — an mp4 would be black; export WAV or FLAC")
8305+ Some("no picture — an mp4 would be black; export WAV, FLAC or MP3")
83068306 );
83078307 assert_eq!(
83088308 format_refusal(&session, Format::Av1).as_deref(),
8309- Some("no picture — an AV1 export would be black; export WAV or FLAC")
8309+ Some("no picture — an AV1 Matroska would be black; export WAV, FLAC or MP3")
8310+ );
8311+ assert_eq!(
8312+ format_refusal(&session, Format::Av1Mp4).as_deref(),
8313+ Some("no picture — an AV1 mp4 would be black; export WAV, FLAC or MP3")
83108314 );
83118315 assert_eq!(format_refusal(&session, Format::Wav), None);
83128316 assert_eq!(format_refusal(&session, Format::Flac), None);
8317+ assert_eq!(format_refusal(&session, Format::Mp3), None);
83138318 }
83148319
83158320 fn info(
@@ -9061,28 +9066,24 @@ mod tests {
90619066 assert!(session.lane_clips(v2).is_empty());
90629067 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
90639068
9064- // A second audio lane carrying sound is what an mp4 export cannot
9065- // write, so the card greys that row before a destination is picked.
9069+ // A second audio lane used to be what an mp4 export could not write --
9070+ // it copied one AAC track and a mix is not a copy. It mixes now
9071+ // (`export::copy_audio`), so no row is greyed by a count of lanes.
90669072 assert_eq!(format_refusal(&session, Format::Mp4), None);
90679073 let a2 = session.add_lane(LaneKind::Audio);
90689074 assert_eq!(a2.label(), "A2");
9069- assert_eq!(
9070- format_refusal(&session, Format::Mp4),
9071- None,
9072- "an empty lane carries nothing"
9073- );
90749075 assert!(
90759076 session
90769077 .place_stream_at(0.0, &path, 0, Some(a2))
90779078 .expect("its own file is on this timeline")
90789079 );
9079- assert_eq!(
9080- format_refusal(&session, Format::Mp4).as_deref(),
9081- Some("2 audio lanes — an mp4 copies one")
9082- );
9083- // ...and the one thing that does not stop an AV1 export, which carries
9084- // no sound to have too much of.
9085- assert_eq!(format_refusal(&session, Format::Av1), None);
9080+ for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
9081+ assert_eq!(
9082+ format_refusal(&session, format),
9083+ None,
9084+ "two audio lanes are a mix, not a refusal"
9085+ );
9086+ }
90869087
90879088 // Undo, one edit at a time and backwards: the drop on A2, the lane A2
90889089 // itself, the lift, the drop on V2, and last the lane V2 -- an added
@@ -10241,59 +10242,80 @@ mod tests {
1024110242
1024210243 #[test]
1024310244 fn every_format_row_is_offered_or_says_why_not() {
10244- // The four this program can write are rows that pick. Three are named
10245+ // The six this program can write are rows that pick. Four are named
1024510246 // after their own extension, so a destination cannot disagree with its
10246- // bytes; the fourth is named after its *codec*, because AV1 arrives and
10247- // leaves in a Matroska file and "MKV" would name the box rather than
10248- // what is in it.
10247+ // bytes; the AV1 pair is named after codec *and* container, because the
10248+ // same picture goes into either box and the row is the choice between
10249+ // them.
1024910250 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();
1025010251 assert_eq!(
1025110252 offered,
10252- vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac]
10253+ vec![
10254+ Format::Mp4,
10255+ Format::Av1,
10256+ Format::Av1Mp4,
10257+ Format::Wav,
10258+ Format::Flac,
10259+ Format::Mp3
10260+ ]
1025310261 );
1025410262 assert_eq!(Format::Av1.ext(), "mkv");
10255- for (format, label, _) in FORMATS {
10263+ assert_eq!(Format::Av1Mp4.ext(), "mp4");
10264+ for (format, _, label, _) in FORMATS {
1025610265 match format {
10257- Some(Format::Av1) => assert_eq!(label, "AV1"),
10266+ Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"),
10267+ Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"),
1025810268 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
1025910269 // A refused format is a row with a reason, never a hidden one:
1026010270 // an empty detail column would read as an oversight.
1026110271 None => assert!(!label.is_empty()),
1026210272 }
1026310273 }
10264- for (format, label, detail) in FORMATS {
10274+ for (format, stroke, label, detail) in FORMATS {
1026510275 assert!(!detail.is_empty(), "{label} says nothing");
10266- // Only the two picture formats leave the bitrate rows live -- the
10267- // card dims them off exactly this.
10276+ // Only the picture formats leave the bitrate rows live -- the card
10277+ // dims them off exactly this.
1026810278 assert_eq!(
1026910279 format.is_some_and(Format::has_video),
10270- matches!(format, Some(Format::Mp4 | Format::Av1))
10280+ matches!(format, Some(Format::Mp4 | Format::Av1 | Format::Av1Mp4))
1027110281 );
10282+ // Every row that can be picked has a key of its own, and no two
10283+ // share one: the card is drivable without a pointer.
10284+ assert_eq!(format.is_some(), !stroke.is_empty(), "{label}");
10285+ if !stroke.is_empty() {
10286+ assert_eq!(format_key(stroke), format, "{label} keys to itself");
10287+ assert!(
10288+ stroke.parse::<u32>().is_err(),
10289+ "{label} takes a digit the bitrate needs"
10290+ );
10291+ }
1027210292 }
1027310293 // The two codecs this program reads and cannot write are rows of their
1027410294 // own, refused by name rather than absent -- HEVC for want of an encoder
1027510295 // (and for its patents), VP9 because AV1 is the row that replaced it.
1027610296 for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {
10277- let (format, _, detail) = FORMATS
10297+ let (format, _, _, detail) = FORMATS
1027810298 .into_iter()
10279- .find(|(_, row, _)| *row == label)
10299+ .find(|(_, _, row, _)| *row == label)
1028010300 .unwrap_or_else(|| panic!("{label} has no row"));
1028110301 assert!(format.is_none(), "{label} is not offered");
1028210302 assert!(detail.contains(word), "{label}: {detail}");
1028310303 }
10284- // The AV1 row says on the row itself that it carries no sound, which is
10285- // the one thing a user could otherwise only find out by playing the file.
10286- let (_, _, av1) = FORMATS
10287- .into_iter()
10288- .find(|(f, ..)| *f == Some(Format::Av1))
10289- .expect("an AV1 row");
10290- assert!(av1.contains("no sound"), "{av1}");
10291- assert!(format_line(Format::Av1).contains("picture only"));
10292- assert_eq!(
10293- format_key("a"),
10294- Some(Format::Av1),
10295- "its own initial picks it"
10296- );
10304+ // Both AV1 rows say they carry sound: the file used to be picture only,
10305+ // and a row that still said so would be the lie a user plays the file
10306+ // to find out about.
10307+ for format in [Format::Av1, Format::Av1Mp4] {
10308+ let (_, _, _, detail) = FORMATS
10309+ .into_iter()
10310+ .find(|(f, ..)| *f == Some(format))
10311+ .expect("an AV1 row");
10312+ assert!(detail.contains("sound"), "{detail}");
10313+ assert!(format_line(format).contains("picture and sound"));
10314+ }
10315+ assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one");
10316+ assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one");
10317+ assert_eq!(format_key("p"), Some(Format::Mp3));
10318+ assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p");
1029710319 // The destination follows the format and keeps the stem, mp4 included.
1029810320 assert_eq!(
1029910321 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
crates/engine/Cargo.tomlmodified+5 -0
@@ -35,6 +35,11 @@ rusty_h264 = { version = "0.8", default-features = false }
3535 # Fraunhofer's C library, which this project's no-install rule forbids. Built
3636 # from `vendor/rusty_aac` -- see the patch table in the workspace manifest.
3737 rusty_aac = "0.5"
38+# The MP3 encoder, so that format is a row a user can pick rather than a licence
39+# note: pure Rust, Apache-2.0, CBR and VBR. The decoder side of mp3 is
40+# symphonia's below -- an mp3 has always been importable here, and until this it
41+# was the one format the editor could read and never write.
42+rusty_mp3 = "0.6"
3843 symphonia-core = "0.6"
3944 symphonia-codec-aac = "0.6"
4045 # The umbrella crate for the standalone audio files: one dependency instead of
crates/engine/src/audio.rsmodified+24 -19
@@ -802,8 +802,9 @@ impl AudioSession {
802802 }
803803
804804 /// One AAC-LC access unit of silence, for the gaps in an exported timeline —
805-/// the export copies packets and has no AAC encoder, so the only silence it can
806-/// write is one spelled out by hand.
805+/// this is the *copy* path, which never encodes anything, so the only silence it
806+/// can write is one spelled out by hand. (The re-encode path next door has a
807+/// real encoder and needs none of this: its gaps are zero samples.)
807808 ///
808809 /// It is the shortest legal `raw_data_block` there is: one element carrying
809810 /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
@@ -848,11 +849,12 @@ fn source_at<'a>(
848849
849850 /// A source's track for the *copy* path, which needs raw AAC access units.
850851 ///
851-/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by
852-/// name and by format rather than exported silent or, worse, exported as noise:
853-/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]),
854-/// so a timeline carrying one of those simply cannot become an mp4 today. The
855-/// wording is what a front-end shows.
852+/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name
853+/// and by format. That is no longer the end of the road: `export::copy_audio`
854+/// takes it as the answer "not copyable" and decodes and re-encodes the timeline
855+/// instead, so these words are a fallback's reason rather than a user's refusal.
856+/// They are still worded for a person, because a caller with no encoder to fall
857+/// back on shows them verbatim.
856858 ///
857859 /// `Ok(None)` for a file with no audio at all, which is a silent export.
858860 fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
@@ -862,16 +864,18 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
862864 // A Matroska source gets its own words: its packets *are* AAC, so
863865 // "export needs AAC audio today" would read as a contradiction. What
864866 // they are not is packets of an mp4 sample table, which is what the
865- // copy walks -- and refusing beats writing a film with no sound in it.
867+ // copy walks. The export decodes such a source and encodes it again
868+ // rather than showing this, so a film's sound reaches an mp4 either way;
869+ // the words stay for a caller that copies and cannot re-encode.
866870 //
867871 // ponytail: the ceiling is the copy path being written against the mp4
868- // reader, not anything about the bytes. Upgrade path is the same one
869- // every other refusal here names -- an AAC encoder, or a `copy_segments`
870- // that walks a Matroska track -- and either would let this through.
872+ // reader, not anything about the bytes. Upgrade path is a
873+ // `copy_segments` that walks a Matroska track, which would make this a
874+ // copy again instead of a re-encode.
871875 Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
872- "{}'s sound is AAC inside a Matroska file, which an mp4 export cannot copy: \
873- it copies packets out of an mp4's own sample table. Export WAV or FLAC for \
874- the sound, or AV1 for the picture alone",
876+ "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \
877+ a copy walks an mp4's own sample table. It is decoded and encoded again \
878+ instead",
875879 path.file_name()
876880 .unwrap_or(path.as_os_str())
877881 .to_string_lossy(),
@@ -879,17 +883,18 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
879883 .into()),
880884 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
881885 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
882- // sample table can hold, and there is no AAC encoder here to turn it
883- // into one. A WAV/FLAC export of the same timeline decodes fine.
886+ // sample table can hold. The export decodes it and encodes AAC, exactly
887+ // as it does for every other source no copy reaches.
884888 Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),
885889 }
886890 }
887891
888-/// The one wording for "this source's audio cannot be copied into an mp4",
889-/// shared by every format that cannot be: a front-end shows it verbatim.
892+/// The one wording for "this source's audio cannot be *copied* into an mp4",
893+/// shared by every format that cannot be. What the export does about it is
894+/// decode and re-encode; this is the reason it had to.
890895 fn uncopyable(path: &Path, codec: &str) -> crate::Error {
891896 format!(
892- "export needs AAC audio today; {} is {codec}",
897+ "a packet copy needs AAC in an mp4; {} is {codec}",
893898 path.file_name()
894899 .unwrap_or(path.as_os_str())
895900 .to_string_lossy(),
crates/engine/src/demux.rsmodified+50 -22
@@ -7,7 +7,10 @@
77 //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --
88 //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in
99 //! practice -- and HEVC rides the same walk, because that is the other codec a
10-//! `.mkv` off a disc arrives in.
10+//! `.mkv` off a disc arrives in. An AV1 *mp4* is read here too, its sample entry
11+//! picked out of the `stsd` by hand for the same reason `mux` writes it by hand:
12+//! this project exports one, and a file this cannot reopen is a file it had no
13+//! business writing.
1114
1215 use std::fs::File;
1316 use std::io::{BufReader, Read, Seek, SeekFrom};
@@ -131,9 +134,9 @@ pub struct Mp4Demuxer {
131134 /// (`audio::priming_samples`), and frame indices count from there.
132135 first_sample: u32,
133136 codec: Codec,
134- /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC),
135- /// re-injected ahead of every sync sample. Empty for VP9, which carries no
136- /// out-of-band parameter sets.
137+ /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or
138+ /// the sequence header OBU for AV1, re-injected ahead of every sync sample.
139+ /// Empty for VP9, which carries no out-of-band parameter sets.
137140 parameter_sets: Vec<u8>,
138141 /// Bytes of the NAL length prefix each sample is written with, off `avcC`
139142 /// or `hvcC`. Unused by VP9.
@@ -160,20 +163,26 @@ impl Mp4Demuxer {
160163 Ok(MediaType::H265) => Some((t, Codec::Hevc)),
161164 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
162165 // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry
163- // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple
164- // and ffmpeg's mov muxer write in practice -- reports no media
165- // type at all, and the file used to read back as having no
166- // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are
167- // parsed regardless of the entry the crate dropped, so only the
168- // fourcc has to be read here by hand. hvc1 differs from hev1 in
169- // that the parameter sets may not repeat in-band, which costs
170- // nothing: they are re-injected out of `hvcC` ahead of every
171- // sync sample either way.
172- _ => (matches!(t.track_type(), Ok(TrackType::Video))
173- && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1"))
174- .then_some((t, Codec::Hevc)),
166+ // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC
167+ // track -- what Apple and ffmpeg's mov muxer write in practice
168+ // -- and every AV1 track report no media type, and such a file
169+ // used to read back as having no video. Its sample tables
170+ // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the
171+ // entry the crate dropped, so only the fourcc has to be read
172+ // here by hand. hvc1 differs from hev1 in that the parameter
173+ // sets may not repeat in-band, which costs nothing: they are
174+ // re-injected out of `hvcC` ahead of every sync sample either
175+ // way, exactly as an AV1 sequence header is out of `av1C`.
176+ _ => matches!(t.track_type(), Ok(TrackType::Video))
177+ .then(|| sample_entry(path, t.track_id()).ok())
178+ .flatten()
179+ .and_then(|(kind, _)| match &kind {
180+ b"hvc1" => Some((t, Codec::Hevc)),
181+ b"av01" => Some((t, Codec::Av1)),
182+ _ => None,
183+ }),
175184 })
176- .ok_or("no H.264, HEVC or VP9 video track in file")?;
185+ .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?;
177186 let (track, codec) = track;
178187
179188 let track_id = track.track_id();
@@ -216,10 +225,19 @@ impl Mp4Demuxer {
216225 parameter_sets = sets;
217226 bit_depth = depth;
218227 }
219- // No parameter sets: a VP9 sample is self-contained, and AV1 never
220- // reaches this arm at all -- `mp4 0.14` knows no `av01` sample
221- // entry, so AV1 only ever arrives through [`MkvDemuxer`].
222- Codec::Vp9 | Codec::Av1 => {}
228+ // The sequence header OBU out of `av1C`, re-injected ahead of every
229+ // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` --
230+ // the same record in the same bytes, which is what makes an AV1 mp4
231+ // written here and an AV1 Matroska written here one stream in two
232+ // containers.
233+ Codec::Av1 => {
234+ let (_, entry) = sample_entry(path, track_id)?;
235+ let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C")
236+ .ok_or("no av1C box in the AV1 sample entry")?;
237+ parameter_sets = parse_av1c(av1c)?;
238+ }
239+ // No parameter sets: a VP9 sample is self-contained.
240+ Codec::Vp9 => {}
223241 }
224242 let sync_samples = track
225243 .trak
@@ -273,6 +291,16 @@ impl Mp4Demuxer {
273291 if self.codec == Codec::Vp9 {
274292 return Ok(Some(sample.bytes.to_vec()));
275293 }
294+ // An AV1 one is a whole temporal unit, likewise unframed -- with the
295+ // sequence header in front of it where a decoder may start.
296+ if self.codec == Codec::Av1 {
297+ let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len());
298+ if sample.is_sync {
299+ au.extend_from_slice(&self.parameter_sets);
300+ }
301+ au.extend_from_slice(&sample.bytes);
302+ return Ok(Some(au));
303+ }
276304
277305 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
278306 if sample.is_sync {
@@ -1075,7 +1103,7 @@ fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>>
10751103 /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
10761104 /// malformed header rather than erroring: every caller is looking for one box
10771105 /// and reports its own absence.
1078-fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
1106+pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
10791107 std::iter::from_fn(move || {
10801108 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
10811109 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
crates/engine/src/export.rsmodified+305 -191
@@ -1,28 +1,36 @@
1-//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska —
2-//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone.
1+//! Export: the edit list rendered back out as one mp4 (H.264 or AV1) or one
2+//! AV1-in-Matroska — or, picture left behind, as one WAV, FLAC or MP3 of the
3+//! timeline's audio alone.
34 //!
45 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
56 //! is impossible — while audio is copied packet for packet wherever a copy can
67 //! say what the timeline says: a copy is exact, free and never a generation of
7-//! loss. Where it *cannot* — an equalized lane, which is sample math no packet
8-//! copy can reach — that lane is decoded, mixed and encoded again with
9-//! `rusty_aac` ([`encode_audio`]). The audio-only formats have no such split:
10-//! `hound` writes PCM and `flacenc` encodes FLAC, so those are always *decoded*
11-//! out of the timeline. The worker owns everything: the caller gets an
8+//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an
9+//! equalized one, a source that is not AAC inside an mp4's own sample table —
10+//! the sound is decoded, mixed and encoded again with `rusty_aac`
11+//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes
12+//! PCM, `flacenc` encodes FLAC and `rusty_mp3` encodes MP3, so those are always
13+//! *decoded* out of the timeline. The worker owns everything: the caller gets an
1214 //! [`ExportHandle`] and polls it from its render loop.
1315 //!
16+//! **Every video format here carries the timeline's sound**, in whichever
17+//! container: the mp4 muxer writes an AAC track and so does the Matroska one.
18+//! Nothing is written picture-only and nothing is left silent without saying so
19+//! — the only sound that does not come out is sound this engine cannot decode at
20+//! all (Opus and AC-3 inside a Matroska file), and that is an error by name.
21+//!
1422 //! A **speeded** clip splits along the same line, and for the same reason. The
1523 //! picture is re-encoded, so the frame walk honours a rate: it takes the source
1624 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
1725 //! very frame preview holds there) and encodes a held one again rather than
1826 //! decoding it twice. A clip whose *file* was shot at another rate than the
1927 //! timeline goes through the same walk with one more conversion on the end
20-//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. The sound is *copied* unless a filter forces a decode, and
21-//! a packet carries no rate -- so a speeded clip on the one audio lane an mp4
22-//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x
23-//! under a re-timed picture.
24-//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are
25-//! decoded and resampled, so they honour a rate like the picture does.
28+//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
29+//! The sound is *copied* unless something forces a decode, and a packet carries
30+//! no rate — so a speeded lane is one of the things that forces one
31+//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
32+//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate
33+//! like the picture does.
2634 //!
2735 //! Nothing partial survives a failure: the worker writes to `<out>.part` and
2836 //! renames it onto `out` only once the file is closed and complete, so the
@@ -32,6 +40,8 @@
3240 //! behind (only in-process cleanup is promised), which is an orphan a user can
3341 //! delete rather than a file that plays for two seconds and stops.
3442
43+use std::fs::File;
44+use std::io::{BufWriter, Write};
3545 use std::path::{Path, PathBuf};
3646 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
3747 use std::sync::{Arc, Mutex};
@@ -63,37 +73,42 @@ const MAX_BITRATE: u64 = 20_000_000;
6373 /// on a build with no assembly, which is what this one is.
6474 const AV1_SPEED: u8 = 10;
6575
66-/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are
67-/// the only *video* pairs with both an encoder and a decoder under this
68-/// project's no-install rule, and WAV and FLAC are the only *standalone* audio
69-/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under
70-/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis
71-/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp4
72-/// track is encoded with -- but AAC is an mp4's own audio, never a file of its
73-/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import
74-/// through the plugin and stop there). A front-end says so rather than hiding
75-/// the rows.
76+/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the
77+/// user's pick of container -- are the only *video* pairs with both an encoder
78+/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are
79+/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and
80+/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is
81+/// what a re-encoded video track's sound leaves through -- but AAC is a
82+/// container's own audio, never a file of its own here.) HEVC and VP9 have no
83+/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there).
84+/// A front-end says so rather than hiding the rows.
85+///
86+/// **Every video format carries sound.** Which way it carries it is the only
87+/// difference: copied packet for packet where a copy can say what the timeline
88+/// says, decoded and encoded again ([`encode_audio`]) where it cannot.
7689 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
7790 pub enum Format {
7891 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
79- /// where a copy could not carry the edit (an equalized lane). Either way it
80- /// carries **one** audio lane: a timeline whose sound is spread over two is
81- /// refused by name here and mixed by the other two formats, which decode.
92+ /// where a copy could not carry the edit (a second audio lane to mix in, a
93+ /// speeded clip, an equalized one, a source no mp4 sample table holds).
8294 #[default]
8395 Mp4,
84- /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound
85- /// this project can *write*: this engine's Matroska writer has no audio
86- /// track at all, and the copy path walks an mp4 sample table, which a
87- /// Matroska file has none of. (*Reading* one's AAC is a different question,
88- /// and since this engine gained a Matroska demuxer the answer is yes --
89- /// `audio::Track::open` does it through symphonia's mkv reader.) The sound
90- /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up
91- /// front.
96+ /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
97+ /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
98+ /// reader reads one back, symphonia's `mkv` reader being what
99+ /// `audio::Track::open` opens it with.
92100 Av1,
93- /// The audio lane alone, 16-bit PCM.
101+ /// The same AV1 stream in an mp4, for everything that plays mp4 and not
102+ /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand
103+ /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
104+ /// unchanged.
105+ Av1Mp4,
106+ /// The audio lanes alone, 16-bit PCM.
94107 Wav,
95- /// The audio lane alone, losslessly compressed.
108+ /// The audio lanes alone, losslessly compressed.
96109 Flac,
110+ /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`).
111+ Mp3,
97112 }
98113
99114 impl Format {
@@ -101,26 +116,36 @@ impl Format {
101116 /// the destination path from it, so the name never disagrees with the bytes.
102117 pub fn ext(self) -> &'static str {
103118 match self {
104- Self::Mp4 => "mp4",
119+ Self::Mp4 | Self::Av1Mp4 => "mp4",
105120 Self::Av1 => "mkv",
106121 Self::Wav => "wav",
107122 Self::Flac => "flac",
123+ Self::Mp3 => "mp3",
108124 }
109125 }
110126
111127 /// Whether this format carries the picture. The bitrate settings are video
112- /// settings and mean nothing to the audio two.
128+ /// settings and mean nothing to the audio-only ones.
113129 pub fn has_video(self) -> bool {
114- matches!(self, Self::Mp4 | Self::Av1)
130+ matches!(self, Self::Mp4 | Self::Av1 | Self::Av1Mp4)
131+ }
132+
133+ /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
134+ /// and which of the two AV1 containers is being written are separate
135+ /// questions, and this is the first.
136+ fn is_av1(self) -> bool {
137+ matches!(self, Self::Av1 | Self::Av1Mp4)
115138 }
116139
117140 /// What the format is called where a refusal names it.
118141 pub fn name(self) -> &'static str {
119142 match self {
120143 Self::Mp4 => "an mp4",
121- Self::Av1 => "an AV1 export",
144+ Self::Av1 => "an AV1 Matroska",
145+ Self::Av1Mp4 => "an AV1 mp4",
122146 Self::Wav => "a WAV",
123147 Self::Flac => "a FLAC",
148+ Self::Mp3 => "an MP3",
124149 }
125150 }
126151 }
@@ -241,12 +266,12 @@ pub fn start(
241266 Err("the timeline is empty: there is nothing to export".into())
242267 }
243268 format if format.has_video() && !has_picture(&project) => Err(format!(
244- "the timeline has no picture: {} would be black. Export WAV or \
245- FLAC, which are the sound itself",
269+ "the timeline has no picture: {} would be black. Export WAV, \
270+ FLAC or MP3, which are the sound itself",
246271 format.name()
247272 )
248273 .into()),
249- Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings),
274+ format if format.has_video() => run(&project, &meta, &part, &worker, &settings),
250275 format => run_audio(&project, &meta, &part, &worker, format),
251276 };
252277 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
@@ -314,9 +339,12 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
314339 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
315340 let bitrate = bitrate_of(meta, settings);
316341 match settings.format {
317- // Opt-in only, for the reason [`Enc::open_av1`] states in full.
318- Format::Av1 if !forced("VE_HW_AV1") => None,
319- Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate),
342+ // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
343+ // AV1 formats sit on it: the container is not the encoder's business.
344+ format if format.is_av1() && !forced("VE_HW_AV1") => None,
345+ format if format.is_av1() => {
346+ HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
347+ }
320348 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
321349 }
322350 }
@@ -327,34 +355,65 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
327355 /// place, so what a card says before an export and what its progress line says
328356 /// during one cannot drift apart.
329357 fn video_label(format: Format, hw: bool) -> &'static str {
330- match (format, hw) {
331- (Format::Av1, true) => "HW encode (VA-API)",
332- (Format::Av1, false) => "SW encode (rav1e)",
358+ match (format.is_av1(), hw) {
333359 (_, true) => "HW encode (VA-API)",
334- (_, false) => "SW encode (rusty_h264)",
360+ (true, false) => "SW encode (rav1e)",
361+ (false, false) => "SW encode (rusty_h264)",
335362 }
336363 }
337364
365+/// The cheap half of "does this timeline's sound have to be re-encoded": what
366+/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
367+/// copy; a speeded lane is resampled; an equalizer is sample math. The other
368+/// half -- whether the sources can be copied out of at all -- costs a file open
369+/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
370+fn forces_encode(project: &Project) -> bool {
371+ let lanes: Vec<_> = project
372+ .audio_lanes()
373+ .into_iter()
374+ .filter(|&lane| !project.lane(lane).is_empty())
375+ .collect();
376+ lanes.len() > 1
377+ || lanes
378+ .iter()
379+ .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
380+ || equalized(project)
381+}
382+
338383 /// What the sound is written by. Every audio encoder here is software -- there
339-/// is no hardware AAC, PCM or FLAC seat -- so this names *which* one, and
340-/// whether an mp4 escapes encoding altogether by copying the packets it was
341-/// given. Empty for AV1, which carries no audio at all: a caller joins this to
342-/// a line that already says so, and repeating it would cost a line of card.
343-fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str {
384+/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
385+/// whether a container escapes encoding altogether by copying the packets it was
386+/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
387+/// timeline's sound too, so leaving it unnamed would be the old lie.
388+///
389+/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
390+/// card asking before the export has no way to know (a source that cannot be
391+/// copied out of is only found by opening it). `None` predicts from the edit
392+/// alone.
393+fn audio_label(
394+ project: &Project,
395+ format: Format,
396+ sound: bool,
397+ copied: Option<bool>,
398+) -> &'static str {
399+ if !sound {
400+ return "no sound to write";
401+ }
344402 match format {
345- Format::Av1 => "",
346- _ if !sound => "no sound to write",
347- Format::Mp4 if equalized(project) => "AAC · SW encode (rusty_aac)",
348- Format::Mp4 => "AAC copy",
349403 Format::Wav => "PCM · SW (hound)",
350404 Format::Flac => "FLAC · SW (flacenc)",
405+ Format::Mp3 => "MP3 · SW (rusty_mp3)",
406+ _ => match copied.unwrap_or(!forces_encode(project)) {
407+ true => "AAC copy",
408+ false => "AAC · SW encode (rusty_aac)",
409+ },
351410 }
352411 }
353412
354413 /// What [`start`] would write this timeline's sound with, before one is
355414 /// started. Pure: no probe and no file opened, so a card may ask it per repaint.
356415 pub fn planned_audio(project: &Project, format: Format) -> &'static str {
357- audio_label(project, format, has_sound(project))
416+ audio_label(project, format, has_sound(project), None)
358417 }
359418
360419 /// What [`start`] would encode the picture with, probed the way the export
@@ -376,19 +435,32 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
376435 shared.finished.store(true, Ordering::Release);
377436 }
378437
379-/// The timeline's one audio lane, copied packet for packet: the mp4 path's
380-/// sound, and the reason that path carries only one lane of it. A lane an
381-/// equalizer has been put on cannot be *copied* at all and leaves through
382-/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit.
438+/// The audio track an export writes, and how it was made -- a copy is the
439+/// source's own packets, bit for bit, and anything else is this project's
440+/// encoder over the decoded mix. [`run`] publishes which of the two really
441+/// happened, so the encoder line a user reads is measured and not promised.
442+pub(crate) struct ExportAudio {
443+ pub params: crate::AacTrackParams,
444+ pub packets: Vec<crate::AacPacket>,
445+ /// Whether those packets are the source's, untouched.
446+ pub copied: bool,
447+}
448+
449+/// The timeline's audio track for a file that carries picture: copied packet for
450+/// packet where a copy says exactly what the timeline says, and decoded, mixed
451+/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
452+/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
453+/// table. Nothing is refused for being uncopyable any more; the only refusals
454+/// left below the copy are about sound this engine cannot *decode* either, and
455+/// those come out of the decode path by name.
456+///
457+/// The copy is still the default and still bit-exact: a timeline nobody has
458+/// touched leaves as the very packets its source holds.
383459 ///
384460 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per
385461 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
386462 /// `copy_segments` that yields packets instead of collecting them.
387-#[allow(clippy::type_complexity)]
388-fn copy_audio(
389- project: &Project,
390- meta: &VideoMeta,
391-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
463+fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
392464 // The segments name their source, and the copy carries its packet-rounding
393465 // debt across a source join exactly as across a cut, so a timeline spanning
394466 // files stays in sync. A source whose AAC parameters disagree with the
@@ -399,16 +471,10 @@ fn copy_audio(
399471 // is the same list `PlaybackSession::seek` hands the decoder, so an export
400472 // of a timeline playing a file's second audio track carries *that* track.
401473 //
402- // One lane, because this path *copies* AAC packets and a mix is not a copy:
403- // summing two lanes means decoding both, and only the one thing a copy
404- // cannot express at all -- an equalizer -- is decoded here today. Refused by
405- // name rather than silently exporting the first lane, which is a file
406- // missing half its sound: the one failure a user would not notice.
407- //
408- // ponytail: the ceiling is this routing, not the codec any more.
409- // [`encode_audio`] already mixes *every* audio lane (it is the WAV path's
410- // own opener), so lifting this refusal is routing a second case to it --
411- // deliberately not done here, where the change under test is the equalizer.
474+ // One lane is the only shape a *copy* has: summing two means decoding both,
475+ // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
476+ // very mix the WAV path writes -- it used to be a refusal, and a refusal is
477+ // what a file missing half its sound deserves, not what a mix does.
412478 //
413479 // *Which* lane is the same question `audio_segments_from` answers for
414480 // playback, and it is asked here rather than assumed: the lane that holds
@@ -418,68 +484,59 @@ fn copy_audio(
418484 // whole comment is about.
419485 let lanes = project.audio_segments_from(0, meta.frame_rate);
420486 let [segments] = &lanes[..] else {
421- return Err(format!(
422- "this timeline has {} audio lanes and an mp4 export copies one: \
423- export WAV or FLAC, which are mixed, or put the sound on one lane",
424- lanes.len()
425- )
426- .into());
487+ return encode_audio(project, meta);
427488 };
428489 // ...and the same list names *which* lane those clips sit on, which is the
429490 // only way to ask what has been done to them.
430491 let lane = project.audio_lanes()[0];
431492 // ...and the same list decides whether any clip this would copy plays at a
432- // rate other than the one it was recorded at. A copy hands the mp4 the very
433- // AAC packets the source holds and there is no rate inside a packet to
493+ // rate other than the one it was recorded at. A copy hands the muxer the
494+ // very AAC packets the source holds and there is no rate inside a packet to
434495 // change: the picture would come out re-timed (the walk in [`run`] honours
435496 // it) over sound at 1.00x, which is the drift a person finds only after the
436- // file has gone somewhere. Refused by name -- and only *here*, on the lane
437- // being copied: AV1 carries no audio at all and never reaches this, so it
438- // honours a speed like WAV and FLAC do.
497+ // file has gone somewhere. Decoded and resampled instead, by the same worker
498+ // playback feeds from.
439499 //
440- // ponytail: the ceiling is the packet copy itself, not the rate, and the way
441- // off it is now next door -- [`encode_audio`] resamples exactly as the WAV
442- // path does, so routing a speeded lane there is the one line the equalizer
443- // below takes. Left refused because this change is the equalizer's, and a
444- // speeded export turning silently from a copy into a re-encode is a change
445- // of its own to make on purpose.
446- if let Some((at, speed)) = project
447- .lane(lane)
448- .iter()
449- .find(|c| !c.speed.is_normal())
450- .map(|c| (c.start, c.speed))
451- {
452- return Err(format!(
453- "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \
454- no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x",
455- timecode(at, meta.frame_rate)
456- )
457- .into());
458- }
459- // A frame *rate* of its own is not one of those, and that is deliberate:
460- // do not "fix" this into a re-encode. A clip counts the **timeline's**
461- // frames whatever its file was shot at ([`Rate`]), so the window this copy
462- // trims a source's sound to is `start..end` in whole timeline frames --
463- // exactly the seconds the picture covers -- and the file is read at the
464- // pitch it was recorded at, which is what playing at the rate it was shot at
465- // means. There is no per-clip stretch to express, so the packets are already
466- // the right sound in the right place; re-encoding a conformed lane would buy
467- // nothing and cost a generation of loss on every mixed-rate export
500+ // ...and whether any clip on it carries an equalizer, which is sample math a
501+ // copy never reaches: copying such a lane would write the clip *flat*,
502+ // silently.
503+ //
504+ // A frame *rate* of its own is not one of those, and that is deliberate: do
505+ // not "fix" this into a re-encode. A clip counts the **timeline's** frames
506+ // whatever its file was shot at ([`crate::project::Rate`]), so the window
507+ // this copy trims a source's sound to is `start..end` in whole timeline
508+ // frames -- exactly the seconds the picture covers -- and the file is read
509+ // at the pitch it was recorded at, which is what playing at the rate it was
510+ // shot at means. There is no per-clip stretch to express, so the packets are
511+ // already the right sound in the right place; re-encoding a conformed lane
512+ // would buy nothing and cost a generation of loss on every mixed-rate export
468513 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
469514 // measures the copied sound against the picture). A *speed* is different
470- // because it resamples, which is why it is refused above.
515+ // because it resamples, which is why it leaves through the re-encode above.
471516 //
472- // ...and last, whether any clip on it carries an equalizer. An EQ is sample
473- // math and a copy never decodes, so copying such a lane would write the clip
474- // *flat*, silently -- the failure a missing audio track is. This lane is
475- // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and
476- // only this case is: a timeline nobody has equalized still leaves through
477- // the copy below, packet for packet, so no passthrough quietly becomes a
478- // generation of loss.
479- if equalized(project) {
517+ // Only these: a timeline nobody has touched still leaves through the copy
518+ // below, packet for packet, so no passthrough quietly becomes a generation
519+ // of loss.
520+ let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
521+ if speeded || equalized(project) {
480522 return encode_audio(project, meta);
481523 }
482- AudioSession::copy_multi_streams(&project.audio_sources(), segments)
524+ // What is left is a copy the *sources* may still not be able to give: AAC
525+ // inside a Matroska file (readable, but not out of a sample table this walks
526+ // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
527+ // sources whose AAC parameters disagree. Every one of them decodes, and what
528+ // decodes can be encoded again, so the copy's refusal is now a route: the
529+ // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
530+ // which symphonia has no decoder for at any version -- is the one that comes
531+ // back, by name, from [`encode_audio`].
532+ match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
533+ Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
534+ params,
535+ packets,
536+ copied: true,
537+ })),
538+ Err(_) => encode_audio(project, meta),
539+ }
483540 }
484541
485542 /// The same lane, *decoded*: what a packet copy cannot carry comes out here as
@@ -499,11 +556,7 @@ fn copy_audio(
499556 /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
500557 /// the whole stream anyway, since it encodes its frames in parallel. Upgrade
501558 /// path is a chunked push once that encoder streams.
502-#[allow(clippy::type_complexity)]
503-fn encode_audio(
504- project: &Project,
505- meta: &VideoMeta,
506-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
559+fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
507560 let sources = project.audio_sources();
508561 let segs = project.audio_segments_from(0, meta.frame_rate);
509562 let eqs = project.audio_eqs_from(0, meta.frame_rate);
@@ -515,7 +568,8 @@ fn encode_audio(
515568 };
516569 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
517570 format!(
518- "{} Hz is not an AAC sample rate: export WAV or FLAC, which write it as it is",
571+ "{} Hz is not an AAC sample rate: export WAV, FLAC or MP3, which write it as \
572+ it is",
519573 audio.sample_rate
520574 )
521575 })?;
@@ -555,8 +609,8 @@ fn encode_audio(
555609 samples: packet.duration,
556610 });
557611 }
558- Ok(Some((
559- crate::AacTrackParams {
612+ Ok(Some(ExportAudio {
613+ params: crate::AacTrackParams {
560614 freq_index,
561615 // 1 and 2 are the ISO channel configurations for mono and stereo,
562616 // and the opener refuses anything wider than stereo already.
@@ -564,7 +618,8 @@ fn encode_audio(
564618 sample_rate: audio.sample_rate,
565619 },
566620 packets,
567- )))
621+ copied: false,
622+ }))
568623 }
569624
570625 fn run(
@@ -577,19 +632,22 @@ fn run(
577632 let total = project.timeline_frames();
578633 let sources = project.sources();
579634 // Audio first: a track has to be declared when the muxer is created, which
580- // happens as soon as the first coded picture arrives. None of it for AV1 --
581- // that one is picture only, for the reason [`Format::Av1`] states -- and no
582- // refusal of it either: a timeline with sound is exported as the video it
583- // also is, and the front-end says the sound is not in the file *before* the
584- // export starts rather than failing it here.
585- let audio = match settings.format {
586- Format::Av1 => None,
587- _ => copy_audio(project, meta)?,
588- };
589- let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
590- freq_index: track.freq_index,
591- chan_conf: track.chan_conf,
635+ // happens as soon as the first coded picture arrives -- and the Matroska
636+ // muxer wants the packets themselves that early too, because it interleaves
637+ // them into the clusters as it writes. Every video format gets the same
638+ // track: none of them is picture-only any more.
639+ let audio = copy_audio(project, meta)?;
640+ let audio_params = audio.as_ref().map(|track| AudioParams {
641+ freq_index: track.params.freq_index,
642+ chan_conf: track.params.chan_conf,
643+ sample_rate: track.params.sample_rate,
592644 });
645+ // What the track *is*, kept before the packets are handed to a muxer: the
646+ // encoder line names a copy or an encode and only `copy_audio` knows which.
647+ let sound = audio.as_ref().map(|track| track.copied);
648+ // Taken by the Matroska muxer at creation; the mp4 one writes its track
649+ // after the picture, so for that path this is still `Some` at the end.
650+ let mut packets = audio.map(|track| track.packets);
593651
594652 // One header parse per source, before any of them is decoded: what rate
595653 // each file was shot at against the timeline's ([`Rate`]), which is how the
@@ -607,13 +665,11 @@ fn run(
607665 // refused reads as the software one that took over rather than as the hope
608666 // it replaced -- and the sound says whether it was copied or encoded, which
609667 // `copy_audio` decided a few lines up.
610- *shared.encoders.lock().unwrap() = Some(
611- match audio_label(project, settings.format, audio.is_some()) {
612- // AV1: no sound in the file and none to name.
613- "" => encoder.label().to_string(),
614- sound => format!("{} · {sound}", encoder.label()),
615- },
616- );
668+ *shared.encoders.lock().unwrap() = Some(format!(
669+ "{} · {}",
670+ encoder.label(),
671+ audio_label(project, settings.format, sound.is_some(), sound)
672+ ));
617673 let mut muxer = None;
618674 let mut done = 0u32;
619675 let black = Black::new(meta);
@@ -739,6 +795,7 @@ fn run(
739795 meta,
740796 settings,
741797 audio_params.as_ref(),
798+ &mut packets,
742799 au,
743800 key,
744801 )?;
@@ -758,6 +815,7 @@ fn run(
758815 meta,
759816 settings,
760817 audio_params.as_ref(),
818+ &mut packets,
761819 au,
762820 key,
763821 )?;
@@ -769,8 +827,10 @@ fn run(
769827 let Some(muxer) = muxer else {
770828 return Err("export produced no coded pictures".into());
771829 };
772- let muxer = match (muxer, audio) {
773- (Muxer::Mp4(mut mp4), Some((_, packets))) => {
830+ // The mp4's audio track after its picture -- the Matroska one interleaved
831+ // its own as it went and left `packets` empty behind it.
832+ let muxer = match (muxer, packets) {
833+ (Muxer::Mp4(mut mp4), Some(packets)) => {
774834 for packet in packets {
775835 mp4.write_audio_packet(&packet.bytes)?;
776836 }
@@ -802,18 +862,6 @@ fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
802862 }
803863 }
804864
805-/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
806-/// enough to sit inside a refusal and exact enough to go and find the clip.
807-/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
808-/// `00:00:12:07` in the middle of a sentence is a serial number.
809-fn timecode(frame: u32, fps: f64) -> String {
810- let secs = match fps.is_finite() && fps > 0.0 {
811- true => (f64::from(frame) / fps) as u32,
812- false => 0,
813- };
814- format!("{:02}:{:02}", secs / 60, secs % 60)
815-}
816-
817865 /// The audio lanes alone, summed, as a WAV or a FLAC.
818866 ///
819867 /// Nothing here re-derives the edit: the play lists are
@@ -855,7 +903,7 @@ fn run_audio(
855903 };
856904 // The picture path's line, for a file that is sound alone: there is sound
857905 // by the line above, so this names the encoder writing it.
858- *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true).to_string());
906+ *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());
859907 let channels = usize::from(audio.channels);
860908 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
861909 * f64::from(audio.sample_rate))
@@ -887,7 +935,10 @@ fn run_audio(
887935 match format {
888936 Format::Wav => write_wav(out, &samples, &audio)?,
889937 Format::Flac => write_flac(out, &samples, &audio)?,
890- Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"),
938+ Format::Mp3 => write_mp3(out, &samples, &audio)?,
939+ Format::Mp4 | Format::Av1 | Format::Av1Mp4 => {
940+ unreachable!("the picture formats are `run`")
941+ }
891942 }
892943 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
893944 Ok(())
@@ -914,6 +965,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()
914965 Ok(())
915966 }
916967
968+/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure
969+/// Rust like every other encoder here, and the reason this format is a row at
970+/// all: the LGPL `shine-rs` was the only one when it was not.
971+///
972+/// 256 kbps CBR, for [`encode_audio`]'s reason: an export is a master a person
973+/// edits from again, not a delivery file, and this is a lossy generation over
974+/// sources that may already have been one. The rate is snapped to a legal Layer
975+/// III value by the encoder, and a sample rate MPEG has no frame for (anything
976+/// but 8-48 kHz) is refused there by name rather than written as something else.
977+///
978+/// ponytail: CBR only, and no rate is offered to the caller -- the export card
979+/// has one bitrate control and it is the *picture's*. Upgrade path is
980+/// `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
981+fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
982+ let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig {
983+ bitrate_kbps: 256,
984+ vbr_quality: None,
985+ });
986+ // The samples are the 16-bit ones a WAV of this timeline holds, so the two
987+ // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
988+ // engine's own decoders do.
989+ let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
990+ encoder
991+ .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
992+ .map_err(|e| format!("mp3 encode: {e}"))?;
993+ encoder.finish();
994+ let mut file = BufWriter::new(File::create(out)?);
995+ // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
996+ // header first: the loop ends on the only error it can see.
997+ while let Ok(frame) = encoder.next_packet() {
998+ file.write_all(&frame)?;
999+ }
1000+ file.flush()?;
1001+ Ok(())
1002+}
1003+
9171004 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
9181005 /// text: they are not `Send + Sync`, and every one of them fails the export the
9191006 /// same way.
@@ -1014,34 +1101,59 @@ fn write_video(
10141101 meta: &VideoMeta,
10151102 settings: &ExportSettings,
10161103 audio: Option<&AudioParams>,
1104+ packets: &mut Option<Vec<crate::AacPacket>>,
10171105 au: &[u8],
10181106 key: bool,
10191107 ) -> crate::Result<()> {
1020- if settings.format == Format::Av1 {
1108+ if settings.format.is_av1() {
1109+ // Every AV1 stream opens on a keyframe, and a keyframe carries the
1110+ // sequence header the track has to declare: an encoder that handed back
1111+ // neither has produced nothing a decoder can start. The same header goes
1112+ // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
1113+ fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result<Av1Params<'a>> {
1114+ Ok(Av1Params {
1115+ width: meta.width,
1116+ height: meta.height,
1117+ frame_rate: meta.frame_rate,
1118+ config: crate::mux::av1_sequence_header(au)
1119+ .ok_or("the first coded picture carries no AV1 sequence header")?,
1120+ })
1121+ }
1122+ if settings.format == Format::Av1 {
1123+ let muxer = match muxer {
1124+ Some(Muxer::Mkv(mkv)) => mkv,
1125+ Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
1126+ none => {
1127+ // The sound with it, all of it: the Matroska muxer writes the
1128+ // packets into the clusters of the pictures they play under.
1129+ let sound = audio.zip(packets.take());
1130+ let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
1131+ out,
1132+ &params(meta, au)?,
1133+ sound,
1134+ )?)) else {
1135+ unreachable!("just inserted a Matroska muxer")
1136+ };
1137+ mkv
1138+ }
1139+ };
1140+ return muxer.write_frame(au, key);
1141+ }
10211142 let muxer = match muxer {
1022- Some(Muxer::Mkv(mkv)) => mkv,
1023- Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
1143+ Some(Muxer::Mp4(mp4)) => mp4,
1144+ Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
10241145 none => {
1025- // Every AV1 stream opens on a keyframe, and a keyframe carries
1026- // the sequence header the track has to declare: an encoder that
1027- // handed back neither has produced nothing a decoder can start.
1028- let config = crate::mux::av1_sequence_header(au)
1029- .ok_or("the first coded picture carries no AV1 sequence header")?;
1030- let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
1146+ let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
10311147 out,
1032- &Av1Params {
1033- width: meta.width,
1034- height: meta.height,
1035- frame_rate: meta.frame_rate,
1036- config,
1037- },
1148+ &params(meta, au)?,
1149+ audio,
10381150 )?)) else {
1039- unreachable!("just inserted a Matroska muxer")
1151+ unreachable!("just inserted an mp4 muxer")
10401152 };
1041- mkv
1153+ mp4
10421154 }
10431155 };
1044- return muxer.write_frame(au, key);
1156+ return muxer.write_av1_frame(au, key);
10451157 }
10461158 if !crate::mux::has_coded_slice(au) {
10471159 return Ok(());
@@ -1123,7 +1235,9 @@ impl Enc {
11231235 }
11241236
11251237 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1126- if settings.format == Format::Av1 {
1238+ // Which *codec* the picture is, not which container it goes in: both AV1
1239+ // formats run the same encoder.
1240+ if settings.format.is_av1() {
11271241 return Self::open_av1(meta, settings);
11281242 }
11291243 // A caller's number goes through the same clamp as the computed one: a
crates/engine/src/mux.rsmodified+538 -19
@@ -5,10 +5,17 @@
55 //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all,
66 //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read
77 //! as EBML by hand ([`MkvMuxer`]).
8+//!
9+//! AV1 goes into an **mp4** too, and the missing sample entry is written by hand
10+//! there as well ([`Mp4Muxer::create_av1`]): the crate writes the file with an
11+//! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the
12+//! spec asks for, which is the only box in a whole mp4 the crate cannot spell.
13+//! Both containers carry the timeline's AAC, so no format here writes a picture
14+//! whose sound was silently left behind.
815
9-use std::fs::File;
10-use std::io::{BufWriter, Seek, SeekFrom, Write};
11-use std::path::Path;
16+use std::fs::{File, OpenOptions};
17+use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
18+use std::path::{Path, PathBuf};
1219
1320 use mp4::{
1421 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
@@ -41,20 +48,31 @@ pub struct VideoParams<'a> {
4148 pub pps: &'a [u8],
4249 }
4350
44-/// Read straight off the source file's `esds`: export copies AAC packets, it
45-/// never re-encodes, so the decoder config is passed through unchanged.
51+/// What the audio track declares: read straight off the source file's `esds`
52+/// where the export copies packets, and off this project's own encoder where it
53+/// re-encodes ([`crate::export`] decides which). `sample_rate` says the same
54+/// thing `freq_index` does and is carried beside it because Matroska states the
55+/// rate as a number rather than as an index into the AAC table.
4656 pub struct AudioParams {
4757 pub freq_index: u8,
4858 pub chan_conf: u8,
59+ pub sample_rate: u32,
4960 }
5061
51-/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores
62+/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores
5263 /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so
5364 /// every sample handed over must carry an exact duration or the tracks drift.
5465 pub struct Mp4Muxer {
5566 writer: Mp4Writer<BufWriter<File>>,
5667 frame_duration: u32,
5768 has_audio: bool,
69+ /// The `av1C` record an AV1 file's sample entry is patched to carry at
70+ /// [`finish`](Mp4Muxer::finish); `None` for H.264, which the crate spells
71+ /// itself. See [`create_av1`](Mp4Muxer::create_av1).
72+ av1c: Option<Vec<u8>>,
73+ /// Where the file is, for that patch: the writer owns the handle it wrote
74+ /// through and the patch reopens the finished file.
75+ path: PathBuf,
5876 }
5977
6078 const VIDEO_TRACK: u32 = 1;
@@ -65,6 +83,61 @@ impl Mp4Muxer {
6583 path: &Path,
6684 video: &VideoParams,
6785 audio: Option<&AudioParams>,
86+ ) -> crate::Result<Self> {
87+ Self::open(path, video, audio, None)
88+ }
89+
90+ /// The same file with an AV1 track in it. `mp4 0.14` writes no `av01` sample
91+ /// entry -- it has no AV1 anything -- so the file is written with an `avc1`
92+ /// entry of placeholder parameter sets and that one entry is rewritten at
93+ /// [`finish`](Mp4Muxer::finish) into the `av01` + `av1C` pair AV1-ISOBMFF
94+ /// §2.2 asks for. Everything else in an mp4 is codec-blind (the sample
95+ /// tables, the audio track, the movie header), so the entry is the only box
96+ /// this has to spell by hand -- and the `moov` it lives in is written *after*
97+ /// `mdat`, so growing it moves no sample and invalidates no chunk offset.
98+ ///
99+ /// The record's layout is the one OxideAV's `oxideav-mp4` writes
100+ /// (`src/sample_entries.rs`, MIT): a `VisualSampleEntry` header verbatim,
101+ /// then `av1C` -- the very four bytes and sequence header OBU [`MkvMuxer`]
102+ /// puts in `CodecPrivate`, which is what makes the two containers' AV1 one
103+ /// stream written twice rather than two.
104+ ///
105+ /// ponytail: the ceiling is that one entry. A second video track, or an AV1
106+ /// track beside an H.264 one, would need the walk in [`patch_av01`] to be
107+ /// told *which* track it is patching; the upgrade path is passing the track
108+ /// id it already knows down that walk.
109+ pub fn create_av1(
110+ path: &Path,
111+ video: &Av1Params,
112+ audio: Option<&AudioParams>,
113+ ) -> crate::Result<Self> {
114+ if video.config.is_empty() {
115+ return Err("no AV1 sequence header for the track's av1C record".into());
116+ }
117+ let mut av1c = AV1C_HEAD.to_vec();
118+ av1c.extend_from_slice(video.config);
119+ Self::open(
120+ path,
121+ &VideoParams {
122+ width: video.width,
123+ height: video.height,
124+ frame_rate: video.frame_rate,
125+ // Never read by anything: the entry that holds them is replaced
126+ // whole at `finish`. Four bytes because `AvcCBox::new` indexes
127+ // `sps[1..=3]` for the profile it will never be asked for.
128+ sps: &[0x67, 0x42, 0x00, 0x1E],
129+ pps: &[0x68, 0xCE, 0x3C, 0x80],
130+ },
131+ audio,
132+ Some(av1c),
133+ )
134+ }
135+
136+ fn open(
137+ path: &Path,
138+ video: &VideoParams,
139+ audio: Option<&AudioParams>,
140+ av1c: Option<Vec<u8>>,
68141 ) -> crate::Result<Self> {
69142 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
70143 return Err(format!("bad frame rate {}", video.frame_rate).into());
@@ -88,10 +161,15 @@ impl Mp4Muxer {
88161 &Mp4Config {
89162 major_brand: FourCC::from(*b"isom"),
90163 minor_version: 512,
164+ // The codec's own brand among them, so a reader that picks a
165+ // parser off `ftyp` is told which of the two this is.
91166 compatible_brands: vec![
92167 FourCC::from(*b"isom"),
93168 FourCC::from(*b"iso2"),
94- FourCC::from(*b"avc1"),
169+ FourCC::from(match av1c {
170+ Some(_) => *b"av01",
171+ None => *b"avc1",
172+ }),
95173 FourCC::from(*b"mp41"),
96174 ],
97175 // The video track's own, deliberately: `mp4` converts every
@@ -116,6 +194,9 @@ impl Mp4Muxer {
116194 })?;
117195 if let Some(audio) = audio {
118196 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;
197+ // The index's own rate, not `audio.sample_rate`: this is the clock
198+ // an `stts` counts in and the `esds` states the index, so the two
199+ // must not be able to disagree.
119200 let sample_rate = freq_index.freq();
120201 writer.add_track(&TrackConfig {
121202 track_type: TrackType::Audio,
@@ -134,6 +215,8 @@ impl Mp4Muxer {
134215 writer,
135216 frame_duration,
136217 has_audio: audio.is_some(),
218+ av1c,
219+ path: path.to_path_buf(),
137220 })
138221 }
139222
@@ -154,6 +237,28 @@ impl Mp4Muxer {
154237 Ok(())
155238 }
156239
240+ /// One coded picture as an AV1 temporal unit, written verbatim: an mp4 AV1
241+ /// sample is the low-overhead OBU stream the encoder handed over, exactly as
242+ /// a Matroska block is, so there is nothing to reframe. `key` is the
243+ /// encoder's own word for a unit a decoder may start on -- an mp4 says it in
244+ /// `stss` where Matroska says it in the block flags.
245+ pub fn write_av1_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {
246+ if obus.is_empty() {
247+ return Err("an empty AV1 temporal unit".into());
248+ }
249+ self.writer.write_sample(
250+ VIDEO_TRACK,
251+ &Mp4Sample {
252+ start_time: 0,
253+ duration: self.frame_duration,
254+ rendering_offset: 0,
255+ is_sync: key,
256+ bytes: Bytes::copy_from_slice(obus),
257+ },
258+ )?;
259+ Ok(())
260+ }
261+
157262 /// One raw AAC packet (no ADTS header), copied verbatim from the source --
158263 /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
159264 /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
@@ -178,8 +283,119 @@ impl Mp4Muxer {
178283
179284 pub fn finish(mut self) -> crate::Result<()> {
180285 self.writer.write_end()?;
181- Ok(())
286+ let Self {
287+ writer, av1c, path, ..
288+ } = self;
289+ // Not a `drop`: the buffered tail of `moov` has to be on disk before the
290+ // patch below reads it back, and a `BufWriter` swallows the error of
291+ // flushing it on drop.
292+ writer.into_writer().flush()?;
293+ match av1c {
294+ Some(av1c) => patch_av01(&path, &av1c),
295+ None => Ok(()),
296+ }
297+ }
298+}
299+
300+/// Rewrites the finished file's one video sample entry from the `avc1` the crate
301+/// wrote into the `av01` + `av1C` an AV1 track declares. Called once, on a
302+/// complete file, and only for a file [`Mp4Muxer::create_av1`] opened.
303+///
304+/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only
305+/// ever rewrites the tail of the file: no sample moves and no chunk offset in
306+/// `co64` changes. The box tree is rebuilt rather than patched in place, which
307+/// is what keeps every ancestor's size right by construction.
308+fn patch_av01(path: &Path, av1c: &[u8]) -> crate::Result<()> {
309+ let mut file = OpenOptions::new().read(true).write(true).open(path)?;
310+ let end = file.metadata()?.len();
311+ let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
312+ let patched = swap_av01(&payload, 0, av1c).ok_or("no avc1 sample entry to rewrite as av01")?;
313+ let mut out = Vec::with_capacity(patched.len() + 8);
314+ push_box(&mut out, b"moov", &patched);
315+ file.seek(SeekFrom::Start(at))?;
316+ file.write_all(&out)?;
317+ file.set_len(at + out.len() as u64)?;
318+ file.flush()?;
319+ Ok(())
320+}
321+
322+/// Offset and payload of the first top-level box of type `want`.
323+fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result<Option<(u64, Vec<u8>)>> {
324+ let mut at = 0u64;
325+ while at + 8 <= end {
326+ let mut header = [0u8; 8];
327+ file.seek(SeekFrom::Start(at))?;
328+ file.read_exact(&mut header)?;
329+ let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
330+ 0 => (end - at, 8),
331+ 1 => {
332+ let mut large = [0u8; 8];
333+ file.read_exact(&mut large)?;
334+ (u64::from_be_bytes(large), 16)
335+ }
336+ size => (u64::from(size), 8),
337+ };
338+ if size < head_len || at + size > end {
339+ return Err("truncated box in the file's top level".into());
340+ }
341+ if &header[4..8] == want {
342+ let mut payload = vec![0u8; (size - head_len) as usize];
343+ file.read_exact(&mut payload)?;
344+ return Ok(Some((at, payload)));
345+ }
346+ at += size;
182347 }
348+ Ok(None)
349+}
350+
351+/// `moov` down to the sample descriptions, which is where the entry lives.
352+const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"];
353+
354+/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry replaced.
355+/// `None` where this branch holds no such entry -- an audio `trak` is walked
356+/// into and comes back untouched, which is how the *video* track is found
357+/// without being told which id it has.
358+fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option<Vec<u8>> {
359+ if depth == STSD_PATH.len() {
360+ // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
361+ let mut out = payload.get(..8)?.to_vec();
362+ let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?;
363+ if kind != b"avc1" {
364+ return None;
365+ }
366+ // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all)
367+ // before its codec box, and `av01` carries exactly the same ones -- so
368+ // the header is kept and only the configuration box is swapped.
369+ let mut swapped = entry.get(..78)?.to_vec();
370+ push_box(&mut swapped, b"av1C", av1c);
371+ push_box(&mut out, b"av01", &swapped);
372+ return Some(out);
373+ }
374+ let mut out = Vec::with_capacity(payload.len());
375+ let mut done = false;
376+ for (kind, child) in crate::demux::boxes(payload) {
377+ let patched = match !done && kind == STSD_PATH[depth] {
378+ true => swap_av01(child, depth + 1, av1c),
379+ false => None,
380+ };
381+ match patched {
382+ Some(child) => {
383+ push_box(&mut out, kind, &child);
384+ done = true;
385+ }
386+ None => push_box(&mut out, kind, child),
387+ }
388+ }
389+ done.then_some(out)
390+}
391+
392+/// One mp4 box: 32-bit size, four-character type, payload. Every box inside a
393+/// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never
394+/// rewrites.
395+fn push_box(out: &mut Vec<u8>, kind: &[u8; 4], payload: &[u8]) {
396+ out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes());
397+ out.extend_from_slice(kind);
398+ out.extend_from_slice(payload);
183399 }
184400
185401 // Matroska element ids, written with the leading length marker they carry in the
@@ -210,6 +426,10 @@ const DEFAULT_DURATION: u32 = 0x23E383;
210426 const VIDEO: u32 = 0xE0;
211427 const PIXEL_WIDTH: u32 = 0xB0;
212428 const PIXEL_HEIGHT: u32 = 0xBA;
429+const AUDIO: u32 = 0xE1;
430+const SAMPLING_FREQUENCY: u32 = 0xB5;
431+const CHANNELS: u32 = 0x9F;
432+const CODEC_DELAY: u32 = 0x56AA;
213433 const CLUSTER: u32 = 0x1F43_B675;
214434 const CLUSTER_TIMESTAMP: u32 = 0xE7;
215435 const SIMPLE_BLOCK: u32 = 0xA3;
@@ -251,11 +471,17 @@ pub struct Av1Params<'a> {
251471 pub config: &'a [u8],
252472 }
253473
254-/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project
255-/// has no encoder for any sound Matroska carries, and copying the timeline's AAC
256-/// in would write a track its own reader refuses (`audio::AudioSession::open`
257-/// leaves a Matroska file silent) -- so the sound is named as left out by the
258-/// front-end rather than written unplayable.
474+/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC
475+/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the
476+/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what
477+/// symphonia's `mkv` reader -- this project's own way back in -- configures its
478+/// decoder from. An AV1 export used to be picture alone; a video file whose
479+/// sound was silently left behind is exactly the failure nobody notices until
480+/// the file has gone somewhere.
481+///
482+/// The sound is *interleaved*: each packet is written into the cluster of the
483+/// picture it plays under, so a player has both by the time it needs them rather
484+/// than a file it must read to the end of to hear.
259485 ///
260486 /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size
261487 /// and the duration -- so a killed process leaves an unfinished file rather than
@@ -272,10 +498,36 @@ pub struct MkvMuxer {
272498 cluster: Vec<u8>,
273499 cluster_ts: i64,
274500 frames: u64,
501+ /// The AAC track, if the timeline has sound, and how far it has been
502+ /// written.
503+ audio: Option<MkvAudio>,
504+}
505+
506+/// The sound waiting to be interleaved into the clusters.
507+struct MkvAudio {
508+ packets: Vec<crate::AacPacket>,
509+ /// Packets already written.
510+ next: usize,
511+ /// Frames already written, which is what the next packet's timestamp is
512+ /// counted from: every AAC-LC packet says its own length and they are not
513+ /// assumed equal here.
514+ samples: u64,
515+ sample_rate: u32,
275516 }
276517
277518 impl MkvMuxer {
278- pub fn create(path: &Path, video: &Av1Params) -> crate::Result<Self> {
519+ /// `audio` is the whole track at once -- the export has it before it has a
520+ /// single coded picture, and interleaving needs to look ahead of the frame
521+ /// being written.
522+ ///
523+ /// ponytail: that is the copy path's own ceiling reappearing (the track sits
524+ /// in memory, ~500 MB an hour); the upgrade path is the same streaming
525+ /// `copy_segments` `export::copy_audio` names.
526+ pub fn create(
527+ path: &Path,
528+ video: &Av1Params,
529+ audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
530+ ) -> crate::Result<Self> {
279531 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
280532 return Err(format!("bad frame rate {}", video.frame_rate).into());
281533 }
@@ -335,6 +587,9 @@ impl MkvMuxer {
335587 elem(&mut entry, VIDEO, &dims);
336588 let mut tracks = Vec::new();
337589 elem(&mut tracks, TRACK_ENTRY, &entry);
590+ if let Some((audio, _)) = &audio {
591+ elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?);
592+ }
338593 elem(&mut head, TRACKS, &tracks);
339594
340595 let mut file = File::create(path)?;
@@ -347,6 +602,12 @@ impl MkvMuxer {
347602 cluster: Vec::new(),
348603 cluster_ts: 0,
349604 frames: 0,
605+ audio: audio.map(|(params, packets)| MkvAudio {
606+ packets,
607+ next: 0,
608+ samples: 0,
609+ sample_rate: params.sample_rate.max(1),
610+ }),
350611 })
351612 }
352613
@@ -373,14 +634,58 @@ impl MkvMuxer {
373634 self.cluster_ts = ts;
374635 uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
375636 }
376- let mut block = Vec::with_capacity(obus.len() + 4);
377- block.push(0x81); // track number 1, as a one-byte EBML integer
637+ // The sound this picture plays under goes in first, into the cluster the
638+ // picture opened: a player reads the two together.
639+ self.drain_audio(ts)?;
640+ self.block(1, ts, key, obus);
641+ self.frames += 1;
642+ Ok(())
643+ }
644+
645+ /// Every audio packet whose timestamp has been reached, into the current
646+ /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left --
647+ /// the sound of a timeline can outlast its last picture by a packet.
648+ fn drain_audio(&mut self, until: i64) -> crate::Result<()> {
649+ loop {
650+ let Some(audio) = &mut self.audio else {
651+ return Ok(());
652+ };
653+ let Some(packet) = audio.packets.get_mut(audio.next) else {
654+ return Ok(());
655+ };
656+ // The packet's own start, in whole milliseconds: every AAC-LC packet
657+ // states its length, so a track of them is counted rather than
658+ // assumed to be 1024 frames each.
659+ let rate = i64::from(audio.sample_rate);
660+ let ts = (audio.samples as i64 * 1000 + rate / 2) / rate;
661+ if ts > until {
662+ return Ok(());
663+ }
664+ // Taken, not copied: the packet is written once and the track can be
665+ // hundreds of megabytes.
666+ let bytes = std::mem::take(&mut packet.bytes);
667+ audio.samples += u64::from(packet.samples);
668+ audio.next += 1;
669+ // A cluster of its own where the sound has run past what a 16-bit
670+ // relative timestamp reaches, which only the tail drain can do.
671+ if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS {
672+ self.flush()?;
673+ self.cluster_ts = ts;
674+ uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
675+ }
676+ self.block(2, ts, true, &bytes);
677+ }
678+ }
679+
680+ /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC
681+ /// packet is a keyframe; a picture is one when the encoder said so.
682+ fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) {
683+ let mut block = Vec::with_capacity(payload.len() + 4);
684+ block.push(0x80 | track); // the track number as a one-byte EBML integer
378685 block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes());
379686 block.push(if key { 0x80 } else { 0 });
380- block.extend_from_slice(obus);
687+ block.extend_from_slice(payload);
381688 elem(&mut self.cluster, SIMPLE_BLOCK, &block);
382- self.frames += 1;
383- Ok(())
384689 }
385690
386691 fn flush(&mut self) -> crate::Result<()> {
@@ -399,6 +704,9 @@ impl MkvMuxer {
399704 /// Closes the last cluster and patches the two fields that could not be
400705 /// known while writing: the segment's size and the presentation duration.
401706 pub fn finish(mut self) -> crate::Result<()> {
707+ // Whatever sound outlasts the last picture, before the last cluster is
708+ // closed: a track cut short here is a file that goes silent at the end.
709+ self.drain_audio(i64::MAX)?;
402710 self.flush()?;
403711 if self.frames == 0 {
404712 return Err("no frames were written to the Matroska file".into());
@@ -417,6 +725,52 @@ impl MkvMuxer {
417725 }
418726 }
419727
728+/// The `TrackEntry` of the AAC track: `A_AAC`, whose `CodecPrivate` is the
729+/// two-byte `AudioSpecificConfig` an mp4 states inside its `esds` -- object type
730+/// 2 (AAC-LC), the sample rate as its index into the AAC table, and the channel
731+/// configuration. symphonia's `mkv` reader hands exactly these bytes to its AAC
732+/// decoder, which is how a file written here reads back here.
733+///
734+/// `CodecDelay` is one packet: the first AAC access unit of both paths that
735+/// reach this -- a copy, whose head packet is the source's priming, and this
736+/// project's own encoder, whose delay is one 1024-frame block -- is that delay,
737+/// and an mp4 reader drops it by convention where Matroska has to be told in
738+/// nanoseconds.
739+fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> {
740+ let rate = audio.sample_rate;
741+ if rate == 0 || audio.chan_conf == 0 {
742+ return Err(format!(
743+ "an AAC track at {rate} Hz with {} channels",
744+ audio.chan_conf
745+ )
746+ .into());
747+ }
748+ let mut entry = Vec::new();
749+ uint(&mut entry, TRACK_NUMBER, 2);
750+ uint(&mut entry, TRACK_UID, 2);
751+ uint(&mut entry, TRACK_TYPE, 2); // audio
752+ uint(&mut entry, FLAG_LACING, 0);
753+ elem(&mut entry, CODEC_ID, b"A_AAC");
754+ // 5 bits object type, 4 bits sample rate index, 4 bits channel config, and
755+ // three zero bits to the byte -- the whole of an AAC-LC AudioSpecificConfig.
756+ let asc = (2u16 << 11)
757+ | (u16::from(audio.freq_index & 0xF) << 7)
758+ | (u16::from(audio.chan_conf & 0xF) << 3);
759+ elem(&mut entry, CODEC_PRIVATE, &asc.to_be_bytes());
760+ uint(
761+ &mut entry,
762+ CODEC_DELAY,
763+ u64::from(AAC_PACKET_SAMPLES) * 1_000_000_000 / u64::from(rate),
764+ );
765+ let mut audio_elem = Vec::new();
766+ put_id(&mut audio_elem, SAMPLING_FREQUENCY);
767+ put_size(&mut audio_elem, 8);
768+ audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes());
769+ uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf));
770+ elem(&mut entry, AUDIO, &audio_elem);
771+ Ok(entry)
772+}
773+
420774 /// The sequence header OBU of a coded temporal unit, for the track's
421775 /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe
422776 /// of a stream never may -- no decoder can start without it.
@@ -750,6 +1104,7 @@ mod tests {
7501104 Some(&AudioParams {
7511105 freq_index: 4, // 44100
7521106 chan_conf: 2,
1107+ sample_rate: 44_100,
7531108 }),
7541109 )
7551110 .unwrap();
@@ -840,6 +1195,168 @@ mod tests {
8401195 assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]);
8411196 }
8421197
1198+ /// One second of a 440 Hz tone as AAC-LC packets, through the very encoder
1199+ /// an export re-encodes with: real bitstream, so a file written with it is
1200+ /// one a decoder either plays or does not.
1201+ fn tone_packets(rate: u32, channels: u16) -> Vec<crate::AacPacket> {
1202+ let frames = rate as usize;
1203+ let mut pcm = Vec::with_capacity(frames * usize::from(channels));
1204+ for i in 0..frames {
1205+ let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5;
1206+ for _ in 0..channels {
1207+ pcm.push(s);
1208+ }
1209+ }
1210+ let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig::default());
1211+ encoder.push_pcm(&pcm, channels, rate).unwrap();
1212+ encoder.finish();
1213+ let mut packets = Vec::new();
1214+ while let Ok(packet) = encoder.next_packet() {
1215+ packets.push(crate::AacPacket {
1216+ bytes: packet.data,
1217+ samples: packet.duration,
1218+ });
1219+ }
1220+ assert!(packets.len() > 10, "a second of audio is many packets");
1221+ packets
1222+ }
1223+
1224+ /// The Matroska file carries **sound**, and this project's own reader is
1225+ /// what hears it: picture and an AAC track out through the muxer, then the
1226+ /// picture back through our EBML reader and the sound back through the
1227+ /// symphonia `mkv` reader `audio::Track::open` uses. An AV1 export used to be
1228+ /// picture alone, which is a file whose sound went missing with nobody told.
1229+ #[test]
1230+ fn a_matroska_file_carries_its_picture_and_its_sound() {
1231+ let sequence = obu(1, &[0x11, 0x22, 0x33]);
1232+ let mut key = sequence.clone();
1233+ key.extend_from_slice(&obu(6, &[0xAA; 8]));
1234+ let inter = obu(6, &[0xBB; 5]);
1235+ let packets = tone_packets(48_000, 2);
1236+ let heard: usize = packets.iter().map(|p| p.samples as usize).sum();
1237+
1238+ let out = std::env::temp_dir().join(format!("ve_mkv_sound_{}.mkv", std::process::id()));
1239+ let mut muxer = MkvMuxer::create(
1240+ &out,
1241+ &Av1Params {
1242+ width: 640,
1243+ height: 360,
1244+ frame_rate: 30.0,
1245+ config: av1_sequence_header(&key).unwrap(),
1246+ },
1247+ Some((
1248+ &AudioParams {
1249+ freq_index: 3, // 48000
1250+ chan_conf: 2,
1251+ sample_rate: 48_000,
1252+ },
1253+ packets,
1254+ )),
1255+ )
1256+ .unwrap();
1257+ // Half a second of picture under a second of sound: the tail of the
1258+ // audio outlives the last frame and must still be in the file.
1259+ muxer.write_frame(&key, true).unwrap();
1260+ for _ in 0..14 {
1261+ muxer.write_frame(&inter, false).unwrap();
1262+ }
1263+ muxer.finish().unwrap();
1264+
1265+ // The picture is untouched by the sound beside it: same units, same
1266+ // count, same sequence header in front of the keyframe.
1267+ let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
1268+ assert_eq!(meta.frame_count, 15);
1269+ assert_eq!(meta.codec, crate::demux::Codec::Av1);
1270+ let first = demuxer.next_access_unit().unwrap().unwrap();
1271+ assert_eq!(&first[sequence.len()..], &key[..]);
1272+ assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
1273+
1274+ // ...and the sound is there, by name and then by ear.
1275+ assert_eq!(
1276+ crate::demux::matroska_audio_codec(&out).unwrap().as_deref(),
1277+ Some("A_AAC")
1278+ );
1279+ let probe = crate::audio::AudioSession::probe(&out, 0)
1280+ .unwrap()
1281+ .expect("the file has an audio track");
1282+ assert_eq!((probe.sample_rate, probe.channels), (48_000, 2));
1283+ let (audio, chunks) = crate::audio::AudioSession::open(&out)
1284+ .unwrap()
1285+ .expect("decodes through symphonia's mkv reader");
1286+ assert_eq!((audio.sample_rate, audio.channels), (48_000, 2));
1287+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
1288+ let frames = samples.len() / 2;
1289+ assert!(
1290+ frames + 1024 >= heard && frames <= heard + 2048,
1291+ "{frames} frames read back of {heard} written"
1292+ );
1293+ let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt();
1294+ assert!(rms > 0.1, "the tone came back silent (rms {rms})");
1295+ std::fs::remove_file(&out).unwrap();
1296+ }
1297+
1298+ /// The same stream in the other container: AV1 into an mp4, whose `av01`
1299+ /// sample entry is written by hand, read back through our own demuxer --
1300+ /// which is the only test that the patched box tree is still an mp4.
1301+ #[test]
1302+ fn an_av1_track_round_trips_through_an_mp4() {
1303+ let sequence = obu(1, &[0x11, 0x22, 0x33]);
1304+ let mut key = sequence.clone();
1305+ key.extend_from_slice(&obu(6, &[0xAA; 8]));
1306+ let inter = obu(6, &[0xBB; 5]);
1307+ let packets = tone_packets(48_000, 2);
1308+
1309+ let out = std::env::temp_dir().join(format!("ve_mp4_av1_{}.mp4", std::process::id()));
1310+ let mut muxer = Mp4Muxer::create_av1(
1311+ &out,
1312+ &Av1Params {
1313+ width: 640,
1314+ height: 360,
1315+ frame_rate: 30.0,
1316+ config: av1_sequence_header(&key).unwrap(),
1317+ },
1318+ Some(&AudioParams {
1319+ freq_index: 3,
1320+ chan_conf: 2,
1321+ sample_rate: 48_000,
1322+ }),
1323+ )
1324+ .unwrap();
1325+ muxer.write_av1_frame(&key, true).unwrap();
1326+ muxer.write_av1_frame(&inter, false).unwrap();
1327+ muxer.write_av1_frame(&inter, false).unwrap();
1328+ for packet in &packets {
1329+ muxer.write_audio_packet(&packet.bytes).unwrap();
1330+ }
1331+ muxer.finish().unwrap();
1332+
1333+ let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
1334+ assert_eq!(meta.codec, crate::demux::Codec::Av1, "read back as AV1");
1335+ assert_eq!((meta.width, meta.height), (640, 360));
1336+ assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{}", meta.frame_rate);
1337+ assert_eq!(meta.frame_count, 3);
1338+ // The sequence header off `av1C` in front of the keyframe, exactly as
1339+ // the Matroska reader puts the one off `CodecPrivate` there.
1340+ let first = demuxer.next_access_unit().unwrap().unwrap();
1341+ assert_eq!(&first[..sequence.len()], &sequence[..]);
1342+ assert_eq!(&first[sequence.len()..], &key[..]);
1343+ assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
1344+ assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
1345+ assert!(demuxer.next_access_unit().unwrap().is_none());
1346+ assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0, "one keyframe");
1347+
1348+ // ...and the audio track beside it is the mp4 path's own, unchanged by
1349+ // the patch: same packets, playable through the same reader.
1350+ let (audio, chunks) = crate::audio::AudioSession::open(&out)
1351+ .unwrap()
1352+ .expect("the mp4's AAC track");
1353+ assert_eq!((audio.sample_rate, audio.channels), (48_000, 2));
1354+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
1355+ let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt();
1356+ assert!(rms > 0.1, "the tone came back silent (rms {rms})");
1357+ std::fs::remove_file(&out).unwrap();
1358+ }
1359+
8431360 /// The Matroska half of the round trip, with no encoder in it: three coded
8441361 /// units out through the muxer and back in through our own demuxer, which is
8451362 /// where the hand-written EBML meets the hand-written EBML reader.
@@ -861,6 +1378,7 @@ mod tests {
8611378 frame_rate: 30.0,
8621379 config,
8631380 },
1381+ None,
8641382 )
8651383 .unwrap();
8661384 muxer.write_frame(&key, true).unwrap();
@@ -903,6 +1421,7 @@ mod tests {
9031421 frame_rate: 30.0,
9041422 config: &[],
9051423 },
1424+ None,
9061425 )
9071426 .is_err()
9081427 );
crates/engine/tests/audio_decode.rsmodified+5 -3
@@ -160,8 +160,10 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
160160 }
161161 }
162162
163-/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC
164-/// encoder here -- and that refusal is named, never a silent silent export.
163+/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the
164+/// *copy* path names it and hands the export on to the re-encode (which decodes
165+/// this very source: the downmix above is what it encodes). Named either way --
166+/// never a silent export.
165167 #[test]
166168 fn an_ac3_source_refuses_an_mp4_audio_copy() {
167169 let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {
@@ -169,7 +171,7 @@ fn an_ac3_source_refuses_an_mp4_audio_copy() {
169171 };
170172 let err = err.to_string();
171173 assert!(
172- err.contains("needs AAC audio") && err.contains("AC-3"),
174+ err.contains("needs AAC in an mp4") && err.contains("AC-3"),
173175 "unhelpful refusal: {err}"
174176 );
175177 }
crates/engine/tests/audio_export.rsmodified+115 -5
@@ -55,8 +55,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
5555 /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`.
5656 ///
5757 /// Three things at once: a cut, a gap (which must arrive as silence), and a
58-/// source the mp4 export flatly refuses — there is no AAC encoder here, so an
59-/// mp3 on the timeline can *only* leave through this door.
58+/// source no mp4 sample table holds — an mp3, which the mp4 path decodes and
59+/// re-encodes today and once refused outright.
6060 fn mixed_project() -> Project {
6161 let clip = |start, source| Clip {
6262 start,
@@ -252,6 +252,116 @@ fn exports_the_timeline_as_a_flac() {
252252 std::fs::remove_file(&out).unwrap();
253253 }
254254
255+/// The third audio row, and the one that used to be a licence note: `rusty_mp3`
256+/// encodes it, and the file is read straight back through symphonia's mp3
257+/// decoder -- the very door an mp3 *import* comes in through, so an export can
258+/// be dropped back onto the timeline it came from.
259+///
260+/// The shape is checked loosely where MP3 cannot be exact: the encoder pads its
261+/// tail to a whole 1152-frame frame and the decoder hands back the padding, so
262+/// the length is asserted to within a frame instead of to the sample. What is
263+/// exact is the edit -- audible, silent, audible -- and the fixtures' 1 Hz
264+/// pulse inside the first second.
265+#[test]
266+fn exports_the_timeline_as_an_mp3() {
267+ let out = out_path("mp3", "mp3");
268+ let handle = engine::export::start(
269+ mixed_project(),
270+ meta(),
271+ &out,
272+ &ExportSettings {
273+ format: Format::Mp3,
274+ ..Default::default()
275+ },
276+ );
277+ wait(&handle, Duration::from_secs(120)).expect("mp3 export");
278+ assert_eq!(handle.progress(), 1.0, "finished at full progress");
279+ assert!(!part_path(&out).exists(), "the .part was renamed away");
280+
281+ let (meta, samples) = decode(&out);
282+ assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
283+ let channels = usize::from(meta.channels);
284+ let frames = samples.len() / channels;
285+ let timeline = (3.0 * f64::from(RATE)) as usize;
286+ assert!(
287+ frames >= timeline && frames <= timeline + 2 * 1152,
288+ "{frames} frames for a three-second timeline ({timeline})"
289+ );
290+ let av = rms(&samples, channels, 0.05, 0.95);
291+ let gap = rms(&samples, channels, 1.1, 1.9);
292+ let tone = rms(&samples, channels, 2.05, 2.95);
293+ println!("mp3 rms: av {av:.4} gap {gap:.6} mp3 second {tone:.4}");
294+ assert!(av > 0.01, "the first second is audible");
295+ assert!(tone > 0.01, "the mp3 second is audible");
296+ assert!(gap < av / 20.0, "the hole is silence: {gap:.6}");
297+ let peak = rms(&samples, channels, 0.2, 0.3);
298+ let dip = rms(&samples, channels, 0.7, 0.8);
299+ assert!(
300+ peak > dip * 4.0,
301+ "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
302+ );
303+ std::fs::remove_file(&out).unwrap();
304+}
305+
306+/// The failure a user hit, as a test: a still picture and a song, exported as an
307+/// **mp4**. There is no AAC track anywhere in that timeline to copy -- an mp3
308+/// holds no such packets and a png holds nothing at all -- so this used to be
309+/// refused by name and the only way out was a WAV beside a picture nobody had.
310+/// The song is decoded and encoded as AAC instead (`export::copy_audio` falls
311+/// through to `encode_audio`), and the file comes back with picture *and* sound.
312+#[test]
313+fn a_still_and_a_song_export_as_an_mp4_with_sound() {
314+ let song = asset("test_tone.mp3");
315+ let still = asset("test_still.png");
316+ let clip = |source, frames| Clip {
317+ start: 0,
318+ in_frame: 0,
319+ out_frame: frames,
320+ source,
321+ link: None,
322+ eq: None,
323+ color: None,
324+ fit: FitPolicy::default(),
325+ speed: Speed::NORMAL,
326+ };
327+ // Two seconds of each at the project's own 30 fps: a still has no length of
328+ // its own and the song is longer than what is placed.
329+ let project = Project::from_parts(
330+ vec![Source::new(still, 0), Source::new(song, 0)],
331+ vec![
332+ (LaneKind::Video, vec![clip(0, 60)]),
333+ (LaneKind::Audio, vec![clip(1, 60)]),
334+ ],
335+ Vec::new(),
336+ Vec::new(),
337+ )
338+ .expect("a still under a song");
339+ // The project's own picture size and rate: the still decides the one and
340+ // the scaffold the other, exactly as opening a png in the editor does.
341+ let meta = engine::VideoMeta {
342+ width: 640,
343+ height: 360,
344+ frame_rate: 30.0,
345+ frame_count: 60,
346+ codec: engine::Codec::H264,
347+ };
348+ let out = out_path("still_song", "mp4");
349+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
350+ wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
351+
352+ // Picture: two seconds of it, through the demuxer an import uses.
353+ let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
354+ assert_eq!((written.width, written.height), (640, 360));
355+ assert_eq!(written.frame_count, 60, "two seconds at 30 fps");
356+ // ...and sound, which is the half that used to be missing.
357+ let (audio, samples) = decode(&out);
358+ let channels = usize::from(audio.channels);
359+ let heard = rms(&samples, channels, 0.2, 1.8);
360+ println!("still+song: {} Hz, rms {heard:.4}", audio.sample_rate);
361+ assert!(heard > 0.01, "the song is in the file (rms {heard:.4})");
362+ std::fs::remove_file(&out).unwrap();
363+}
364+
255365 /// Cancel leaves nothing behind -- not the output, not the `.part`. The
256366 /// timeline is long enough (a minute of audio) that the escape lands mid-decode
257367 /// rather than after the file is already closed.
@@ -307,9 +417,9 @@ fn a_silent_timeline_refuses_an_audio_export() {
307417 );
308418 }
309419
310-/// An AC-3 source leaves through this door and no other: the mp4 export cannot
311-/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the
312-/// same timeline decodes, downmixes and reopens through the engine's own reader.
420+/// An AC-3 source through the audio-only door: the mp4 export cannot
421+/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline
422+/// decodes, downmixes and reopens through the engine's own reader.
313423 #[test]
314424 fn a_51_ac3_source_round_trips_through_a_wav() {
315425 let source = asset("test_ac3_51.mp4");
crates/engine/tests/audio_files.rsmodified+8 -5
@@ -273,7 +273,7 @@ fn an_audio_only_project_saves_reloads_and_exports_its_sound() {
273273 assert_eq!(
274274 e.to_string(),
275275 "the timeline has no picture: an mp4 would be black. \
276- Export WAV or FLAC, which are the sound itself"
276+ Export WAV, FLAC or MP3, which are the sound itself"
277277 );
278278 assert!(!mp4.exists(), "the refusal wrote a file anyway");
279279
@@ -415,16 +415,19 @@ fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
415415 }
416416 }
417417
418-/// The export copies AAC packets and has no encoder, so a timeline carrying an
419-/// mp3 cannot become an mp4 -- named, with its format, rather than exported
420-/// silent or exported wrong.
418+/// The *copy* path names what it cannot copy, by file and by format. That is a
419+/// fallback's reason rather than a user's refusal now -- `export::copy_audio`
420+/// takes this `Err` as "not copyable" and decodes and re-encodes the timeline
421+/// instead (`tests/audio_export.rs` exports exactly this shape as an mp4 with
422+/// sound in it) -- but the words are what a caller with no encoder shows, so
423+/// they are still asserted here.
421424 #[test]
422425 fn an_export_refuses_audio_it_cannot_copy() {
423426 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];
424427 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
425428 assert_eq!(
426429 refusal(AudioSession::copy_multi_segments(&sources, &segs)),
427- "export needs AAC audio today; test_tone.mp3 is mp3"
430+ "a packet copy needs AAC in an mp4; test_tone.mp3 is mp3"
428431 );
429432 // A timeline of nothing but mp4 still exports, which is the invariant this
430433 // refusal must not have cost.
crates/engine/tests/audio_segments.rsmodified+1 -1
@@ -185,7 +185,7 @@ fn a_gap_segment_is_silence_of_its_own_length() {
185185 );
186186 }
187187
188-/// The copy side of a gap: there is no AAC encoder here, so the hole is copied
188+/// The copy side of a gap: a copy never encodes, so the hole is copied
189189 /// as hand-written silent packets -- real access units, one 1024-frame stts
190190 /// entry each, the rounding debt carried through them like any other segment.
191191 /// Every packet after the gap therefore still lands at its timeline position.
crates/engine/tests/av1.rsmodified+80 -18
@@ -195,39 +195,45 @@ fn a_seek_lands_on_the_frame_it_asked_for() {
195195 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");
196196 }
197197
198-/// An mp4 export of a Matroska source is refused by name, and says where the
199-/// sound can go instead.
198+/// An mp4 export of a Matroska source carries its sound.
200199 ///
201-/// It used to *succeed*, silently, and only because this engine could not read
202-/// a Matroska file's audio at all: the export wrote picture with no sound in it
203-/// and nobody was told. Now that the sound is read (`tests/hevc_mkv.rs`), the
204-/// rule the whole mp4 path is built on applies to it like to any other source
205-/// it cannot copy -- an AC-3 mp4 has always been refused in the same breath.
206-/// The picture half of the same export is [`an_av1_export_reopens_through_our_own_demuxer`].
200+/// Three lives, this one. It used to *succeed* silently and write picture with
201+/// no sound, because this engine could not read a Matroska file's audio at all.
202+/// Then the sound became readable and this became a refusal by name, because
203+/// the mp4 path could only *copy* AAC out of an mp4's own sample table and a
204+/// Matroska file has none. Now the copy that cannot be made is a decode and a
205+/// re-encode (`export::copy_audio` -> `encode_audio`), so the export carries the
206+/// film's sound instead of naming what it cannot do with it. The picture half of
207+/// the same export is [`an_av1_export_reopens_through_our_own_demuxer`].
207208 #[test]
208209 #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
209-fn an_mp4_export_of_a_matroska_source_is_refused_by_name() {
210+fn an_mp4_export_of_a_matroska_source_carries_its_sound() {
210211 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
211212 let meta = *session.meta();
212- let project = Project::single(asset("test_av1.mkv"), meta.frame_count);
213+ // A short one: the picture is re-encoded frame by frame and what is under
214+ // test here is the sound reaching the file, not H.264 throughput.
215+ let project = Project::single(asset("test_av1.mkv"), 15);
213216 let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id()));
214217 let _ = std::fs::remove_file(&out);
215218
216219 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
217220 let started = Instant::now();
218221 while !handle.is_finished() {
219- assert!(started.elapsed() < Duration::from_secs(120), "export hung");
222+ assert!(started.elapsed() < Duration::from_secs(300), "export hung");
220223 std::thread::sleep(Duration::from_millis(20));
221224 }
222- let refused = handle
225+ handle
223226 .result()
224227 .expect("outcome")
225- .expect_err("an mkv's AAC cannot be copied into an mp4")
226- .to_string();
227- assert!(refused.contains("test_av1.mkv"), "{refused}");
228- assert!(refused.contains("Matroska"), "{refused}");
229- assert!(refused.contains("WAV or FLAC"), "{refused}");
230- assert!(!out.exists(), "a refused export leaves no file behind");
228+ .expect("an mkv's AAC is decoded and encoded again into the mp4");
229+ let (audio, chunks) = AudioSession::open(&out)
230+ .expect("reopen the export")
231+ .expect("the export has an audio track");
232+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
233+ let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
234+ println!("mkv -> mp4: {} Hz, rms {rms:.4}", audio.sample_rate);
235+ assert!(rms > 0.001, "the film's sound is in the mp4 (rms {rms})");
236+ std::fs::remove_file(&out).unwrap();
231237 }
232238
233239 /// A short timeline out of the H.264 fixture, which is what the AV1 export tests
@@ -323,6 +329,62 @@ fn an_av1_export_reopens_through_our_own_demuxer() {
323329 std::fs::remove_file(&out).unwrap();
324330 }
325331
332+/// A timeline with sound, exported as AV1 into **both** containers: the file
333+/// carries the picture *and* the timeline's audio, and this project's own
334+/// readers are what say so -- the demuxer for the picture, the audio session for
335+/// the sound. An AV1 export used to be picture only, which is a file whose sound
336+/// went missing with nobody told.
337+///
338+/// Two frames of 720p: `rav1e` is built here without its assembly, so the length
339+/// of the timeline is the length of the test, and what is under test is the
340+/// wiring from the format to the muxer, not the encoder.
341+#[test]
342+fn an_av1_export_carries_the_timelines_sound_in_either_container() {
343+ for (format, ext) in [
344+ (engine::export::Format::Av1, "mkv"),
345+ (engine::export::Format::Av1Mp4, "mp4"),
346+ ] {
347+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av");
348+ assert!(session.cut_at(2.0 / 30.0), "two frames of it");
349+ assert!(session.delete_clip(engine::project::Lane::V1, 1));
350+ let out = std::env::temp_dir().join(format!("ve_av1_sound_{}.{ext}", std::process::id()));
351+ let _ = std::fs::remove_file(&out);
352+ let settings = ExportSettings {
353+ format,
354+ force_sw: true,
355+ ..Default::default()
356+ };
357+ let handle = session.export_to_with(&out, &settings);
358+ let started = Instant::now();
359+ while !handle.is_finished() {
360+ assert!(started.elapsed() < Duration::from_secs(300), "export hung");
361+ std::thread::sleep(Duration::from_millis(20));
362+ }
363+ handle.result().expect("outcome").expect("an AV1 export");
364+
365+ // The picture, through the demuxer an import comes in by -- an `av01`
366+ // sample entry in the mp4 and a `V_AV1` track in the Matroska file, both
367+ // of them written by hand and read back by hand.
368+ let (meta, _) = Demuxer::open(&out).expect("reopen the export");
369+ assert_eq!(meta.codec, Codec::Av1, "{ext}: an AV1 export is AV1");
370+ assert_eq!((meta.width, meta.height), (1280, 720), "{ext}");
371+ assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there");
372+
373+ // ...and the sound beside it, which is the half that used to be absent.
374+ let (audio, chunks) = AudioSession::open(&out)
375+ .expect("reopen for its sound")
376+ .expect("an AV1 export has an audio track");
377+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
378+ let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
379+ println!(
380+ "{ext}: {} Hz x{}, rms {rms:.4}",
381+ audio.sample_rate, audio.channels
382+ );
383+ assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})");
384+ std::fs::remove_file(&out).unwrap();
385+ }
386+}
387+
326388 /// An audio-only timeline is refused an AV1 export by name, exactly as it is
327389 /// refused an mp4: every frame of it is a gap, so the file would be black.
328390 #[test]
crates/engine/tests/backends.rsmodified+58 -37
@@ -96,49 +96,70 @@ fn a_playing_session_reports_the_seat_the_probe_named() {
9696 /// picture's seat is probed by opening the very encoder the export opens, and
9797 /// the sound's is decided outright. A drift between them is a front-end lying
9898 /// about the machine, which is exactly what this whole surface is for.
99+///
100+/// Every picture format, because each one is a different pair of seats: H.264
101+/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either
102+/// container -- a container is not an encoder, and the card must not say it is.
99103 #[test]
100104 fn the_planned_encoders_are_the_ones_the_job_opens() {
101- let settings = ExportSettings {
102- format: Format::Mp4,
103- ..ExportSettings::default()
104- };
105- let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
106- let planned = format!(
107- "{} · {}",
108- engine::export::planned_video(session.meta(), &settings).expect("an mp4 carries picture"),
109- session.planned_audio(Format::Mp4)
110- );
111- let out = out_path("planned", "mp4");
112- let handle = session.export_to_with(&out, &settings);
113- let started = Instant::now();
114- let opened = loop {
115- if let Some(line) = handle.encoders() {
116- break line;
117- }
118- assert!(
119- !handle.is_finished(),
120- "the export settled before it opened an encoder: {:?}",
121- handle.result().map(|r| r.err())
105+ for (format, ext) in [
106+ (Format::Mp4, "mp4"),
107+ (Format::Av1, "mkv"),
108+ (Format::Av1Mp4, "mp4"),
109+ ] {
110+ let settings = ExportSettings {
111+ format,
112+ ..ExportSettings::default()
113+ };
114+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
115+ let planned = format!(
116+ "{} · {}",
117+ engine::export::planned_video(session.meta(), &settings)
118+ .expect("these formats carry picture"),
119+ session.planned_audio(format)
122120 );
123- assert!(
124- started.elapsed() < Duration::from_secs(60),
125- "no encoder was published"
126- );
127- std::thread::sleep(Duration::from_millis(10));
128- };
129- // Nothing here wants the file, only the seat it was going to be written
130- // with: cancelling deletes the `.part` the worker had started.
131- handle.cancel();
132- wind_down(&handle);
133- assert_eq!(opened, planned);
121+ let out = out_path("planned", ext);
122+ let handle = session.export_to_with(&out, &settings);
123+ let started = Instant::now();
124+ let opened = loop {
125+ if let Some(line) = handle.encoders() {
126+ break line;
127+ }
128+ assert!(
129+ !handle.is_finished(),
130+ "the export settled before it opened an encoder: {:?}",
131+ handle.result().map(|r| r.err())
132+ );
133+ assert!(
134+ started.elapsed() < Duration::from_secs(60),
135+ "no encoder was published"
136+ );
137+ std::thread::sleep(Duration::from_millis(10));
138+ };
139+ // Nothing here wants the file, only the seat it was going to be written
140+ // with: cancelling deletes the `.part` the worker had started.
141+ handle.cancel();
142+ wind_down(&handle);
143+ assert_eq!(opened, planned, "{ext}");
144+ // ...and the sound is named on both, AV1 included: an AV1 export
145+ // carries the timeline's audio now, so a line that said nothing about
146+ // it would be the old picture-only lie in a new place.
147+ assert!(planned.contains("AAC"), "{ext}: {planned}");
148+ }
134149 }
135150
136151 /// A WAV job has no picture at all and still names what writes it, so an audio
137152 /// export is not a progress line with nothing to say.
138153 #[test]
139154 fn an_audio_only_job_names_its_encoder() {
155+ for format in [Format::Wav, Format::Flac, Format::Mp3] {
156+ audio_only_job_names_its_encoder(format);
157+ }
158+}
159+
160+fn audio_only_job_names_its_encoder(format: Format) {
140161 let settings = ExportSettings {
141- format: Format::Wav,
162+ format,
142163 ..ExportSettings::default()
143164 };
144165 assert_eq!(
@@ -149,11 +170,11 @@ fn an_audio_only_job_names_its_encoder() {
149170 &settings
150171 ),
151172 None,
152- "a WAV has no video seat to name"
173+ "an audio-only format has no video seat to name"
153174 );
154175 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
155- let planned = session.planned_audio(Format::Wav);
156- let out = out_path("wav", "wav");
176+ let planned = session.planned_audio(format);
177+ let out = out_path("audio", format.ext());
157178 let handle = session.export_to_with(&out, &settings);
158179 let started = Instant::now();
159180 let opened = loop {
@@ -169,7 +190,7 @@ fn an_audio_only_job_names_its_encoder() {
169190 handle.cancel();
170191 wind_down(&handle);
171192 let _ = std::fs::remove_file(&out);
172- assert_eq!(opened, planned);
193+ assert_eq!(opened, planned, "{}", format.ext());
173194 }
174195
175196 /// Waits for a cancelled job to settle, so its `.part` is gone before the test
crates/engine/tests/lanes.rsmodified+40 -6
@@ -363,14 +363,48 @@ fn two_audio_lanes_are_summed() {
363363 out_two / out_one
364364 );
365365
366- // The mp4 path *copies* AAC packets and cannot mix: it refuses by name
367- // rather than writing a file missing half its sound.
366+ // ...and the mp4 of the same timeline carries that very mix. It used to be
367+ // a refusal by name -- the mp4 path *copies* AAC packets and a mix is not a
368+ // copy -- and a refusal is what a file missing half its sound deserves;
369+ // this decodes both lanes and encodes the sum instead (`export::copy_audio`
370+ // routes to `encode_audio`), which is the same mix the WAV above measured.
368371 let out = out_path("mixed", "mp4");
369372 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
370- let err = wait(&handle, Duration::from_secs(120)).expect_err("mp4 cannot mix");
371- println!("mp4 refusal: {err}");
372- assert!(err.to_string().contains("2 audio lanes"), "{err}");
373- assert!(!out.exists(), "a refused export leaves no file");
373+ wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes");
374+ let (audio, chunks) = engine::AudioSession::open(&out)
375+ .expect("reopen the export")
376+ .expect("it has an audio track");
377+ let coded: Vec<f64> = chunks
378+ .into_iter()
379+ .flat_map(|c| c.samples)
380+ .map(|s| f64::from(s) * f64::from(i16::MAX))
381+ .collect();
382+ let per = f64::from(audio.sample_rate) / FPS * f64::from(audio.channels);
383+ let window = |from: u32, to: u32| {
384+ let (a, b) = (
385+ (f64::from(from) * per) as usize,
386+ (f64::from(to) * per) as usize,
387+ );
388+ let w = &coded[a.min(coded.len())..b.min(coded.len())];
389+ (w.iter().map(|s| s * s).sum::<f64>() / w.len().max(1) as f64).sqrt()
390+ };
391+ let (coded_over, coded_out) = (
392+ window(TOP_IN + 5, TOP_OUT - 5),
393+ window(TOP_OUT + 5, TOTAL - 5),
394+ );
395+ println!("mp4 rms: under A2 {coded_over:.1}, past it {coded_out:.1}");
396+ // Against the WAV of the same timeline, not against a figure: one lossy
397+ // generation moves the level by a fraction of a dB and nothing here is
398+ // measuring the encoder.
399+ assert!(
400+ (coded_over / over_two - 1.0).abs() < 0.1,
401+ "the mp4's overlap is {coded_over:.1} against the mix's {over_two:.1}"
402+ );
403+ assert!(
404+ (coded_out / out_two - 1.0).abs() < 0.1,
405+ "past A2 the mp4 is {coded_out:.1} against the mix's {out_two:.1}"
406+ );
407+ std::fs::remove_file(&out).unwrap();
374408 }
375409
376410 /// A project with one lane of each kind is what it always was: the composite of
crates/engine/tests/speed.rsmodified+24 -19
@@ -301,25 +301,33 @@ fn a_wav_export_of_a_2x_timeline_matches_the_preview() {
301301 std::fs::remove_file(&out).ok();
302302 }
303303
304-/// The half that refuses: an mp4 *copies* AAC packets and a packet carries no
305-/// rate, so a speeded clip **on the lane being copied** is refused by name --
306-/// never written out at 1.00x under a re-timed picture. Only that lane: the
307-/// picture honours a rate (below), and AV1 has no audio to copy at all.
304+/// The other half of the same rule, and it used to be a refusal: an mp4 *copies*
305+/// AAC packets and a packet carries no rate, so a speeded clip on the lane being
306+/// copied could only have come out at 1.00x under a re-timed picture. It is
307+/// decoded, resampled and encoded again now (`export::copy_audio` routes a
308+/// speeded lane to `encode_audio`), so the file carries the sound that was
309+/// heard -- measured the way the WAV above is, by where the beep lands.
308310 #[test]
309-fn an_mp4_export_refuses_a_speeded_sound_clip_by_name() {
311+fn an_mp4_export_resamples_a_speeded_sound_clip() {
310312 let (mut project, meta) = sync_project();
311313 project
312314 .set_speed(Lane::A1, 0, Speed::from_permille(2000))
313315 .expect("room enough");
314- let out = out_path("refuse", "mp4");
316+ let heard = beep_at(&play(&project));
317+ let out = out_path("speeded", "mp4");
315318 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
316- let text = wait(&handle, Duration::from_secs(120))
317- .expect_err("an mp4 export cannot carry a rate in a copied packet")
318- .to_string();
319- assert!(text.contains("2.00x"), "{text}");
320- assert!(text.contains("00:00"), "{text}");
321- assert!(text.contains("WAV or FLAC"), "{text}");
322- assert!(!out.exists(), "a refused export writes no file");
319+ wait(&handle, Duration::from_secs(180)).expect("an mp4 of a speeded sound clip");
320+ let (audio, chunks) = AudioSession::open(&out)
321+ .expect("reopen the export")
322+ .expect("it has an audio track");
323+ assert_eq!(audio.sample_rate, RATE);
324+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
325+ let in_file = beep_at(&samples);
326+ assert!(
327+ (in_file - heard).abs() <= 1.0 / FPS,
328+ "the beep is at {in_file:.3}s in the file and was at {heard:.3}s in the preview"
329+ );
330+ std::fs::remove_file(&out).ok();
323331 }
324332
325333 /// The half that honours, and the shape that catches a walk that only works at
@@ -393,8 +401,8 @@ fn an_mp4_export_honours_a_speeded_picture_across_a_rate_change() {
393401 std::fs::remove_file(&out).ok();
394402 }
395403
396-/// AV1 carries no audio at all, so nothing about a rate reaches a packet copy
397-/// there: it honours a speeded picture with no detaching and no refusal.
404+/// AV1 honours a speeded picture with no detaching and no refusal -- and its
405+/// sound, which it now carries, is resampled exactly as the mp4's is.
398406 #[test]
399407 fn an_av1_export_honours_a_speeded_take_whole() {
400408 let (mut project, meta) = sync_project();
@@ -413,10 +421,7 @@ fn an_av1_export_honours_a_speeded_take_whole() {
413421 },
414422 );
415423 wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take");
416- assert!(
417- out.exists(),
418- "AV1 never refuses a rate: it has no audio lane"
419- );
424+ assert!(out.exists(), "AV1 never refuses a rate");
420425 assert!(
421426 std::fs::metadata(&out).expect("the export").len() > 0,
422427 "and it wrote something"