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 +1360 -423

Cargo.lockmodified+7 -0
@@ -1640,6 +1640,7 @@ dependencies = [
1640 "rav1e",1640 "rav1e",
1641 "rusty_aac",1641 "rusty_aac",
1642 "rusty_h264",1642 "rusty_h264",
1643+ "rusty_mp3",
1643 "symphonia",1644 "symphonia",
1644 "symphonia-codec-aac",1645 "symphonia-codec-aac",
1645 "symphonia-core",1646 "symphonia-core",
@@ -4924,6 +4925,12 @@ dependencies = [
4924 "rusty_h264-common",4925 "rusty_h264-common",
4925 ]4926 ]
4926 4927
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+
4927 [[package]]4934 [[package]]
4928 name = "rustybuzz"4935 name = "rustybuzz"
4929 version = "0.14.1"4936 version = "0.14.1"
crates/app/src/keymap.rsmodified+2 -2
@@ -337,8 +337,8 @@ pub const FIXED: [Fixed; 16] = [
337 category: Category::File,337 category: Category::File,
338 },338 },
339 Fixed {339 Fixed {
340- chord: "m / a / w / f",340+ chord: "m / a / v / w / f / p",
341- label: "Pick the export format: MP4, AV1, WAV or FLAC",341+ label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, WAV, FLAC or MP3",
342 category: Category::File,342 category: Category::File,
343 },343 },
344 Fixed {344 Fixed {
crates/app/src/main.rsmodified+133 -111
@@ -2090,7 +2090,15 @@ impl Player {
2090 return;2090 return;
2091 };2091 };
2092 let settings = export_settings(self.quality, self.custom_mbps, self.format);2092 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;
2094 return;2102 return;
2095 }2103 }
2096 let meta = *session.meta();2104 let meta = *session.meta();
@@ -4710,7 +4718,7 @@ impl Player {
4710 let formats: Vec<_> = FORMATS4718 let formats: Vec<_> = FORMATS
4711 .into_iter()4719 .into_iter()
4712 .enumerate()4720 .enumerate()
4713- .map(|(i, (format, label, detail))| {4721+ .map(|(i, (format, _, label, detail))| {
4714 // Per row, because the two picture formats are refused by4722 // Per row, because the two picture formats are refused by
4715 // different things: an audio-only timeline greys both, a second4723 // different things: an audio-only timeline greys both, a second
4716 // audio lane only the mp4.4724 // audio lane only the mp4.
@@ -4794,7 +4802,7 @@ impl Player {
4794 .text_size(px(11.))4802 .text_size(px(11.))
4795 .text_color(rgb(INK_DIM))4803 .text_color(rgb(INK_DIM))
4796 .child(self.notice.clone().unwrap_or_else(|| {4804 .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()
4798 })),4806 })),
4799 )4807 )
4800 // Capped and scrolling like the keybindings list: the4808 // Capped and scrolling like the keybindings list: the
@@ -6927,48 +6935,67 @@ impl Quality {
6927 }6935 }
6928 }6936 }
6929 6937
6930-/// The export card's format rows: what this program can write, and what it6938+/// The export card's format rows: the key that picks one, its name, and what it
6931-/// cannot with the reason it cannot. A format with no entry at all would read6939+/// writes -- or, where this program cannot write it, the reason it cannot. A
6932-/// as an oversight, and a menu of three as a claim that nothing else exists --6940+/// format with no entry at all would read as an oversight, and a menu of three
6933-/// so the refusals are rows too, dimmed and unclickable.6941+/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
6942+/// and unclickable.
6934 ///6943 ///
6935-/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a6944+/// `None` is exactly that kind of row, and there are three left. MP3 stopped
6936-/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a6945+/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
6937-/// decision about this project rather than about the code, and the row says so6946+/// `shine-rs` was the licence question, and it is not the only encoder any
6938-/// instead of pretending the encoder does not exist. HEVC and VP9 are the two6947+/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the
6939-/// this program *reads* and cannot write -- the plugin decodes both and there is6948+/// plugin decodes both and there is no encoder for either here -- so they are
6940-/// no encoder for either here -- so they are rows for the same reason: a codec6949+/// rows for the same reason: a codec that opens but never comes back out is
6941-/// that opens but never comes back out is exactly the gap a user would other-6950+/// exactly the gap a user would otherwise go looking for. AAC is not a row at
6942-/// wise go looking for.6951+/// all: it is what both containers' sound *is*, never a file of its own.
6943-const FORMATS: [(Option<Format>, &str, &str); 9] = [6952+///
6944- (Some(Format::Mp4), "MP4", "H.264 picture + AAC sound"),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"),
6945 (6959 (
6946 Some(Format::Av1),6960 Some(Format::Av1),
6947- "AV1",6961+ "a",
6948- "AV1 picture in .mkv — no sound: export WAV or FLAC for that",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",
6949 ),6978 ),
6950- (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),6979+ (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"),
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"),
6955 (6980 (
6956 None,6981 None,
6982+ "",
6957 "HEVC",6983 "HEVC",
6958 "no encoder in this stack, and patent-encumbered",6984 "no encoder in this stack, and patent-encumbered",
6959 ),6985 ),
6960- (None, "VP9", "superseded by AV1, which is the row above"),6986+ (None, "", "VP9", "superseded by AV1, which is the row above"),
6961 ];6987 ];
6962 6988
6963-/// The format a key picks while the export card is up: the row's own initial,6989+/// The format a key picks while the export card is up. A letter of the row's
6964-/// which is unambiguous across the three that can be picked. `None` for6990+/// own name, spelled out in the table rather than taken from the initial: `MP4`
6965-/// everything else, digits included -- those are the bitrate's.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.
6966 fn format_key(key: &str) -> Option<Format> {6994 fn format_key(key: &str) -> Option<Format> {
6967 FORMATS6995 FORMATS
6968 .into_iter()6996 .into_iter()
6969- .filter_map(|(format, label, _)| format.zip(label.get(..1)))6997+ .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key))
6970- .find(|(_, initial)| initial.eq_ignore_ascii_case(key))6998+ .find_map(|(format, ..)| format)
6971- .map(|(format, _)| format)
6972 }6999 }
6973 7000
6974 /// What one of the colour card's own strokes does. Its keys are card-local --7001 /// What one of the colour card's own strokes does. Its keys are card-local --
@@ -7138,9 +7165,11 @@ fn export_line(
7138 fn format_line(format: Format) -> &'static str {7165 fn format_line(format: Format) -> &'static str {
7139 match format {7166 match format {
7140 Format::Mp4 => "H.264 · MP4 · moov at end",7167 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",
7142 Format::Wav => "16-bit PCM · WAV · timeline audio only",7170 Format::Wav => "16-bit PCM · WAV · timeline audio only",
7143 Format::Flac => "FLAC · lossless · timeline audio only",7171 Format::Flac => "FLAC · lossless · timeline audio only",
7172+ Format::Mp3 => "MP3 · 256 kbps · timeline audio only",
7144 }7173 }
7145 }7174 }
7146 7175
@@ -7150,7 +7179,7 @@ fn format_label(format: Format) -> &'static str {
7150 FORMATS7179 FORMATS
7151 .iter()7180 .iter()
7152 .find(|(row, ..)| *row == Some(format))7181 .find(|(row, ..)| *row == Some(format))
7153- .map_or("EXPORT", |(_, label, _)| *label)7182+ .map_or("EXPORT", |(_, _, label, _)| *label)
7154 }7183 }
7155 7184
7156 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.7185 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
@@ -7270,11 +7299,12 @@ fn is_bare_modifier(key: &str) -> bool {
7270 /// refuses it too (`export::start`); this is what greys the row before a7299 /// refuses it too (`export::start`); this is what greys the row before a
7271 /// destination has been picked.7300 /// destination has been picked.
7272 ///7301 ///
7273-/// The second reason is the mp4 path's alone: it *copies* one AAC track and7302+/// It is the *only* reason left. A second audio lane, a speeded clip, a source
7274-/// there is no encoder here to mix several with, so a timeline whose sound is7303+/// no mp4 sample table holds: each of those used to grey the MP4 row, because
7275-/// spread over more than one audio lane is refused by the engine7304+/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
7276-/// (`export::run`). An AV1 export carries no sound at all -- said on its row as7305+/// cannot say what the timeline says (`export::copy_audio`), so none of them is
7277-/// its detail, not as a refusal -- so no count of audio lanes stops it.7306+/// a refusal any more -- and every video format carries the sound, so there is
7307+/// nothing here that is one format's alone.
7278 fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {7308 fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
7279 if !format.has_video() {7309 if !format.has_video() {
7280 return None;7310 return None;
@@ -7283,43 +7313,13 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
7283 .lanes()7313 .lanes()
7284 .into_iter()7314 .into_iter()
7285 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());7315 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
7286- if !picture {7316+ match picture {
7287- return Some(format!(7317+ true => None,
7288- "no picture — {} would be black; export WAV or FLAC",7318+ false => Some(format!(
7319+ "no picture — {} would be black; export WAV, FLAC or MP3",
7289 format.name()7320 format.name()
7290- ));7321+ )),
7291 }7322 }
7292- if format != Format::Mp4 {
7293- return None;
7294- }
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- })
7323 }7323 }
7324 7324
7325 /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap7325 /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap
@@ -8302,14 +8302,19 @@ mod tests {
8302 // and are never refused.8302 // and are never refused.
8303 assert_eq!(8303 assert_eq!(
8304 format_refusal(&session, Format::Mp4).as_deref(),8304 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")
8306 );8306 );
8307 assert_eq!(8307 assert_eq!(
8308 format_refusal(&session, Format::Av1).as_deref(),8308 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")
8310 );8314 );
8311 assert_eq!(format_refusal(&session, Format::Wav), None);8315 assert_eq!(format_refusal(&session, Format::Wav), None);
8312 assert_eq!(format_refusal(&session, Format::Flac), None);8316 assert_eq!(format_refusal(&session, Format::Flac), None);
8317+ assert_eq!(format_refusal(&session, Format::Mp3), None);
8313 }8318 }
8314 8319
8315 fn info(8320 fn info(
@@ -9061,28 +9066,24 @@ mod tests {
9061 assert!(session.lane_clips(v2).is_empty());9066 assert!(session.lane_clips(v2).is_empty());
9062 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");9067 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
9063 9068
9064- // A second audio lane carrying sound is what an mp4 export cannot9069+ // A second audio lane used to be what an mp4 export could not write --
9065- // write, so the card greys that row before a destination is picked.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.
9066 assert_eq!(format_refusal(&session, Format::Mp4), None);9072 assert_eq!(format_refusal(&session, Format::Mp4), None);
9067 let a2 = session.add_lane(LaneKind::Audio);9073 let a2 = session.add_lane(LaneKind::Audio);
9068 assert_eq!(a2.label(), "A2");9074 assert_eq!(a2.label(), "A2");
9069- assert_eq!(
9070- format_refusal(&session, Format::Mp4),
9071- None,
9072- "an empty lane carries nothing"
9073- );
9074 assert!(9075 assert!(
9075 session9076 session
9076 .place_stream_at(0.0, &path, 0, Some(a2))9077 .place_stream_at(0.0, &path, 0, Some(a2))
9077 .expect("its own file is on this timeline")9078 .expect("its own file is on this timeline")
9078 );9079 );
9080+ for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
9079 assert_eq!(9081 assert_eq!(
9080- format_refusal(&session, Format::Mp4).as_deref(),9082+ format_refusal(&session, format),
9081- Some("2 audio lanes — an mp4 copies one")9083+ None,
9084+ "two audio lanes are a mix, not a refusal"
9082 );9085 );
9083- // ...and the one thing that does not stop an AV1 export, which carries9086+ }
9084- // no sound to have too much of.
9085- assert_eq!(format_refusal(&session, Format::Av1), None);
9086 9087
9087 // Undo, one edit at a time and backwards: the drop on A2, the lane A29088 // Undo, one edit at a time and backwards: the drop on A2, the lane A2
9088 // itself, the lift, the drop on V2, and last the lane V2 -- an added9089 // itself, the lift, the drop on V2, and last the lane V2 -- an added
@@ -10241,59 +10242,80 @@ mod tests {
10241 10242
10242 #[test]10243 #[test]
10243 fn every_format_row_is_offered_or_says_why_not() {10244 fn every_format_row_is_offered_or_says_why_not() {
10244- // The four this program can write are rows that pick. Three are named10245+ // The six this program can write are rows that pick. Four are named
10245 // after their own extension, so a destination cannot disagree with its10246 // after their own extension, so a destination cannot disagree with its
10246- // bytes; the fourth is named after its *codec*, because AV1 arrives and10247+ // bytes; the AV1 pair is named after codec *and* container, because the
10247- // leaves in a Matroska file and "MKV" would name the box rather than10248+ // same picture goes into either box and the row is the choice between
10248- // what is in it.10249+ // them.
10249 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();10250 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();
10250 assert_eq!(10251 assert_eq!(
10251 offered,10252 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+ ]
10253 );10261 );
10254 assert_eq!(Format::Av1.ext(), "mkv");10262 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 {
10256 match format {10265 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"),
10258 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),10268 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
10259 // A refused format is a row with a reason, never a hidden one:10269 // A refused format is a row with a reason, never a hidden one:
10260 // an empty detail column would read as an oversight.10270 // an empty detail column would read as an oversight.
10261 None => assert!(!label.is_empty()),10271 None => assert!(!label.is_empty()),
10262 }10272 }
10263 }10273 }
10264- for (format, label, detail) in FORMATS {10274+ for (format, stroke, label, detail) in FORMATS {
10265 assert!(!detail.is_empty(), "{label} says nothing");10275 assert!(!detail.is_empty(), "{label} says nothing");
10266- // Only the two picture formats leave the bitrate rows live -- the10276+ // Only the picture formats leave the bitrate rows live -- the card
10267- // card dims them off exactly this.10277+ // dims them off exactly this.
10268 assert_eq!(10278 assert_eq!(
10269 format.is_some_and(Format::has_video),10279 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))
10271 );10281 );
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+ }
10272 }10292 }
10273 // The two codecs this program reads and cannot write are rows of their10293 // The two codecs this program reads and cannot write are rows of their
10274 // own, refused by name rather than absent -- HEVC for want of an encoder10294 // own, refused by name rather than absent -- HEVC for want of an encoder
10275 // (and for its patents), VP9 because AV1 is the row that replaced it.10295 // (and for its patents), VP9 because AV1 is the row that replaced it.
10276 for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {10296 for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {
10277- let (format, _, detail) = FORMATS10297+ let (format, _, _, detail) = FORMATS
10278 .into_iter()10298 .into_iter()
10279- .find(|(_, row, _)| *row == label)10299+ .find(|(_, _, row, _)| *row == label)
10280 .unwrap_or_else(|| panic!("{label} has no row"));10300 .unwrap_or_else(|| panic!("{label} has no row"));
10281 assert!(format.is_none(), "{label} is not offered");10301 assert!(format.is_none(), "{label} is not offered");
10282 assert!(detail.contains(word), "{label}: {detail}");10302 assert!(detail.contains(word), "{label}: {detail}");
10283 }10303 }
10284- // The AV1 row says on the row itself that it carries no sound, which is10304+ // Both AV1 rows say they carry sound: the file used to be picture only,
10285- // the one thing a user could otherwise only find out by playing the file.10305+ // and a row that still said so would be the lie a user plays the file
10286- let (_, _, av1) = FORMATS10306+ // to find out about.
10307+ for format in [Format::Av1, Format::Av1Mp4] {
10308+ let (_, _, _, detail) = FORMATS
10287 .into_iter()10309 .into_iter()
10288- .find(|(f, ..)| *f == Some(Format::Av1))10310+ .find(|(f, ..)| *f == Some(format))
10289 .expect("an AV1 row");10311 .expect("an AV1 row");
10290- assert!(av1.contains("no sound"), "{av1}");10312+ assert!(detail.contains("sound"), "{detail}");
10291- assert!(format_line(Format::Av1).contains("picture only"));10313+ assert!(format_line(format).contains("picture and sound"));
10292- assert_eq!(10314+ }
10293- format_key("a"),10315+ assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one");
10294- Some(Format::Av1),10316+ assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one");
10295- "its own initial picks it"10317+ assert_eq!(format_key("p"), Some(Format::Mp3));
10296- );10318+ assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p");
10297 // The destination follows the format and keeps the stem, mp4 included.10319 // The destination follows the format and keeps the stem, mp4 included.
10298 assert_eq!(10320 assert_eq!(
10299 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),10321 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 }
35 # Fraunhofer's C library, which this project's no-install rule forbids. Built35 # Fraunhofer's C library, which this project's no-install rule forbids. Built
36 # from `vendor/rusty_aac` -- see the patch table in the workspace manifest.36 # from `vendor/rusty_aac` -- see the patch table in the workspace manifest.
37 rusty_aac = "0.5"37 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"
38 symphonia-core = "0.6"43 symphonia-core = "0.6"
39 symphonia-codec-aac = "0.6"44 symphonia-codec-aac = "0.6"
40 # The umbrella crate for the standalone audio files: one dependency instead of45 # 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 {
802 }802 }
803 803
804 /// One AAC-LC access unit of silence, for the gaps in an exported timeline —804 /// 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 can805+/// this is the *copy* path, which never encodes anything, so the only silence it
806-/// write is one spelled out by hand.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.)
807 ///808 ///
808 /// It is the shortest legal `raw_data_block` there is: one element carrying809 /// It is the shortest legal `raw_data_block` there is: one element carrying
809 /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no810 /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
@@ -848,11 +849,12 @@ fn source_at<'a>(
848 849
849 /// A source's track for the *copy* path, which needs raw AAC access units.850 /// A source's track for the *copy* path, which needs raw AAC access units.
850 ///851 ///
851-/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by852+/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name
852-/// name and by format rather than exported silent or, worse, exported as noise:853+/// and by format. That is no longer the end of the road: `export::copy_audio`
853-/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]),854+/// takes it as the answer "not copyable" and decodes and re-encodes the timeline
854-/// so a timeline carrying one of those simply cannot become an mp4 today. The855+/// instead, so these words are a fallback's reason rather than a user's refusal.
855-/// wording is what a front-end shows.856+/// They are still worded for a person, because a caller with no encoder to fall
857+/// back on shows them verbatim.
856 ///858 ///
857 /// `Ok(None)` for a file with no audio at all, which is a silent export.859 /// `Ok(None)` for a file with no audio at all, which is a silent export.
858 fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {860 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>> {
862 // A Matroska source gets its own words: its packets *are* AAC, so864 // A Matroska source gets its own words: its packets *are* AAC, so
863 // "export needs AAC audio today" would read as a contradiction. What865 // "export needs AAC audio today" would read as a contradiction. What
864 // they are not is packets of an mp4 sample table, which is what the866 // 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.
866 //870 //
867 // ponytail: the ceiling is the copy path being written against the mp4871 // ponytail: the ceiling is the copy path being written against the mp4
868- // reader, not anything about the bytes. Upgrade path is the same one872+ // reader, not anything about the bytes. Upgrade path is a
869- // every other refusal here names -- an AAC encoder, or a `copy_segments`873+ // `copy_segments` that walks a Matroska track, which would make this a
870- // that walks a Matroska track -- and either would let this through.874+ // copy again instead of a re-encode.
871 Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(875 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: \876+ "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \
873- it copies packets out of an mp4's own sample table. Export WAV or FLAC for \877+ a copy walks an mp4's own sample table. It is decoded and encoded again \
874- the sound, or AV1 for the picture alone",878+ instead",
875 path.file_name()879 path.file_name()
876 .unwrap_or(path.as_os_str())880 .unwrap_or(path.as_os_str())
877 .to_string_lossy(),881 .to_string_lossy(),
@@ -879,17 +883,18 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
879 .into()),883 .into()),
880 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),884 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
881 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`885 // 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 it886+ // sample table can hold. The export decodes it and encodes AAC, exactly
883- // into one. A WAV/FLAC export of the same timeline decodes fine.887+ // as it does for every other source no copy reaches.
884 Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),888 Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),
885 }889 }
886 }890 }
887 891
888-/// The one wording for "this source's audio cannot be copied into an mp4",892+/// 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.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.
890 fn uncopyable(path: &Path, codec: &str) -> crate::Error {895 fn uncopyable(path: &Path, codec: &str) -> crate::Error {
891 format!(896 format!(
892- "export needs AAC audio today; {} is {codec}",897+ "a packet copy needs AAC in an mp4; {} is {codec}",
893 path.file_name()898 path.file_name()
894 .unwrap_or(path.as_os_str())899 .unwrap_or(path.as_os_str())
895 .to_string_lossy(),900 .to_string_lossy(),
crates/engine/src/demux.rsmodified+50 -22
@@ -7,7 +7,10 @@
7 //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --7 //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --
8 //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in8 //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in
9 //! practice -- and HEVC rides the same walk, because that is the other codec a9 //! 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.
11 14
12 use std::fs::File;15 use std::fs::File;
13 use std::io::{BufReader, Read, Seek, SeekFrom};16 use std::io::{BufReader, Read, Seek, SeekFrom};
@@ -131,9 +134,9 @@ pub struct Mp4Demuxer {
131 /// (`audio::priming_samples`), and frame indices count from there.134 /// (`audio::priming_samples`), and frame indices count from there.
132 first_sample: u32,135 first_sample: u32,
133 codec: Codec,136 codec: Codec,
134- /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC),137+ /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or
135- /// re-injected ahead of every sync sample. Empty for VP9, which carries no138+ /// the sequence header OBU for AV1, re-injected ahead of every sync sample.
136- /// out-of-band parameter sets.139+ /// Empty for VP9, which carries no out-of-band parameter sets.
137 parameter_sets: Vec<u8>,140 parameter_sets: Vec<u8>,
138 /// Bytes of the NAL length prefix each sample is written with, off `avcC`141 /// Bytes of the NAL length prefix each sample is written with, off `avcC`
139 /// or `hvcC`. Unused by VP9.142 /// or `hvcC`. Unused by VP9.
@@ -160,20 +163,26 @@ impl Mp4Demuxer {
160 Ok(MediaType::H265) => Some((t, Codec::Hevc)),163 Ok(MediaType::H265) => Some((t, Codec::Hevc)),
161 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),164 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
162 // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry165 // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry
163- // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple166+ // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC
164- // and ffmpeg's mov muxer write in practice -- reports no media167+ // track -- what Apple and ffmpeg's mov muxer write in practice
165- // type at all, and the file used to read back as having no168+ // -- and every AV1 track report no media type, and such a file
166- // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are169+ // used to read back as having no video. Its sample tables
167- // parsed regardless of the entry the crate dropped, so only the170+ // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the
168- // fourcc has to be read here by hand. hvc1 differs from hev1 in171+ // entry the crate dropped, so only the fourcc has to be read
169- // that the parameter sets may not repeat in-band, which costs172+ // here by hand. hvc1 differs from hev1 in that the parameter
170- // nothing: they are re-injected out of `hvcC` ahead of every173+ // sets may not repeat in-band, which costs nothing: they are
171- // sync sample either way.174+ // re-injected out of `hvcC` ahead of every sync sample either
172- _ => (matches!(t.track_type(), Ok(TrackType::Video))175+ // way, exactly as an AV1 sequence header is out of `av1C`.
173- && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1"))176+ _ => matches!(t.track_type(), Ok(TrackType::Video))
174- .then_some((t, Codec::Hevc)),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+ }),
175 })184 })
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")?;
177 let (track, codec) = track;186 let (track, codec) = track;
178 187
179 let track_id = track.track_id();188 let track_id = track.track_id();
@@ -216,10 +225,19 @@ impl Mp4Demuxer {
216 parameter_sets = sets;225 parameter_sets = sets;
217 bit_depth = depth;226 bit_depth = depth;
218 }227 }
219- // No parameter sets: a VP9 sample is self-contained, and AV1 never228+ // The sequence header OBU out of `av1C`, re-injected ahead of every
220- // reaches this arm at all -- `mp4 0.14` knows no `av01` sample229+ // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` --
221- // entry, so AV1 only ever arrives through [`MkvDemuxer`].230+ // the same record in the same bytes, which is what makes an AV1 mp4
222- Codec::Vp9 | Codec::Av1 => {}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 => {}
223 }241 }
224 let sync_samples = track242 let sync_samples = track
225 .trak243 .trak
@@ -273,6 +291,16 @@ impl Mp4Demuxer {
273 if self.codec == Codec::Vp9 {291 if self.codec == Codec::Vp9 {
274 return Ok(Some(sample.bytes.to_vec()));292 return Ok(Some(sample.bytes.to_vec()));
275 }293 }
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+ }
276 304
277 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);305 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
278 if sample.is_sync {306 if sample.is_sync {
@@ -1075,7 +1103,7 @@ fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>>
1075 /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first1103 /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
1076 /// malformed header rather than erroring: every caller is looking for one box1104 /// malformed header rather than erroring: every caller is looking for one box
1077 /// and reports its own absence.1105 /// 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])> {
1079 std::iter::from_fn(move || {1107 std::iter::from_fn(move || {
1080 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;1108 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
1081 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize1109 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
crates/engine/src/export.rsmodified+298 -184
@@ -1,28 +1,36 @@
1-//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska —1+//! Export: the edit list rendered back out as one mp4 (H.264 or AV1) or one
2-//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone.2+//! AV1-in-Matroska — or, picture left behind, as one WAV, FLAC or MP3 of the
3+//! timeline's audio alone.
3 //!4 //!
4 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it5 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
5 //! is impossible — while audio is copied packet for packet wherever a copy can6 //! is impossible — while audio is copied packet for packet wherever a copy can
6 //! say what the timeline says: a copy is exact, free and never a generation of7 //! 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 packet8+//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an
8-//! copy can reach — that lane is decoded, mixed and encoded again with9+//! equalized one, a source that is not AAC inside an mp4's own sample table —
9-//! `rusty_aac` ([`encode_audio`]). The audio-only formats have no such split:10+//! the sound is decoded, mixed and encoded again with `rusty_aac`
10-//! `hound` writes PCM and `flacenc` encodes FLAC, so those are always *decoded*11+//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes
11-//! out of the timeline. The worker owns everything: the caller gets an12+//! 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
12 //! [`ExportHandle`] and polls it from its render loop.14 //! [`ExportHandle`] and polls it from its render loop.
13 //!15 //!
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+//!
14 //! A **speeded** clip splits along the same line, and for the same reason. The22 //! A **speeded** clip splits along the same line, and for the same reason. The
15 //! picture is re-encoded, so the frame walk honours a rate: it takes the source23 //! picture is re-encoded, so the frame walk honours a rate: it takes the source
16 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the24 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
17 //! very frame preview holds there) and encodes a held one again rather than25 //! very frame preview holds there) and encodes a held one again rather than
18 //! decoding it twice. A clip whose *file* was shot at another rate than the26 //! decoding it twice. A clip whose *file* was shot at another rate than the
19 //! timeline goes through the same walk with one more conversion on the end27 //! 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, and28+//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
21-//! a packet carries no rate -- so a speeded clip on the one audio lane an mp429+//! The sound is *copied* unless something forces a decode, and a packet carries
22-//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x30+//! no rate — so a speeded lane is one of the things that forces one
23-//! under a re-timed picture.31+//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
24-//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are32+//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate
25-//! decoded and resampled, so they honour a rate like the picture does.33+//! like the picture does.
26 //!34 //!
27 //! Nothing partial survives a failure: the worker writes to `<out>.part` and35 //! Nothing partial survives a failure: the worker writes to `<out>.part` and
28 //! renames it onto `out` only once the file is closed and complete, so the36 //! renames it onto `out` only once the file is closed and complete, so the
@@ -32,6 +40,8 @@
32 //! behind (only in-process cleanup is promised), which is an orphan a user can40 //! behind (only in-process cleanup is promised), which is an orphan a user can
33 //! delete rather than a file that plays for two seconds and stops.41 //! delete rather than a file that plays for two seconds and stops.
34 42
43+use std::fs::File;
44+use std::io::{BufWriter, Write};
35 use std::path::{Path, PathBuf};45 use std::path::{Path, PathBuf};
36 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};46 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
37 use std::sync::{Arc, Mutex};47 use std::sync::{Arc, Mutex};
@@ -63,37 +73,42 @@ const MAX_BITRATE: u64 = 20_000_000;
63 /// on a build with no assembly, which is what this one is.73 /// on a build with no assembly, which is what this one is.
64 const AV1_SPEED: u8 = 10;74 const AV1_SPEED: u8 = 10;
65 75
66-/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are76+/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the
67-/// the only *video* pairs with both an encoder and a decoder under this77+/// user's pick of container -- are the only *video* pairs with both an encoder
68-/// project's no-install rule, and WAV and FLAC are the only *standalone* audio78+/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are
69-/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under79+/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and
70-/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis80+/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is
71-/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp481+/// what a re-encoded video track's sound leaves through -- but AAC is a
72-/// track is encoded with -- but AAC is an mp4's own audio, never a file of its82+/// container's own audio, never a file of its own here.) HEVC and VP9 have no
73-/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import83+/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there).
74-/// through the plugin and stop there). A front-end says so rather than hiding84+/// A front-end says so rather than hiding the rows.
75-/// 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.
76 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]89 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
77 pub enum Format {90 pub enum Format {
78 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,91 /// 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 it92+ /// where a copy could not carry the edit (a second audio lane to mix in, a
80- /// carries **one** audio lane: a timeline whose sound is spread over two is93+ /// speeded clip, an equalized one, a source no mp4 sample table holds).
81- /// refused by name here and mixed by the other two formats, which decode.
82 #[default]94 #[default]
83 Mp4,95 Mp4,
84- /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound96+ /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
85- /// this project can *write*: this engine's Matroska writer has no audio97+ /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
86- /// track at all, and the copy path walks an mp4 sample table, which a98+ /// reader reads one back, symphonia's `mkv` reader being what
87- /// Matroska file has none of. (*Reading* one's AAC is a different question,99+ /// `audio::Track::open` opens it with.
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.
92 Av1,100 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.
94 Wav,107 Wav,
95- /// The audio lane alone, losslessly compressed.108+ /// The audio lanes alone, losslessly compressed.
96 Flac,109 Flac,
110+ /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`).
111+ Mp3,
97 }112 }
98 113
99 impl Format {114 impl Format {
@@ -101,26 +116,36 @@ impl Format {
101 /// the destination path from it, so the name never disagrees with the bytes.116 /// the destination path from it, so the name never disagrees with the bytes.
102 pub fn ext(self) -> &'static str {117 pub fn ext(self) -> &'static str {
103 match self {118 match self {
104- Self::Mp4 => "mp4",119+ Self::Mp4 | Self::Av1Mp4 => "mp4",
105 Self::Av1 => "mkv",120 Self::Av1 => "mkv",
106 Self::Wav => "wav",121 Self::Wav => "wav",
107 Self::Flac => "flac",122 Self::Flac => "flac",
123+ Self::Mp3 => "mp3",
108 }124 }
109 }125 }
110 126
111 /// Whether this format carries the picture. The bitrate settings are video127 /// 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.
113 pub fn has_video(self) -> bool {129 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)
115 }138 }
116 139
117 /// What the format is called where a refusal names it.140 /// What the format is called where a refusal names it.
118 pub fn name(self) -> &'static str {141 pub fn name(self) -> &'static str {
119 match self {142 match self {
120 Self::Mp4 => "an mp4",143 Self::Mp4 => "an mp4",
121- Self::Av1 => "an AV1 export",144+ Self::Av1 => "an AV1 Matroska",
145+ Self::Av1Mp4 => "an AV1 mp4",
122 Self::Wav => "a WAV",146 Self::Wav => "a WAV",
123 Self::Flac => "a FLAC",147 Self::Flac => "a FLAC",
148+ Self::Mp3 => "an MP3",
124 }149 }
125 }150 }
126 }151 }
@@ -241,12 +266,12 @@ pub fn start(
241 Err("the timeline is empty: there is nothing to export".into())266 Err("the timeline is empty: there is nothing to export".into())
242 }267 }
243 format if format.has_video() && !has_picture(&project) => Err(format!(268 format if format.has_video() && !has_picture(&project) => Err(format!(
244- "the timeline has no picture: {} would be black. Export WAV or \269+ "the timeline has no picture: {} would be black. Export WAV, \
245- FLAC, which are the sound itself",270+ FLAC or MP3, which are the sound itself",
246 format.name()271 format.name()
247 )272 )
248 .into()),273 .into()),
249- Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings),274+ format if format.has_video() => run(&project, &meta, &part, &worker, &settings),
250 format => run_audio(&project, &meta, &part, &worker, format),275 format => run_audio(&project, &meta, &part, &worker, format),
251 };276 };
252 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));277 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> {
314 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;339 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
315 let bitrate = bitrate_of(meta, settings);340 let bitrate = bitrate_of(meta, settings);
316 match settings.format {341 match settings.format {
317- // Opt-in only, for the reason [`Enc::open_av1`] states in full.342+ // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
318- Format::Av1 if !forced("VE_HW_AV1") => None,343+ // AV1 formats sit on it: the container is not the encoder's business.
319- Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate),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+ }
320 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),348 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
321 }349 }
322 }350 }
@@ -327,34 +355,65 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
327 /// place, so what a card says before an export and what its progress line says355 /// place, so what a card says before an export and what its progress line says
328 /// during one cannot drift apart.356 /// during one cannot drift apart.
329 fn video_label(format: Format, hw: bool) -> &'static str {357 fn video_label(format: Format, hw: bool) -> &'static str {
330- match (format, hw) {358+ match (format.is_av1(), hw) {
331- (Format::Av1, true) => "HW encode (VA-API)",
332- (Format::Av1, false) => "SW encode (rav1e)",
333 (_, true) => "HW encode (VA-API)",359 (_, true) => "HW encode (VA-API)",
334- (_, false) => "SW encode (rusty_h264)",360+ (true, false) => "SW encode (rav1e)",
361+ (false, false) => "SW encode (rusty_h264)",
335 }362 }
336 }363 }
337 364
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+
338 /// What the sound is written by. Every audio encoder here is software -- there383 /// 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, and384+/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
340-/// whether an mp4 escapes encoding altogether by copying the packets it was385+/// whether a container escapes encoding altogether by copying the packets it was
341-/// given. Empty for AV1, which carries no audio at all: a caller joins this to386+/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
342-/// a line that already says so, and repeating it would cost a line of card.387+/// timeline's sound too, so leaving it unnamed would be the old lie.
343-fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str {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+ }
344 match format {402 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",
349 Format::Wav => "PCM · SW (hound)",403 Format::Wav => "PCM · SW (hound)",
350 Format::Flac => "FLAC · SW (flacenc)",404 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+ },
351 }410 }
352 }411 }
353 412
354 /// What [`start`] would write this timeline's sound with, before one is413 /// What [`start`] would write this timeline's sound with, before one is
355 /// started. Pure: no probe and no file opened, so a card may ask it per repaint.414 /// started. Pure: no probe and no file opened, so a card may ask it per repaint.
356 pub fn planned_audio(project: &Project, format: Format) -> &'static str {415 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)
358 }417 }
359 418
360 /// What [`start`] would encode the picture with, probed the way the export419 /// What [`start`] would encode the picture with, probed the way the export
@@ -376,19 +435,32 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
376 shared.finished.store(true, Ordering::Release);435 shared.finished.store(true, Ordering::Release);
377 }436 }
378 437
379-/// The timeline's one audio lane, copied packet for packet: the mp4 path's438+/// The audio track an export writes, and how it was made -- a copy is the
380-/// sound, and the reason that path carries only one lane of it. A lane an439+/// source's own packets, bit for bit, and anything else is this project's
381-/// equalizer has been put on cannot be *copied* at all and leaves through440+/// encoder over the decoded mix. [`run`] publishes which of the two really
382-/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit.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.
383 ///459 ///
384 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per460 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per
385 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming461 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
386 /// `copy_segments` that yields packets instead of collecting them.462 /// `copy_segments` that yields packets instead of collecting them.
387-#[allow(clippy::type_complexity)]463+fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
388-fn copy_audio(
389- project: &Project,
390- meta: &VideoMeta,
391-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
392 // The segments name their source, and the copy carries its packet-rounding464 // The segments name their source, and the copy carries its packet-rounding
393 // debt across a source join exactly as across a cut, so a timeline spanning465 // debt across a source join exactly as across a cut, so a timeline spanning
394 // files stays in sync. A source whose AAC parameters disagree with the466 // files stays in sync. A source whose AAC parameters disagree with the
@@ -399,16 +471,10 @@ fn copy_audio(
399 // is the same list `PlaybackSession::seek` hands the decoder, so an export471 // is the same list `PlaybackSession::seek` hands the decoder, so an export
400 // of a timeline playing a file's second audio track carries *that* track.472 // of a timeline playing a file's second audio track carries *that* track.
401 //473 //
402- // One lane, because this path *copies* AAC packets and a mix is not a copy:474+ // One lane is the only shape a *copy* has: summing two means decoding both,
403- // summing two lanes means decoding both, and only the one thing a copy475+ // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
404- // cannot express at all -- an equalizer -- is decoded here today. Refused by476+ // very mix the WAV path writes -- it used to be a refusal, and a refusal is
405- // name rather than silently exporting the first lane, which is a file477+ // what a file missing half its sound deserves, not what a mix does.
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.
412 //478 //
413 // *Which* lane is the same question `audio_segments_from` answers for479 // *Which* lane is the same question `audio_segments_from` answers for
414 // playback, and it is asked here rather than assumed: the lane that holds480 // playback, and it is asked here rather than assumed: the lane that holds
@@ -418,68 +484,59 @@ fn copy_audio(
418 // whole comment is about.484 // whole comment is about.
419 let lanes = project.audio_segments_from(0, meta.frame_rate);485 let lanes = project.audio_segments_from(0, meta.frame_rate);
420 let [segments] = &lanes[..] else {486 let [segments] = &lanes[..] else {
421- return Err(format!(487+ return encode_audio(project, meta);
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());
427 };488 };
428 // ...and the same list names *which* lane those clips sit on, which is the489 // ...and the same list names *which* lane those clips sit on, which is the
429 // only way to ask what has been done to them.490 // only way to ask what has been done to them.
430 let lane = project.audio_lanes()[0];491 let lane = project.audio_lanes()[0];
431 // ...and the same list decides whether any clip this would copy plays at a492 // ...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 very493+ // rate other than the one it was recorded at. A copy hands the muxer the
433- // AAC packets the source holds and there is no rate inside a packet to494+ // very AAC packets the source holds and there is no rate inside a packet to
434 // change: the picture would come out re-timed (the walk in [`run`] honours495 // change: the picture would come out re-timed (the walk in [`run`] honours
435 // it) over sound at 1.00x, which is the drift a person finds only after the496 // 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 lane497+ // file has gone somewhere. Decoded and resampled instead, by the same worker
437- // being copied: AV1 carries no audio at all and never reaches this, so it498+ // playback feeds from.
438- // honours a speed like WAV and FLAC do.
439 //499 //
440- // ponytail: the ceiling is the packet copy itself, not the rate, and the way500+ // ...and whether any clip on it carries an equalizer, which is sample math a
441- // off it is now next door -- [`encode_audio`] resamples exactly as the WAV501+ // copy never reaches: copying such a lane would write the clip *flat*,
442- // path does, so routing a speeded lane there is the one line the equalizer502+ // silently.
443- // below takes. Left refused because this change is the equalizer's, and a503+ //
444- // speeded export turning silently from a copy into a re-encode is a change504+ // A frame *rate* of its own is not one of those, and that is deliberate: do
445- // of its own to make on purpose.505+ // not "fix" this into a re-encode. A clip counts the **timeline's** frames
446- if let Some((at, speed)) = project506+ // whatever its file was shot at ([`crate::project::Rate`]), so the window
447- .lane(lane)507+ // this copy trims a source's sound to is `start..end` in whole timeline
448- .iter()508+ // frames -- exactly the seconds the picture covers -- and the file is read
449- .find(|c| !c.speed.is_normal())509+ // at the pitch it was recorded at, which is what playing at the rate it was
450- .map(|c| (c.start, c.speed))510+ // shot at means. There is no per-clip stretch to express, so the packets are
451- {511+ // already the right sound in the right place; re-encoding a conformed lane
452- return Err(format!(512+ // would buy nothing and cost a generation of loss on every mixed-rate export
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
468 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`513 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
469 // measures the copied sound against the picture). A *speed* is different514 // 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.
471 //516 //
472- // ...and last, whether any clip on it carries an equalizer. An EQ is sample517+ // Only these: a timeline nobody has touched still leaves through the copy
473- // math and a copy never decodes, so copying such a lane would write the clip518+ // below, packet for packet, so no passthrough quietly becomes a generation
474- // *flat*, silently -- the failure a missing audio track is. This lane is519+ // of loss.
475- // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and520+ let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
476- // only this case is: a timeline nobody has equalized still leaves through521+ if speeded || equalized(project) {
477- // the copy below, packet for packet, so no passthrough quietly becomes a
478- // generation of loss.
479- if equalized(project) {
480 return encode_audio(project, meta);522 return encode_audio(project, meta);
481 }523 }
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+ }
483 }540 }
484 541
485 /// The same lane, *decoded*: what a packet copy cannot carry comes out here as542 /// The same lane, *decoded*: what a packet copy cannot carry comes out here as
@@ -499,11 +556,7 @@ fn copy_audio(
499 /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers556 /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
500 /// the whole stream anyway, since it encodes its frames in parallel. Upgrade557 /// the whole stream anyway, since it encodes its frames in parallel. Upgrade
501 /// path is a chunked push once that encoder streams.558 /// path is a chunked push once that encoder streams.
502-#[allow(clippy::type_complexity)]559+fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
503-fn encode_audio(
504- project: &Project,
505- meta: &VideoMeta,
506-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
507 let sources = project.audio_sources();560 let sources = project.audio_sources();
508 let segs = project.audio_segments_from(0, meta.frame_rate);561 let segs = project.audio_segments_from(0, meta.frame_rate);
509 let eqs = project.audio_eqs_from(0, meta.frame_rate);562 let eqs = project.audio_eqs_from(0, meta.frame_rate);
@@ -515,7 +568,8 @@ fn encode_audio(
515 };568 };
516 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {569 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
517 format!(570 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",
519 audio.sample_rate573 audio.sample_rate
520 )574 )
521 })?;575 })?;
@@ -555,8 +609,8 @@ fn encode_audio(
555 samples: packet.duration,609 samples: packet.duration,
556 });610 });
557 }611 }
558- Ok(Some((612+ Ok(Some(ExportAudio {
559- crate::AacTrackParams {613+ params: crate::AacTrackParams {
560 freq_index,614 freq_index,
561 // 1 and 2 are the ISO channel configurations for mono and stereo,615 // 1 and 2 are the ISO channel configurations for mono and stereo,
562 // and the opener refuses anything wider than stereo already.616 // and the opener refuses anything wider than stereo already.
@@ -564,7 +618,8 @@ fn encode_audio(
564 sample_rate: audio.sample_rate,618 sample_rate: audio.sample_rate,
565 },619 },
566 packets,620 packets,
567- )))621+ copied: false,
622+ }))
568 }623 }
569 624
570 fn run(625 fn run(
@@ -577,19 +632,22 @@ fn run(
577 let total = project.timeline_frames();632 let total = project.timeline_frames();
578 let sources = project.sources();633 let sources = project.sources();
579 // Audio first: a track has to be declared when the muxer is created, which634 // 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 --635+ // happens as soon as the first coded picture arrives -- and the Matroska
581- // that one is picture only, for the reason [`Format::Av1`] states -- and no636+ // muxer wants the packets themselves that early too, because it interleaves
582- // refusal of it either: a timeline with sound is exported as the video it637+ // them into the clusters as it writes. Every video format gets the same
583- // also is, and the front-end says the sound is not in the file *before* the638+ // track: none of them is picture-only any more.
584- // export starts rather than failing it here.639+ let audio = copy_audio(project, meta)?;
585- let audio = match settings.format {640+ let audio_params = audio.as_ref().map(|track| AudioParams {
586- Format::Av1 => None,641+ freq_index: track.params.freq_index,
587- _ => copy_audio(project, meta)?,642+ chan_conf: track.params.chan_conf,
588- };643+ sample_rate: track.params.sample_rate,
589- let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
590- freq_index: track.freq_index,
591- chan_conf: track.chan_conf,
592 });644 });
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);
593 651
594 // One header parse per source, before any of them is decoded: what rate652 // One header parse per source, before any of them is decoded: what rate
595 // each file was shot at against the timeline's ([`Rate`]), which is how the653 // each file was shot at against the timeline's ([`Rate`]), which is how the
@@ -607,13 +665,11 @@ fn run(
607 // refused reads as the software one that took over rather than as the hope665 // refused reads as the software one that took over rather than as the hope
608 // it replaced -- and the sound says whether it was copied or encoded, which666 // it replaced -- and the sound says whether it was copied or encoded, which
609 // `copy_audio` decided a few lines up.667 // `copy_audio` decided a few lines up.
610- *shared.encoders.lock().unwrap() = Some(668+ *shared.encoders.lock().unwrap() = Some(format!(
611- match audio_label(project, settings.format, audio.is_some()) {669+ "{} · {}",
612- // AV1: no sound in the file and none to name.670+ encoder.label(),
613- "" => encoder.label().to_string(),671+ audio_label(project, settings.format, sound.is_some(), sound)
614- sound => format!("{} · {sound}", encoder.label()),672+ ));
615- },
616- );
617 let mut muxer = None;673 let mut muxer = None;
618 let mut done = 0u32;674 let mut done = 0u32;
619 let black = Black::new(meta);675 let black = Black::new(meta);
@@ -739,6 +795,7 @@ fn run(
739 meta,795 meta,
740 settings,796 settings,
741 audio_params.as_ref(),797 audio_params.as_ref(),
798+ &mut packets,
742 au,799 au,
743 key,800 key,
744 )?;801 )?;
@@ -758,6 +815,7 @@ fn run(
758 meta,815 meta,
759 settings,816 settings,
760 audio_params.as_ref(),817 audio_params.as_ref(),
818+ &mut packets,
761 au,819 au,
762 key,820 key,
763 )?;821 )?;
@@ -769,8 +827,10 @@ fn run(
769 let Some(muxer) = muxer else {827 let Some(muxer) = muxer else {
770 return Err("export produced no coded pictures".into());828 return Err("export produced no coded pictures".into());
771 };829 };
772- let muxer = match (muxer, audio) {830+ // The mp4's audio track after its picture -- the Matroska one interleaved
773- (Muxer::Mp4(mut mp4), Some((_, packets))) => {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)) => {
774 for packet in packets {834 for packet in packets {
775 mp4.write_audio_packet(&packet.bytes)?;835 mp4.write_audio_packet(&packet.bytes)?;
776 }836 }
@@ -802,18 +862,6 @@ fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
802 }862 }
803 }863 }
804 864
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-
817 /// The audio lanes alone, summed, as a WAV or a FLAC.865 /// The audio lanes alone, summed, as a WAV or a FLAC.
818 ///866 ///
819 /// Nothing here re-derives the edit: the play lists are867 /// Nothing here re-derives the edit: the play lists are
@@ -855,7 +903,7 @@ fn run_audio(
855 };903 };
856 // The picture path's line, for a file that is sound alone: there is sound904 // The picture path's line, for a file that is sound alone: there is sound
857 // by the line above, so this names the encoder writing it.905 // 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());
859 let channels = usize::from(audio.channels);907 let channels = usize::from(audio.channels);
860 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate908 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
861 * f64::from(audio.sample_rate))909 * f64::from(audio.sample_rate))
@@ -887,7 +935,10 @@ fn run_audio(
887 match format {935 match format {
888 Format::Wav => write_wav(out, &samples, &audio)?,936 Format::Wav => write_wav(out, &samples, &audio)?,
889 Format::Flac => write_flac(out, &samples, &audio)?,937 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+ }
891 }942 }
892 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);943 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
893 Ok(())944 Ok(())
@@ -914,6 +965,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()
914 Ok(())965 Ok(())
915 }966 }
916 967
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+
917 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to1004 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
918 /// text: they are not `Send + Sync`, and every one of them fails the export the1005 /// text: they are not `Send + Sync`, and every one of them fails the export the
919 /// same way.1006 /// same way.
@@ -1014,27 +1101,36 @@ fn write_video(
1014 meta: &VideoMeta,1101 meta: &VideoMeta,
1015 settings: &ExportSettings,1102 settings: &ExportSettings,
1016 audio: Option<&AudioParams>,1103 audio: Option<&AudioParams>,
1104+ packets: &mut Option<Vec<crate::AacPacket>>,
1017 au: &[u8],1105 au: &[u8],
1018 key: bool,1106 key: bool,
1019 ) -> crate::Result<()> {1107 ) -> crate::Result<()> {
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+ }
1020 if settings.format == Format::Av1 {1122 if settings.format == Format::Av1 {
1021 let muxer = match muxer {1123 let muxer = match muxer {
1022 Some(Muxer::Mkv(mkv)) => mkv,1124 Some(Muxer::Mkv(mkv)) => mkv,
1023 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),1125 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
1024 none => {1126 none => {
1025- // Every AV1 stream opens on a keyframe, and a keyframe carries1127+ // The sound with it, all of it: the Matroska muxer writes the
1026- // the sequence header the track has to declare: an encoder that1128+ // packets into the clusters of the pictures they play under.
1027- // handed back neither has produced nothing a decoder can start.1129+ let sound = audio.zip(packets.take());
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(1130 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
1031 out,1131 out,
1032- &Av1Params {1132+ &params(meta, au)?,
1033- width: meta.width,1133+ sound,
1034- height: meta.height,
1035- frame_rate: meta.frame_rate,
1036- config,
1037- },
1038 )?)) else {1134 )?)) else {
1039 unreachable!("just inserted a Matroska muxer")1135 unreachable!("just inserted a Matroska muxer")
1040 };1136 };
@@ -1043,6 +1139,22 @@ fn write_video(
1043 };1139 };
1044 return muxer.write_frame(au, key);1140 return muxer.write_frame(au, key);
1045 }1141 }
1142+ let muxer = match muxer {
1143+ Some(Muxer::Mp4(mp4)) => mp4,
1144+ Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
1145+ none => {
1146+ let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
1147+ out,
1148+ &params(meta, au)?,
1149+ audio,
1150+ )?)) else {
1151+ unreachable!("just inserted an mp4 muxer")
1152+ };
1153+ mp4
1154+ }
1155+ };
1156+ return muxer.write_av1_frame(au, key);
1157+ }
1046 if !crate::mux::has_coded_slice(au) {1158 if !crate::mux::has_coded_slice(au) {
1047 return Ok(());1159 return Ok(());
1048 }1160 }
@@ -1123,7 +1235,9 @@ impl Enc {
1123 }1235 }
1124 1236
1125 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {1237 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() {
1127 return Self::open_av1(meta, settings);1241 return Self::open_av1(meta, settings);
1128 }1242 }
1129 // A caller's number goes through the same clamp as the computed one: a1243 // A caller's number goes through the same clamp as the computed one: a
crates/engine/src/mux.rsmodified+537 -18
@@ -5,10 +5,17 @@
5 //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all,5 //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all,
6 //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read6 //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read
7 //! as EBML by hand ([`MkvMuxer`]).7 //! 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.
8 15
9-use std::fs::File;16+use std::fs::{File, OpenOptions};
10-use std::io::{BufWriter, Seek, SeekFrom, Write};17+use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
11-use std::path::Path;18+use std::path::{Path, PathBuf};
12 19
13 use mp4::{20 use mp4::{
14 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,21 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
@@ -41,20 +48,31 @@ pub struct VideoParams<'a> {
41 pub pps: &'a [u8],48 pub pps: &'a [u8],
42 }49 }
43 50
44-/// Read straight off the source file's `esds`: export copies AAC packets, it51+/// What the audio track declares: read straight off the source file's `esds`
45-/// never re-encodes, so the decoder config is passed through unchanged.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.
46 pub struct AudioParams {56 pub struct AudioParams {
47 pub freq_index: u8,57 pub freq_index: u8,
48 pub chan_conf: u8,58 pub chan_conf: u8,
59+ pub sample_rate: u32,
49 }60 }
50 61
51-/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores62+/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores
52 /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so63 /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so
53 /// every sample handed over must carry an exact duration or the tracks drift.64 /// every sample handed over must carry an exact duration or the tracks drift.
54 pub struct Mp4Muxer {65 pub struct Mp4Muxer {
55 writer: Mp4Writer<BufWriter<File>>,66 writer: Mp4Writer<BufWriter<File>>,
56 frame_duration: u32,67 frame_duration: u32,
57 has_audio: bool,68 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,
58 }76 }
59 77
60 const VIDEO_TRACK: u32 = 1;78 const VIDEO_TRACK: u32 = 1;
@@ -65,6 +83,61 @@ impl Mp4Muxer {
65 path: &Path,83 path: &Path,
66 video: &VideoParams,84 video: &VideoParams,
67 audio: Option<&AudioParams>,85 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>>,
68 ) -> crate::Result<Self> {141 ) -> crate::Result<Self> {
69 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {142 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
70 return Err(format!("bad frame rate {}", video.frame_rate).into());143 return Err(format!("bad frame rate {}", video.frame_rate).into());
@@ -88,10 +161,15 @@ impl Mp4Muxer {
88 &Mp4Config {161 &Mp4Config {
89 major_brand: FourCC::from(*b"isom"),162 major_brand: FourCC::from(*b"isom"),
90 minor_version: 512,163 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.
91 compatible_brands: vec![166 compatible_brands: vec![
92 FourCC::from(*b"isom"),167 FourCC::from(*b"isom"),
93 FourCC::from(*b"iso2"),168 FourCC::from(*b"iso2"),
94- FourCC::from(*b"avc1"),169+ FourCC::from(match av1c {
170+ Some(_) => *b"av01",
171+ None => *b"avc1",
172+ }),
95 FourCC::from(*b"mp41"),173 FourCC::from(*b"mp41"),
96 ],174 ],
97 // The video track's own, deliberately: `mp4` converts every175 // The video track's own, deliberately: `mp4` converts every
@@ -116,6 +194,9 @@ impl Mp4Muxer {
116 })?;194 })?;
117 if let Some(audio) = audio {195 if let Some(audio) = audio {
118 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;196 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.
119 let sample_rate = freq_index.freq();200 let sample_rate = freq_index.freq();
120 writer.add_track(&TrackConfig {201 writer.add_track(&TrackConfig {
121 track_type: TrackType::Audio,202 track_type: TrackType::Audio,
@@ -134,6 +215,8 @@ impl Mp4Muxer {
134 writer,215 writer,
135 frame_duration,216 frame_duration,
136 has_audio: audio.is_some(),217 has_audio: audio.is_some(),
218+ av1c,
219+ path: path.to_path_buf(),
137 })220 })
138 }221 }
139 222
@@ -154,6 +237,28 @@ impl Mp4Muxer {
154 Ok(())237 Ok(())
155 }238 }
156 239
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+
157 /// One raw AAC packet (no ADTS header), copied verbatim from the source --262 /// One raw AAC packet (no ADTS header), copied verbatim from the source --
158 /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC263 /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
159 /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.264 /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
@@ -178,8 +283,119 @@ impl Mp4Muxer {
178 283
179 pub fn finish(mut self) -> crate::Result<()> {284 pub fn finish(mut self) -> crate::Result<()> {
180 self.writer.write_end()?;285 self.writer.write_end()?;
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()?;
181 Ok(())319 Ok(())
182 }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;
347+ }
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);
183 }399 }
184 400
185 // Matroska element ids, written with the leading length marker they carry in the401 // Matroska element ids, written with the leading length marker they carry in the
@@ -210,6 +426,10 @@ const DEFAULT_DURATION: u32 = 0x23E383;
210 const VIDEO: u32 = 0xE0;426 const VIDEO: u32 = 0xE0;
211 const PIXEL_WIDTH: u32 = 0xB0;427 const PIXEL_WIDTH: u32 = 0xB0;
212 const PIXEL_HEIGHT: u32 = 0xBA;428 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;
213 const CLUSTER: u32 = 0x1F43_B675;433 const CLUSTER: u32 = 0x1F43_B675;
214 const CLUSTER_TIMESTAMP: u32 = 0xE7;434 const CLUSTER_TIMESTAMP: u32 = 0xE7;
215 const SIMPLE_BLOCK: u32 = 0xA3;435 const SIMPLE_BLOCK: u32 = 0xA3;
@@ -251,11 +471,17 @@ pub struct Av1Params<'a> {
251 pub config: &'a [u8],471 pub config: &'a [u8],
252 }472 }
253 473
254-/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project474+/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC
255-/// has no encoder for any sound Matroska carries, and copying the timeline's AAC475+/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the
256-/// in would write a track its own reader refuses (`audio::AudioSession::open`476+/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what
257-/// leaves a Matroska file silent) -- so the sound is named as left out by the477+/// symphonia's `mkv` reader -- this project's own way back in -- configures its
258-/// front-end rather than written unplayable.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.
259 ///485 ///
260 /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size486 /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size
261 /// and the duration -- so a killed process leaves an unfinished file rather than487 /// and the duration -- so a killed process leaves an unfinished file rather than
@@ -272,10 +498,36 @@ pub struct MkvMuxer {
272 cluster: Vec<u8>,498 cluster: Vec<u8>,
273 cluster_ts: i64,499 cluster_ts: i64,
274 frames: u64,500 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,
275 }516 }
276 517
277 impl MkvMuxer {518 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> {
279 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {531 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
280 return Err(format!("bad frame rate {}", video.frame_rate).into());532 return Err(format!("bad frame rate {}", video.frame_rate).into());
281 }533 }
@@ -335,6 +587,9 @@ impl MkvMuxer {
335 elem(&mut entry, VIDEO, &dims);587 elem(&mut entry, VIDEO, &dims);
336 let mut tracks = Vec::new();588 let mut tracks = Vec::new();
337 elem(&mut tracks, TRACK_ENTRY, &entry);589 elem(&mut tracks, TRACK_ENTRY, &entry);
590+ if let Some((audio, _)) = &audio {
591+ elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?);
592+ }
338 elem(&mut head, TRACKS, &tracks);593 elem(&mut head, TRACKS, &tracks);
339 594
340 let mut file = File::create(path)?;595 let mut file = File::create(path)?;
@@ -347,6 +602,12 @@ impl MkvMuxer {
347 cluster: Vec::new(),602 cluster: Vec::new(),
348 cluster_ts: 0,603 cluster_ts: 0,
349 frames: 0,604 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+ }),
350 })611 })
351 }612 }
352 613
@@ -373,14 +634,58 @@ impl MkvMuxer {
373 self.cluster_ts = ts;634 self.cluster_ts = ts;
374 uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);635 uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
375 }636 }
376- let mut block = Vec::with_capacity(obus.len() + 4);637+ // The sound this picture plays under goes in first, into the cluster the
377- block.push(0x81); // track number 1, as a one-byte EBML integer638+ // 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
378 block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes());685 block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes());
379 block.push(if key { 0x80 } else { 0 });686 block.push(if key { 0x80 } else { 0 });
380- block.extend_from_slice(obus);687+ block.extend_from_slice(payload);
381 elem(&mut self.cluster, SIMPLE_BLOCK, &block);688 elem(&mut self.cluster, SIMPLE_BLOCK, &block);
382- self.frames += 1;
383- Ok(())
384 }689 }
385 690
386 fn flush(&mut self) -> crate::Result<()> {691 fn flush(&mut self) -> crate::Result<()> {
@@ -399,6 +704,9 @@ impl MkvMuxer {
399 /// Closes the last cluster and patches the two fields that could not be704 /// Closes the last cluster and patches the two fields that could not be
400 /// known while writing: the segment's size and the presentation duration.705 /// known while writing: the segment's size and the presentation duration.
401 pub fn finish(mut self) -> crate::Result<()> {706 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)?;
402 self.flush()?;710 self.flush()?;
403 if self.frames == 0 {711 if self.frames == 0 {
404 return Err("no frames were written to the Matroska file".into());712 return Err("no frames were written to the Matroska file".into());
@@ -417,6 +725,52 @@ impl MkvMuxer {
417 }725 }
418 }726 }
419 727
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+
420 /// The sequence header OBU of a coded temporal unit, for the track's774 /// The sequence header OBU of a coded temporal unit, for the track's
421 /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe775 /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe
422 /// of a stream never may -- no decoder can start without it.776 /// of a stream never may -- no decoder can start without it.
@@ -750,6 +1104,7 @@ mod tests {
750 Some(&AudioParams {1104 Some(&AudioParams {
751 freq_index: 4, // 441001105 freq_index: 4, // 44100
752 chan_conf: 2,1106 chan_conf: 2,
1107+ sample_rate: 44_100,
753 }),1108 }),
754 )1109 )
755 .unwrap();1110 .unwrap();
@@ -840,6 +1195,168 @@ mod tests {
840 assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]);1195 assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]);
841 }1196 }
842 1197
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+
843 /// The Matroska half of the round trip, with no encoder in it: three coded1360 /// The Matroska half of the round trip, with no encoder in it: three coded
844 /// units out through the muxer and back in through our own demuxer, which is1361 /// units out through the muxer and back in through our own demuxer, which is
845 /// where the hand-written EBML meets the hand-written EBML reader.1362 /// where the hand-written EBML meets the hand-written EBML reader.
@@ -861,6 +1378,7 @@ mod tests {
861 frame_rate: 30.0,1378 frame_rate: 30.0,
862 config,1379 config,
863 },1380 },
1381+ None,
864 )1382 )
865 .unwrap();1383 .unwrap();
866 muxer.write_frame(&key, true).unwrap();1384 muxer.write_frame(&key, true).unwrap();
@@ -903,6 +1421,7 @@ mod tests {
903 frame_rate: 30.0,1421 frame_rate: 30.0,
904 config: &[],1422 config: &[],
905 },1423 },
1424+ None,
906 )1425 )
907 .is_err()1426 .is_err()
908 );1427 );
crates/engine/tests/audio_decode.rsmodified+5 -3
@@ -160,8 +160,10 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
160 }160 }
161 }161 }
162 162
163-/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC163+/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the
164-/// encoder here -- and that refusal is named, never a silent silent export.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.
165 #[test]167 #[test]
166 fn an_ac3_source_refuses_an_mp4_audio_copy() {168 fn an_ac3_source_refuses_an_mp4_audio_copy() {
167 let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {169 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() {
169 };171 };
170 let err = err.to_string();172 let err = err.to_string();
171 assert!(173 assert!(
172- err.contains("needs AAC audio") && err.contains("AC-3"),174+ err.contains("needs AAC in an mp4") && err.contains("AC-3"),
173 "unhelpful refusal: {err}"175 "unhelpful refusal: {err}"
174 );176 );
175 }177 }
crates/engine/tests/audio_export.rsmodified+115 -5
@@ -55,8 +55,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
55 /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`.55 /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`.
56 ///56 ///
57 /// Three things at once: a cut, a gap (which must arrive as silence), and a57 /// 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 an58+/// source no mp4 sample table holds — an mp3, which the mp4 path decodes and
59-/// mp3 on the timeline can *only* leave through this door.59+/// re-encodes today and once refused outright.
60 fn mixed_project() -> Project {60 fn mixed_project() -> Project {
61 let clip = |start, source| Clip {61 let clip = |start, source| Clip {
62 start,62 start,
@@ -252,6 +252,116 @@ fn exports_the_timeline_as_a_flac() {
252 std::fs::remove_file(&out).unwrap();252 std::fs::remove_file(&out).unwrap();
253 }253 }
254 254
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+
255 /// Cancel leaves nothing behind -- not the output, not the `.part`. The365 /// Cancel leaves nothing behind -- not the output, not the `.part`. The
256 /// timeline is long enough (a minute of audio) that the escape lands mid-decode366 /// timeline is long enough (a minute of audio) that the escape lands mid-decode
257 /// rather than after the file is already closed.367 /// rather than after the file is already closed.
@@ -307,9 +417,9 @@ fn a_silent_timeline_refuses_an_audio_export() {
307 );417 );
308 }418 }
309 419
310-/// An AC-3 source leaves through this door and no other: the mp4 export cannot420+/// An AC-3 source through the audio-only door: the mp4 export cannot
311-/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the421+/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline
312-/// same timeline decodes, downmixes and reopens through the engine's own reader.422+/// decodes, downmixes and reopens through the engine's own reader.
313 #[test]423 #[test]
314 fn a_51_ac3_source_round_trips_through_a_wav() {424 fn a_51_ac3_source_round_trips_through_a_wav() {
315 let source = asset("test_ac3_51.mp4");425 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() {
273 assert_eq!(273 assert_eq!(
274 e.to_string(),274 e.to_string(),
275 "the timeline has no picture: an mp4 would be black. \275 "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"
277 );277 );
278 assert!(!mp4.exists(), "the refusal wrote a file anyway");278 assert!(!mp4.exists(), "the refusal wrote a file anyway");
279 279
@@ -415,16 +415,19 @@ fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
415 }415 }
416 }416 }
417 417
418-/// The export copies AAC packets and has no encoder, so a timeline carrying an418+/// The *copy* path names what it cannot copy, by file and by format. That is a
419-/// mp3 cannot become an mp4 -- named, with its format, rather than exported419+/// fallback's reason rather than a user's refusal now -- `export::copy_audio`
420-/// silent or exported wrong.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.
421 #[test]424 #[test]
422 fn an_export_refuses_audio_it_cannot_copy() {425 fn an_export_refuses_audio_it_cannot_copy() {
423 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];426 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];
424 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];427 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
425 assert_eq!(428 assert_eq!(
426 refusal(AudioSession::copy_multi_segments(&sources, &segs)),429 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"
428 );431 );
429 // A timeline of nothing but mp4 still exports, which is the invariant this432 // A timeline of nothing but mp4 still exports, which is the invariant this
430 // refusal must not have cost.433 // 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() {
185 );185 );
186 }186 }
187 187
188-/// The copy side of a gap: there is no AAC encoder here, so the hole is copied188+/// The copy side of a gap: a copy never encodes, so the hole is copied
189 /// as hand-written silent packets -- real access units, one 1024-frame stts189 /// as hand-written silent packets -- real access units, one 1024-frame stts
190 /// entry each, the rounding debt carried through them like any other segment.190 /// entry each, the rounding debt carried through them like any other segment.
191 /// Every packet after the gap therefore still lands at its timeline position.191 /// 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() {
195 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");195 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");
196 }196 }
197 197
198-/// An mp4 export of a Matroska source is refused by name, and says where the198+/// An mp4 export of a Matroska source carries its sound.
199-/// sound can go instead.
200 ///199 ///
201-/// It used to *succeed*, silently, and only because this engine could not read200+/// Three lives, this one. It used to *succeed* silently and write picture with
202-/// a Matroska file's audio at all: the export wrote picture with no sound in it201+/// no sound, because this engine could not read a Matroska file's audio at all.
203-/// and nobody was told. Now that the sound is read (`tests/hevc_mkv.rs`), the202+/// Then the sound became readable and this became a refusal by name, because
204-/// rule the whole mp4 path is built on applies to it like to any other source203+/// the mp4 path could only *copy* AAC out of an mp4's own sample table and a
205-/// it cannot copy -- an AC-3 mp4 has always been refused in the same breath.204+/// Matroska file has none. Now the copy that cannot be made is a decode and a
206-/// The picture half of the same export is [`an_av1_export_reopens_through_our_own_demuxer`].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`].
207 #[test]208 #[test]
208 #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]209 #[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() {
210 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");211 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
211 let meta = *session.meta();212 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);
213 let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id()));216 let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id()));
214 let _ = std::fs::remove_file(&out);217 let _ = std::fs::remove_file(&out);
215 218
216 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());219 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
217 let started = Instant::now();220 let started = Instant::now();
218 while !handle.is_finished() {221 while !handle.is_finished() {
219- assert!(started.elapsed() < Duration::from_secs(120), "export hung");222+ assert!(started.elapsed() < Duration::from_secs(300), "export hung");
220 std::thread::sleep(Duration::from_millis(20));223 std::thread::sleep(Duration::from_millis(20));
221 }224 }
222- let refused = handle225+ handle
223 .result()226 .result()
224 .expect("outcome")227 .expect("outcome")
225- .expect_err("an mkv's AAC cannot be copied into an mp4")228+ .expect("an mkv's AAC is decoded and encoded again into the mp4");
226- .to_string();229+ let (audio, chunks) = AudioSession::open(&out)
227- assert!(refused.contains("test_av1.mkv"), "{refused}");230+ .expect("reopen the export")
228- assert!(refused.contains("Matroska"), "{refused}");231+ .expect("the export has an audio track");
229- assert!(refused.contains("WAV or FLAC"), "{refused}");232+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
230- assert!(!out.exists(), "a refused export leaves no file behind");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();
231 }237 }
232 238
233 /// A short timeline out of the H.264 fixture, which is what the AV1 export tests239 /// 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() {
323 std::fs::remove_file(&out).unwrap();329 std::fs::remove_file(&out).unwrap();
324 }330 }
325 331
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+
326 /// An audio-only timeline is refused an AV1 export by name, exactly as it is388 /// An audio-only timeline is refused an AV1 export by name, exactly as it is
327 /// refused an mp4: every frame of it is a gap, so the file would be black.389 /// refused an mp4: every frame of it is a gap, so the file would be black.
328 #[test]390 #[test]
crates/engine/tests/backends.rsmodified+31 -10
@@ -96,19 +96,29 @@ fn a_playing_session_reports_the_seat_the_probe_named() {
96 /// picture's seat is probed by opening the very encoder the export opens, and96 /// picture's seat is probed by opening the very encoder the export opens, and
97 /// the sound's is decided outright. A drift between them is a front-end lying97 /// the sound's is decided outright. A drift between them is a front-end lying
98 /// about the machine, which is exactly what this whole surface is for.98 /// 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.
99 #[test]103 #[test]
100 fn the_planned_encoders_are_the_ones_the_job_opens() {104 fn the_planned_encoders_are_the_ones_the_job_opens() {
105+ for (format, ext) in [
106+ (Format::Mp4, "mp4"),
107+ (Format::Av1, "mkv"),
108+ (Format::Av1Mp4, "mp4"),
109+ ] {
101 let settings = ExportSettings {110 let settings = ExportSettings {
102- format: Format::Mp4,111+ format,
103 ..ExportSettings::default()112 ..ExportSettings::default()
104 };113 };
105 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");114 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
106 let planned = format!(115 let planned = format!(
107 "{} · {}",116 "{} · {}",
108- engine::export::planned_video(session.meta(), &settings).expect("an mp4 carries picture"),117+ engine::export::planned_video(session.meta(), &settings)
109- session.planned_audio(Format::Mp4)118+ .expect("these formats carry picture"),
119+ session.planned_audio(format)
110 );120 );
111- let out = out_path("planned", "mp4");121+ let out = out_path("planned", ext);
112 let handle = session.export_to_with(&out, &settings);122 let handle = session.export_to_with(&out, &settings);
113 let started = Instant::now();123 let started = Instant::now();
114 let opened = loop {124 let opened = loop {
@@ -130,15 +140,26 @@ fn the_planned_encoders_are_the_ones_the_job_opens() {
130 // with: cancelling deletes the `.part` the worker had started.140 // with: cancelling deletes the `.part` the worker had started.
131 handle.cancel();141 handle.cancel();
132 wind_down(&handle);142 wind_down(&handle);
133- assert_eq!(opened, planned);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+ }
134 }149 }
135 150
136 /// A WAV job has no picture at all and still names what writes it, so an audio151 /// A WAV job has no picture at all and still names what writes it, so an audio
137 /// export is not a progress line with nothing to say.152 /// export is not a progress line with nothing to say.
138 #[test]153 #[test]
139 fn an_audio_only_job_names_its_encoder() {154 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) {
140 let settings = ExportSettings {161 let settings = ExportSettings {
141- format: Format::Wav,162+ format,
142 ..ExportSettings::default()163 ..ExportSettings::default()
143 };164 };
144 assert_eq!(165 assert_eq!(
@@ -149,11 +170,11 @@ fn an_audio_only_job_names_its_encoder() {
149 &settings170 &settings
150 ),171 ),
151 None,172 None,
152- "a WAV has no video seat to name"173+ "an audio-only format has no video seat to name"
153 );174 );
154 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");175 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
155- let planned = session.planned_audio(Format::Wav);176+ let planned = session.planned_audio(format);
156- let out = out_path("wav", "wav");177+ let out = out_path("audio", format.ext());
157 let handle = session.export_to_with(&out, &settings);178 let handle = session.export_to_with(&out, &settings);
158 let started = Instant::now();179 let started = Instant::now();
159 let opened = loop {180 let opened = loop {
@@ -169,7 +190,7 @@ fn an_audio_only_job_names_its_encoder() {
169 handle.cancel();190 handle.cancel();
170 wind_down(&handle);191 wind_down(&handle);
171 let _ = std::fs::remove_file(&out);192 let _ = std::fs::remove_file(&out);
172- assert_eq!(opened, planned);193+ assert_eq!(opened, planned, "{}", format.ext());
173 }194 }
174 195
175 /// Waits for a cancelled job to settle, so its `.part` is gone before the test196 /// 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() {
363 out_two / out_one363 out_two / out_one
364 );364 );
365 365
366- // The mp4 path *copies* AAC packets and cannot mix: it refuses by name366+ // ...and the mp4 of the same timeline carries that very mix. It used to be
367- // rather than writing a file missing half its sound.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.
368 let out = out_path("mixed", "mp4");371 let out = out_path("mixed", "mp4");
369 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());372 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
370- let err = wait(&handle, Duration::from_secs(120)).expect_err("mp4 cannot mix");373+ wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes");
371- println!("mp4 refusal: {err}");374+ let (audio, chunks) = engine::AudioSession::open(&out)
372- assert!(err.to_string().contains("2 audio lanes"), "{err}");375+ .expect("reopen the export")
373- assert!(!out.exists(), "a refused export leaves no file");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();
374 }408 }
375 409
376 /// A project with one lane of each kind is what it always was: the composite of410 /// 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() {
301 std::fs::remove_file(&out).ok();301 std::fs::remove_file(&out).ok();
302 }302 }
303 303
304-/// The half that refuses: an mp4 *copies* AAC packets and a packet carries no304+/// The other half of the same rule, and it used to be a refusal: an mp4 *copies*
305-/// rate, so a speeded clip **on the lane being copied** is refused by name --305+/// AAC packets and a packet carries no rate, so a speeded clip on the lane being
306-/// never written out at 1.00x under a re-timed picture. Only that lane: the306+/// copied could only have come out at 1.00x under a re-timed picture. It is
307-/// picture honours a rate (below), and AV1 has no audio to copy at all.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.
308 #[test]310 #[test]
309-fn an_mp4_export_refuses_a_speeded_sound_clip_by_name() {311+fn an_mp4_export_resamples_a_speeded_sound_clip() {
310 let (mut project, meta) = sync_project();312 let (mut project, meta) = sync_project();
311 project313 project
312 .set_speed(Lane::A1, 0, Speed::from_permille(2000))314 .set_speed(Lane::A1, 0, Speed::from_permille(2000))
313 .expect("room enough");315 .expect("room enough");
314- let out = out_path("refuse", "mp4");316+ let heard = beep_at(&play(&project));
317+ let out = out_path("speeded", "mp4");
315 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());318 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
316- let text = wait(&handle, Duration::from_secs(120))319+ wait(&handle, Duration::from_secs(180)).expect("an mp4 of a speeded sound clip");
317- .expect_err("an mp4 export cannot carry a rate in a copied packet")320+ let (audio, chunks) = AudioSession::open(&out)
318- .to_string();321+ .expect("reopen the export")
319- assert!(text.contains("2.00x"), "{text}");322+ .expect("it has an audio track");
320- assert!(text.contains("00:00"), "{text}");323+ assert_eq!(audio.sample_rate, RATE);
321- assert!(text.contains("WAV or FLAC"), "{text}");324+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
322- assert!(!out.exists(), "a refused export writes no file");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();
323 }331 }
324 332
325 /// The half that honours, and the shape that catches a walk that only works at333 /// 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() {
393 std::fs::remove_file(&out).ok();401 std::fs::remove_file(&out).ok();
394 }402 }
395 403
396-/// AV1 carries no audio at all, so nothing about a rate reaches a packet copy404+/// AV1 honours a speeded picture with no detaching and no refusal -- and its
397-/// there: it honours a speeded picture with no detaching and no refusal.405+/// sound, which it now carries, is resampled exactly as the mp4's is.
398 #[test]406 #[test]
399 fn an_av1_export_honours_a_speeded_take_whole() {407 fn an_av1_export_honours_a_speeded_take_whole() {
400 let (mut project, meta) = sync_project();408 let (mut project, meta) = sync_project();
@@ -413,10 +421,7 @@ fn an_av1_export_honours_a_speeded_take_whole() {
413 },421 },
414 );422 );
415 wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take");423 wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take");
416- assert!(424+ assert!(out.exists(), "AV1 never refuses a rate");
417- out.exists(),
418- "AV1 never refuses a rate: it has no audio lane"
419- );
420 assert!(425 assert!(
421 std::fs::metadata(&out).expect("the export").len() > 0,426 std::fs::metadata(&out).expect("the export").len() > 0,
422 "and it wrote something"427 "and it wrote something"