forge
Explore
Log in

Don't you dare go Hollow

Every video format carries sound, AV1 picks its box, MP3 is a row

Browse files at this commit

5ebd3acac637733451e021f8c1f1a02043d2ab2bAhmet Kaan GümüşParent: aa9c851
  • feat
    • every video format carries sound, AV1 picks its box, MP3 is a row
Show full message
✨ feat(export): every video format carries sound, AV1 picks its box, MP3 is a row

Three asks, one seam — the export's audio path was a packet copy, and everything
it could not copy was a refusal.

- MkvMuxer gains an A_AAC track (CodecPrivate = AudioSpecificConfig, CodecDelay
  one packet) and interleaves it into the clusters: an AV1 export carries the
  timeline's sound instead of naming it as left out.
- Mp4Muxer::create_av1 writes AV1 into an mp4 — the `av01` + `av1C` sample entry
  `mp4 0.14` cannot spell is patched into the finished moov (layout cribbed from
  OxideAV's oxideav-mp4, MIT); Mp4Demuxer reads that entry back.
- Format::Mp3 through `rusty_mp3` at 256 kbps CBR, and Format::Av1Mp4 beside
  Format::Av1: the export card has a row and a key for each.
- copy_audio lifts every "cannot copy" refusal into a route to encode_audio —
  a second audio lane, a speeded clip, a Matroska source, an mp3 or a png
  timeline. A copy nothing forces stays a bit-exact copy.

Round trips per container, through this project's own readers: mkv + mp4 AV1
with a tone (mux unit tests), an AV1 export in either box (tests/av1.rs), a
still under a song as an mp4 with sound and an MP3 of the timeline
(tests/audio_export.rs), two lanes summed into an mp4 (tests/lanes.rs), a
speeded lane resampled into one (tests/speed.rs).

15 changed files +1236 -373

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+128 -114
@@ -4480,7 +4480,7 @@ impl Player {
4480 let formats: Vec<_> = FORMATS4480 let formats: Vec<_> = FORMATS
4481 .into_iter()4481 .into_iter()
4482 .enumerate()4482 .enumerate()
4483- .map(|(i, (format, label, detail))| {4483+ .map(|(i, (format, _, label, detail))| {
4484 // Per row, because the two picture formats are refused by4484 // Per row, because the two picture formats are refused by
4485 // different things: an audio-only timeline greys both, a second4485 // different things: an audio-only timeline greys both, a second
4486 // audio lane only the mp4.4486 // audio lane only the mp4.
@@ -4564,7 +4564,7 @@ impl Player {
4564 .text_size(px(11.))4564 .text_size(px(11.))
4565 .text_color(rgb(INK_DIM))4565 .text_color(rgb(INK_DIM))
4566 .child(self.notice.clone().unwrap_or_else(|| {4566 .child(self.notice.clone().unwrap_or_else(|| {
4567- "pick a format (m/a/w/f), then Export — esc closes".into()4567+ "pick a format (m/a/v/w/f/p), then Export — esc closes".into()
4568 })),4568 })),
4569 )4569 )
4570 // Capped and scrolling like the keybindings list: the4570 // Capped and scrolling like the keybindings list: the
@@ -6655,48 +6655,67 @@ impl Quality {
6655 }6655 }
6656 }6656 }
6657 6657
6658-/// The export card's format rows: what this program can write, and what it6658+/// The export card's format rows: the key that picks one, its name, and what it
6659-/// cannot with the reason it cannot. A format with no entry at all would read6659+/// writes -- or, where this program cannot write it, the reason it cannot. A
6660-/// as an oversight, and a menu of three as a claim that nothing else exists --6660+/// format with no entry at all would read as an oversight, and a menu of three
6661-/// so the refusals are rows too, dimmed and unclickable.6661+/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
6662+/// and unclickable.
6662 ///6663 ///
6663-/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a6664+/// `None` is exactly that kind of row, and there are three left. MP3 stopped
6664-/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a6665+/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
6665-/// decision about this project rather than about the code, and the row says so6666+/// `shine-rs` was the licence question, and it is not the only encoder any
6666-/// instead of pretending the encoder does not exist. HEVC and VP9 are the two6667+/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the
6667-/// this program *reads* and cannot write -- the plugin decodes both and there is6668+/// plugin decodes both and there is no encoder for either here -- so they are
6668-/// no encoder for either here -- so they are rows for the same reason: a codec6669+/// rows for the same reason: a codec that opens but never comes back out is
6669-/// that opens but never comes back out is exactly the gap a user would other-6670+/// exactly the gap a user would otherwise go looking for. AAC is not a row at
6670-/// wise go looking for.6671+/// all: it is what both containers' sound *is*, never a file of its own.
6671-const FORMATS: [(Option<Format>, &str, &str); 9] = [6672+///
6672- (Some(Format::Mp4), "MP4", "H.264 picture + AAC sound"),6673+/// AV1 is two rows because a codec and a container are two choices: the same
6674+/// picture and the same AAC track go into a Matroska file or into an mp4, and
6675+/// which one a user needs is about what has to play the file, not about the
6676+/// encode.
6677+const FORMATS: [(Option<Format>, &str, &str, &str); 9] = [
6678+ (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"),
6673 (6679 (
6674 Some(Format::Av1),6680 Some(Format::Av1),
6675- "AV1",6681+ "a",
6676- "AV1 picture in .mkv — no sound: export WAV or FLAC for that",6682+ "AV1 · MKV",
6683+ "AV1 picture + AAC sound in .mkv",
6684+ ),
6685+ (
6686+ Some(Format::Av1Mp4),
6687+ "v",
6688+ "AV1 · MP4",
6689+ "the same AV1 picture and sound in .mp4",
6690+ ),
6691+ (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"),
6692+ (Some(Format::Flac), "f", "FLAC", "lossless — audio only"),
6693+ (
6694+ Some(Format::Mp3),
6695+ "p",
6696+ "MP3",
6697+ "MPEG-1 Layer III, 256 kbps — audio only",
6677 ),6698 ),
6678- (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),6699+ (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"),
6679- (Some(Format::Flac), "FLAC", "lossless — audio only"),
6680- (None, "MP3", "encoder is LGPL — licence decision pending"),
6681- (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),
6682- (None, "AAC", "an MP4's sound here, not a file of its own"),
6683 (6700 (
6684 None,6701 None,
6702+ "",
6685 "HEVC",6703 "HEVC",
6686 "no encoder in this stack, and patent-encumbered",6704 "no encoder in this stack, and patent-encumbered",
6687 ),6705 ),
6688- (None, "VP9", "superseded by AV1, which is the row above"),6706+ (None, "", "VP9", "superseded by AV1, which is the row above"),
6689 ];6707 ];
6690 6708
6691-/// The format a key picks while the export card is up: the row's own initial,6709+/// The format a key picks while the export card is up. A letter of the row's
6692-/// which is unambiguous across the three that can be picked. `None` for6710+/// own name, spelled out in the table rather than taken from the initial: `MP4`
6693-/// everything else, digits included -- those are the bitrate's.6711+/// and `MP3` share one, and so do the two AV1 containers, so an initial cannot
6712+/// tell six rows apart. Never a digit -- those are the bitrate's. `None` for
6713+/// everything else, the rows that cannot be picked included.
6694 fn format_key(key: &str) -> Option<Format> {6714 fn format_key(key: &str) -> Option<Format> {
6695 FORMATS6715 FORMATS
6696 .into_iter()6716 .into_iter()
6697- .filter_map(|(format, label, _)| format.zip(label.get(..1)))6717+ .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key))
6698- .find(|(_, initial)| initial.eq_ignore_ascii_case(key))6718+ .find_map(|(format, ..)| format)
6699- .map(|(format, _)| format)
6700 }6719 }
6701 6720
6702 /// What one of the colour card's own strokes does. Its keys are card-local --6721 /// What one of the colour card's own strokes does. Its keys are card-local --
@@ -6848,9 +6867,11 @@ fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {
6848 fn format_line(format: Format) -> &'static str {6867 fn format_line(format: Format) -> &'static str {
6849 match format {6868 match format {
6850 Format::Mp4 => "H.264 · MP4 · moov at end",6869 Format::Mp4 => "H.264 · MP4 · moov at end",
6851- Format::Av1 => "AV1 · Matroska · picture only, no audio track",6870+ Format::Av1 => "AV1 · Matroska · picture and sound",
6871+ Format::Av1Mp4 => "AV1 · MP4 · picture and sound",
6852 Format::Wav => "16-bit PCM · WAV · timeline audio only",6872 Format::Wav => "16-bit PCM · WAV · timeline audio only",
6853 Format::Flac => "FLAC · lossless · timeline audio only",6873 Format::Flac => "FLAC · lossless · timeline audio only",
6874+ Format::Mp3 => "MP3 · 256 kbps · timeline audio only",
6854 }6875 }
6855 }6876 }
6856 6877
@@ -6860,7 +6881,7 @@ fn format_label(format: Format) -> &'static str {
6860 FORMATS6881 FORMATS
6861 .iter()6882 .iter()
6862 .find(|(row, ..)| *row == Some(format))6883 .find(|(row, ..)| *row == Some(format))
6863- .map_or("EXPORT", |(_, label, _)| *label)6884+ .map_or("EXPORT", |(_, _, label, _)| *label)
6864 }6885 }
6865 6886
6866 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.6887 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
@@ -6980,11 +7001,12 @@ fn is_bare_modifier(key: &str) -> bool {
6980 /// refuses it too (`export::start`); this is what greys the row before a7001 /// refuses it too (`export::start`); this is what greys the row before a
6981 /// destination has been picked.7002 /// destination has been picked.
6982 ///7003 ///
6983-/// The second reason is the mp4 path's alone: it *copies* one AAC track and7004+/// It is the *only* reason left. A second audio lane, a speeded clip, a source
6984-/// there is no encoder here to mix several with, so a timeline whose sound is7005+/// no mp4 sample table holds: each of those used to grey the MP4 row, because
6985-/// spread over more than one audio lane is refused by the engine7006+/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
6986-/// (`export::run`). An AV1 export carries no sound at all -- said on its row as7007+/// cannot say what the timeline says (`export::copy_audio`), so none of them is
6987-/// its detail, not as a refusal -- so no count of audio lanes stops it.7008+/// a refusal any more -- and every video format carries the sound, so there is
7009+/// nothing here that is one format's alone.
6988 fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {7010 fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
6989 if !format.has_video() {7011 if !format.has_video() {
6990 return None;7012 return None;
@@ -6993,43 +7015,13 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
6993 .lanes()7015 .lanes()
6994 .into_iter()7016 .into_iter()
6995 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());7017 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
6996- if !picture {7018+ match picture {
6997- return Some(format!(7019+ true => None,
6998- "no picture — {} would be black; export WAV or FLAC",7020+ false => Some(format!(
7021+ "no picture — {} would be black; export WAV, FLAC or MP3",
6999 format.name()7022 format.name()
7000- ));7023+ )),
7001 }7024 }
7002- if format != Format::Mp4 {
7003- return None;
7004- }
7005- let audio: Vec<Lane> = session
7006- .lanes()
7007- .into_iter()
7008- .filter(|&lane| lane.kind == LaneKind::Audio && !session.lane_clips(lane).is_empty())
7009- .collect();
7010- if audio.len() > 1 {
7011- return Some(format!("{} audio lanes — an mp4 copies one", audio.len()));
7012- }
7013- // ...and the third reason, the same path's: a copied AAC packet carries no
7014- // rate, so a speeded clip on the lane being copied would come back at 1.00x
7015- // under a picture the export *does* re-time. The engine refuses it by name
7016- // (`export::copy_audio`); this greys the row before anyone picks a
7017- // destination. The picture's own rate is no reason at all -- the export walk
7018- // honours that -- so only this one lane is asked.
7019- audio
7020- .first()
7021- .and_then(|&lane| {
7022- session
7023- .lane_clips(lane)
7024- .iter()
7025- .find(|c| !c.speed.is_normal())
7026- })
7027- .map(|c| {
7028- format!(
7029- "sound at {} — an mp4 copies packets, which carry no rate",
7030- c.speed
7031- )
7032- })
7033 }7025 }
7034 7026
7035 /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap7027 /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap
@@ -7984,14 +7976,19 @@ mod tests {
7984 // and are never refused.7976 // and are never refused.
7985 assert_eq!(7977 assert_eq!(
7986 format_refusal(&session, Format::Mp4).as_deref(),7978 format_refusal(&session, Format::Mp4).as_deref(),
7987- Some("no picture — an mp4 would be black; export WAV or FLAC")7979+ Some("no picture — an mp4 would be black; export WAV, FLAC or MP3")
7988 );7980 );
7989 assert_eq!(7981 assert_eq!(
7990 format_refusal(&session, Format::Av1).as_deref(),7982 format_refusal(&session, Format::Av1).as_deref(),
7991- Some("no picture — an AV1 export would be black; export WAV or FLAC")7983+ Some("no picture — an AV1 Matroska would be black; export WAV, FLAC or MP3")
7984+ );
7985+ assert_eq!(
7986+ format_refusal(&session, Format::Av1Mp4).as_deref(),
7987+ Some("no picture — an AV1 mp4 would be black; export WAV, FLAC or MP3")
7992 );7988 );
7993 assert_eq!(format_refusal(&session, Format::Wav), None);7989 assert_eq!(format_refusal(&session, Format::Wav), None);
7994 assert_eq!(format_refusal(&session, Format::Flac), None);7990 assert_eq!(format_refusal(&session, Format::Flac), None);
7991+ assert_eq!(format_refusal(&session, Format::Mp3), None);
7995 }7992 }
7996 7993
7997 fn info(7994 fn info(
@@ -8731,28 +8728,24 @@ mod tests {
8731 assert!(session.lane_clips(v2).is_empty());8728 assert!(session.lane_clips(v2).is_empty());
8732 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");8729 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
8733 8730
8734- // A second audio lane carrying sound is what an mp4 export cannot8731+ // A second audio lane used to be what an mp4 export could not write --
8735- // write, so the card greys that row before a destination is picked.8732+ // it copied one AAC track and a mix is not a copy. It mixes now
8733+ // (`export::copy_audio`), so no row is greyed by a count of lanes.
8736 assert_eq!(format_refusal(&session, Format::Mp4), None);8734 assert_eq!(format_refusal(&session, Format::Mp4), None);
8737 let a2 = session.add_lane(LaneKind::Audio);8735 let a2 = session.add_lane(LaneKind::Audio);
8738 assert_eq!(a2.label(), "A2");8736 assert_eq!(a2.label(), "A2");
8739- assert_eq!(
8740- format_refusal(&session, Format::Mp4),
8741- None,
8742- "an empty lane carries nothing"
8743- );
8744 assert!(8737 assert!(
8745 session8738 session
8746 .place_stream_at(0.0, &path, 0, Some(a2))8739 .place_stream_at(0.0, &path, 0, Some(a2))
8747 .expect("its own file is on this timeline")8740 .expect("its own file is on this timeline")
8748 );8741 );
8749- assert_eq!(8742+ for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
8750- format_refusal(&session, Format::Mp4).as_deref(),8743+ assert_eq!(
8751- Some("2 audio lanes — an mp4 copies one")8744+ format_refusal(&session, format),
8752- );8745+ None,
8753- // ...and the one thing that does not stop an AV1 export, which carries8746+ "two audio lanes are a mix, not a refusal"
8754- // no sound to have too much of.8747+ );
8755- assert_eq!(format_refusal(&session, Format::Av1), None);8748+ }
8756 8749
8757 // Undo, one edit at a time and backwards: the drop on A2, the lane A28750 // Undo, one edit at a time and backwards: the drop on A2, the lane A2
8758 // itself, the lift, the drop on V2, and last the lane V2 -- an added8751 // itself, the lift, the drop on V2, and last the lane V2 -- an added
@@ -9837,59 +9830,80 @@ mod tests {
9837 9830
9838 #[test]9831 #[test]
9839 fn every_format_row_is_offered_or_says_why_not() {9832 fn every_format_row_is_offered_or_says_why_not() {
9840- // The four this program can write are rows that pick. Three are named9833+ // The six this program can write are rows that pick. Four are named
9841 // after their own extension, so a destination cannot disagree with its9834 // after their own extension, so a destination cannot disagree with its
9842- // bytes; the fourth is named after its *codec*, because AV1 arrives and9835+ // bytes; the AV1 pair is named after codec *and* container, because the
9843- // leaves in a Matroska file and "MKV" would name the box rather than9836+ // same picture goes into either box and the row is the choice between
9844- // what is in it.9837+ // them.
9845 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();9838 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();
9846 assert_eq!(9839 assert_eq!(
9847 offered,9840 offered,
9848- vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac]9841+ vec![
9842+ Format::Mp4,
9843+ Format::Av1,
9844+ Format::Av1Mp4,
9845+ Format::Wav,
9846+ Format::Flac,
9847+ Format::Mp3
9848+ ]
9849 );9849 );
9850 assert_eq!(Format::Av1.ext(), "mkv");9850 assert_eq!(Format::Av1.ext(), "mkv");
9851- for (format, label, _) in FORMATS {9851+ assert_eq!(Format::Av1Mp4.ext(), "mp4");
9852+ for (format, _, label, _) in FORMATS {
9852 match format {9853 match format {
9853- Some(Format::Av1) => assert_eq!(label, "AV1"),9854+ Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"),
9855+ Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"),
9854 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),9856 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
9855 // A refused format is a row with a reason, never a hidden one:9857 // A refused format is a row with a reason, never a hidden one:
9856 // an empty detail column would read as an oversight.9858 // an empty detail column would read as an oversight.
9857 None => assert!(!label.is_empty()),9859 None => assert!(!label.is_empty()),
9858 }9860 }
9859 }9861 }
9860- for (format, label, detail) in FORMATS {9862+ for (format, stroke, label, detail) in FORMATS {
9861 assert!(!detail.is_empty(), "{label} says nothing");9863 assert!(!detail.is_empty(), "{label} says nothing");
9862- // Only the two picture formats leave the bitrate rows live -- the9864+ // Only the picture formats leave the bitrate rows live -- the card
9863- // card dims them off exactly this.9865+ // dims them off exactly this.
9864 assert_eq!(9866 assert_eq!(
9865 format.is_some_and(Format::has_video),9867 format.is_some_and(Format::has_video),
9866- matches!(format, Some(Format::Mp4 | Format::Av1))9868+ matches!(format, Some(Format::Mp4 | Format::Av1 | Format::Av1Mp4))
9867 );9869 );
9870+ // Every row that can be picked has a key of its own, and no two
9871+ // share one: the card is drivable without a pointer.
9872+ assert_eq!(format.is_some(), !stroke.is_empty(), "{label}");
9873+ if !stroke.is_empty() {
9874+ assert_eq!(format_key(stroke), format, "{label} keys to itself");
9875+ assert!(
9876+ stroke.parse::<u32>().is_err(),
9877+ "{label} takes a digit the bitrate needs"
9878+ );
9879+ }
9868 }9880 }
9869 // The two codecs this program reads and cannot write are rows of their9881 // The two codecs this program reads and cannot write are rows of their
9870 // own, refused by name rather than absent -- HEVC for want of an encoder9882 // own, refused by name rather than absent -- HEVC for want of an encoder
9871 // (and for its patents), VP9 because AV1 is the row that replaced it.9883 // (and for its patents), VP9 because AV1 is the row that replaced it.
9872 for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {9884 for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {
9873- let (format, _, detail) = FORMATS9885+ let (format, _, _, detail) = FORMATS
9874 .into_iter()9886 .into_iter()
9875- .find(|(_, row, _)| *row == label)9887+ .find(|(_, _, row, _)| *row == label)
9876 .unwrap_or_else(|| panic!("{label} has no row"));9888 .unwrap_or_else(|| panic!("{label} has no row"));
9877 assert!(format.is_none(), "{label} is not offered");9889 assert!(format.is_none(), "{label} is not offered");
9878 assert!(detail.contains(word), "{label}: {detail}");9890 assert!(detail.contains(word), "{label}: {detail}");
9879 }9891 }
9880- // The AV1 row says on the row itself that it carries no sound, which is9892+ // Both AV1 rows say they carry sound: the file used to be picture only,
9881- // the one thing a user could otherwise only find out by playing the file.9893+ // and a row that still said so would be the lie a user plays the file
9882- let (_, _, av1) = FORMATS9894+ // to find out about.
9883- .into_iter()9895+ for format in [Format::Av1, Format::Av1Mp4] {
9884- .find(|(f, ..)| *f == Some(Format::Av1))9896+ let (_, _, _, detail) = FORMATS
9885- .expect("an AV1 row");9897+ .into_iter()
9886- assert!(av1.contains("no sound"), "{av1}");9898+ .find(|(f, ..)| *f == Some(format))
9887- assert!(format_line(Format::Av1).contains("picture only"));9899+ .expect("an AV1 row");
9888- assert_eq!(9900+ assert!(detail.contains("sound"), "{detail}");
9889- format_key("a"),9901+ assert!(format_line(format).contains("picture and sound"));
9890- Some(Format::Av1),9902+ }
9891- "its own initial picks it"9903+ assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one");
9892- );9904+ assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one");
9905+ assert_eq!(format_key("p"), Some(Format::Mp3));
9906+ assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p");
9893 // The destination follows the format and keeps the stem, mp4 included.9907 // The destination follows the format and keeps the stem, mp4 included.
9894 assert_eq!(9908 assert_eq!(
9895 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),9909 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+209 -140
@@ -1,26 +1,32 @@
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. The sound is *copied* unless a filter forces a decode, and26+//! decoding it twice. The sound is *copied* unless something forces a decode,
19-//! a packet carries no rate -- so a speeded clip on the one audio lane an mp427+//! and a packet carries no rate — so a speeded lane is one of the things that
20-//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x28+//! forces one ([`copy_audio`]) rather than being written out at 1.00x under a
21-//! under a re-timed picture.29+//! re-timed picture.
22-//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are
23-//! decoded and resampled, so they honour a rate like the picture does.
24 //!30 //!
25 //! Nothing partial survives a failure: the worker writes to `<out>.part` and31 //! Nothing partial survives a failure: the worker writes to `<out>.part` and
26 //! renames it onto `out` only once the file is closed and complete, so the32 //! renames it onto `out` only once the file is closed and complete, so the
@@ -30,6 +36,8 @@
30 //! behind (only in-process cleanup is promised), which is an orphan a user can36 //! behind (only in-process cleanup is promised), which is an orphan a user can
31 //! delete rather than a file that plays for two seconds and stops.37 //! delete rather than a file that plays for two seconds and stops.
32 38
39+use std::fs::File;
40+use std::io::{BufWriter, Write};
33 use std::path::{Path, PathBuf};41 use std::path::{Path, PathBuf};
34 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};42 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
35 use std::sync::{Arc, Mutex};43 use std::sync::{Arc, Mutex};
@@ -61,37 +69,42 @@ const MAX_BITRATE: u64 = 20_000_000;
61 /// on a build with no assembly, which is what this one is.69 /// on a build with no assembly, which is what this one is.
62 const AV1_SPEED: u8 = 10;70 const AV1_SPEED: u8 = 10;
63 71
64-/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are72+/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the
65-/// the only *video* pairs with both an encoder and a decoder under this73+/// user's pick of container -- are the only *video* pairs with both an encoder
66-/// project's no-install rule, and WAV and FLAC are the only *standalone* audio74+/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are
67-/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under75+/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and
68-/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis76+/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is
69-/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp477+/// what a re-encoded video track's sound leaves through -- but AAC is a
70-/// track is encoded with -- but AAC is an mp4's own audio, never a file of its78+/// container's own audio, never a file of its own here.) HEVC and VP9 have no
71-/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import79+/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there).
72-/// through the plugin and stop there). A front-end says so rather than hiding80+/// A front-end says so rather than hiding the rows.
73-/// the rows.81+///
82+/// **Every video format carries sound.** Which way it carries it is the only
83+/// difference: copied packet for packet where a copy can say what the timeline
84+/// says, decoded and encoded again ([`encode_audio`]) where it cannot.
74 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]85 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75 pub enum Format {86 pub enum Format {
76 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,87 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
77- /// where a copy could not carry the edit (an equalized lane). Either way it88+ /// where a copy could not carry the edit (a second audio lane to mix in, a
78- /// carries **one** audio lane: a timeline whose sound is spread over two is89+ /// speeded clip, an equalized one, a source no mp4 sample table holds).
79- /// refused by name here and mixed by the other two formats, which decode.
80 #[default]90 #[default]
81 Mp4,91 Mp4,
82- /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound92+ /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
83- /// this project can *write*: this engine's Matroska writer has no audio93+ /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
84- /// track at all, and the copy path walks an mp4 sample table, which a94+ /// reader reads one back, symphonia's `mkv` reader being what
85- /// Matroska file has none of. (*Reading* one's AAC is a different question,95+ /// `audio::Track::open` opens it with.
86- /// and since this engine gained a Matroska demuxer the answer is yes --
87- /// `audio::Track::open` does it through symphonia's mkv reader.) The sound
88- /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up
89- /// front.
90 Av1,96 Av1,
91- /// The audio lane alone, 16-bit PCM.97+ /// The same AV1 stream in an mp4, for everything that plays mp4 and not
98+ /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand
99+ /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
100+ /// unchanged.
101+ Av1Mp4,
102+ /// The audio lanes alone, 16-bit PCM.
92 Wav,103 Wav,
93- /// The audio lane alone, losslessly compressed.104+ /// The audio lanes alone, losslessly compressed.
94 Flac,105 Flac,
106+ /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`).
107+ Mp3,
95 }108 }
96 109
97 impl Format {110 impl Format {
@@ -99,26 +112,36 @@ impl Format {
99 /// the destination path from it, so the name never disagrees with the bytes.112 /// the destination path from it, so the name never disagrees with the bytes.
100 pub fn ext(self) -> &'static str {113 pub fn ext(self) -> &'static str {
101 match self {114 match self {
102- Self::Mp4 => "mp4",115+ Self::Mp4 | Self::Av1Mp4 => "mp4",
103 Self::Av1 => "mkv",116 Self::Av1 => "mkv",
104 Self::Wav => "wav",117 Self::Wav => "wav",
105 Self::Flac => "flac",118 Self::Flac => "flac",
119+ Self::Mp3 => "mp3",
106 }120 }
107 }121 }
108 122
109 /// Whether this format carries the picture. The bitrate settings are video123 /// Whether this format carries the picture. The bitrate settings are video
110- /// settings and mean nothing to the audio two.124+ /// settings and mean nothing to the audio-only ones.
111 pub fn has_video(self) -> bool {125 pub fn has_video(self) -> bool {
112- matches!(self, Self::Mp4 | Self::Av1)126+ matches!(self, Self::Mp4 | Self::Av1 | Self::Av1Mp4)
127+ }
128+
129+ /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
130+ /// and which of the two AV1 containers is being written are separate
131+ /// questions, and this is the first.
132+ fn is_av1(self) -> bool {
133+ matches!(self, Self::Av1 | Self::Av1Mp4)
113 }134 }
114 135
115 /// What the format is called where a refusal names it.136 /// What the format is called where a refusal names it.
116 pub fn name(self) -> &'static str {137 pub fn name(self) -> &'static str {
117 match self {138 match self {
118 Self::Mp4 => "an mp4",139 Self::Mp4 => "an mp4",
119- Self::Av1 => "an AV1 export",140+ Self::Av1 => "an AV1 Matroska",
141+ Self::Av1Mp4 => "an AV1 mp4",
120 Self::Wav => "a WAV",142 Self::Wav => "a WAV",
121 Self::Flac => "a FLAC",143 Self::Flac => "a FLAC",
144+ Self::Mp3 => "an MP3",
122 }145 }
123 }146 }
124 }147 }
@@ -227,12 +250,12 @@ pub fn start(
227 Err("the timeline is empty: there is nothing to export".into())250 Err("the timeline is empty: there is nothing to export".into())
228 }251 }
229 format if format.has_video() && !has_picture(&project) => Err(format!(252 format if format.has_video() && !has_picture(&project) => Err(format!(
230- "the timeline has no picture: {} would be black. Export WAV or \253+ "the timeline has no picture: {} would be black. Export WAV, \
231- FLAC, which are the sound itself",254+ FLAC or MP3, which are the sound itself",
232 format.name()255 format.name()
233 )256 )
234 .into()),257 .into()),
235- Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings),258+ format if format.has_video() => run(&project, &meta, &part, &worker, &settings),
236 format => run_audio(&project, &meta, &part, &worker, format),259 format => run_audio(&project, &meta, &part, &worker, format),
237 };260 };
238 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));261 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
@@ -265,10 +288,16 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
265 shared.finished.store(true, Ordering::Release);288 shared.finished.store(true, Ordering::Release);
266 }289 }
267 290
268-/// The timeline's one audio lane, copied packet for packet: the mp4 path's291+/// The timeline's audio track for a file that carries picture: copied packet for
269-/// sound, and the reason that path carries only one lane of it. A lane an292+/// packet where a copy says exactly what the timeline says, and decoded, mixed
270-/// equalizer has been put on cannot be *copied* at all and leaves through293+/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
271-/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit.294+/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
295+/// table. Nothing is refused for being uncopyable any more; the only refusals
296+/// left below the copy are about sound this engine cannot *decode* either, and
297+/// those come out of the decode path by name.
298+///
299+/// The copy is still the default and still bit-exact: a timeline nobody has
300+/// touched leaves as the very packets its source holds.
272 ///301 ///
273 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per302 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per
274 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming303 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
@@ -288,16 +317,10 @@ fn copy_audio(
288 // is the same list `PlaybackSession::seek` hands the decoder, so an export317 // is the same list `PlaybackSession::seek` hands the decoder, so an export
289 // of a timeline playing a file's second audio track carries *that* track.318 // of a timeline playing a file's second audio track carries *that* track.
290 //319 //
291- // One lane, because this path *copies* AAC packets and a mix is not a copy:320+ // One lane is the only shape a *copy* has: summing two means decoding both,
292- // summing two lanes means decoding both, and only the one thing a copy321+ // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
293- // cannot express at all -- an equalizer -- is decoded here today. Refused by322+ // very mix the WAV path writes -- it used to be a refusal, and a refusal is
294- // name rather than silently exporting the first lane, which is a file323+ // what a file missing half its sound deserves, not what a mix does.
295- // missing half its sound: the one failure a user would not notice.
296- //
297- // ponytail: the ceiling is this routing, not the codec any more.
298- // [`encode_audio`] already mixes *every* audio lane (it is the WAV path's
299- // own opener), so lifting this refusal is routing a second case to it --
300- // deliberately not done here, where the change under test is the equalizer.
301 //324 //
302 // *Which* lane is the same question `audio_segments_from` answers for325 // *Which* lane is the same question `audio_segments_from` answers for
303 // playback, and it is asked here rather than assumed: the lane that holds326 // playback, and it is asked here rather than assumed: the lane that holds
@@ -307,57 +330,44 @@ fn copy_audio(
307 // whole comment is about.330 // whole comment is about.
308 let lanes = project.audio_segments_from(0, meta.frame_rate);331 let lanes = project.audio_segments_from(0, meta.frame_rate);
309 let [segments] = &lanes[..] else {332 let [segments] = &lanes[..] else {
310- return Err(format!(333+ return encode_audio(project, meta);
311- "this timeline has {} audio lanes and an mp4 export copies one: \
312- export WAV or FLAC, which are mixed, or put the sound on one lane",
313- lanes.len()
314- )
315- .into());
316 };334 };
317 // ...and the same list names *which* lane those clips sit on, which is the335 // ...and the same list names *which* lane those clips sit on, which is the
318 // only way to ask what has been done to them.336 // only way to ask what has been done to them.
319 let lane = project.audio_lanes()[0];337 let lane = project.audio_lanes()[0];
320 // ...and the same list decides whether any clip this would copy plays at a338 // ...and the same list decides whether any clip this would copy plays at a
321- // rate other than the one it was recorded at. A copy hands the mp4 the very339+ // rate other than the one it was recorded at. A copy hands the muxer the
322- // AAC packets the source holds and there is no rate inside a packet to340+ // very AAC packets the source holds and there is no rate inside a packet to
323 // change: the picture would come out re-timed (the walk in [`run`] honours341 // change: the picture would come out re-timed (the walk in [`run`] honours
324 // it) over sound at 1.00x, which is the drift a person finds only after the342 // it) over sound at 1.00x, which is the drift a person finds only after the
325- // file has gone somewhere. Refused by name -- and only *here*, on the lane343+ // file has gone somewhere. Decoded and resampled instead, by the same worker
326- // being copied: AV1 carries no audio at all and never reaches this, so it344+ // playback feeds from.
327- // honours a speed like WAV and FLAC do.
328 //345 //
329- // ponytail: the ceiling is the packet copy itself, not the rate, and the way346+ // ...and whether any clip on it carries an equalizer, which is sample math a
330- // off it is now next door -- [`encode_audio`] resamples exactly as the WAV347+ // copy never reaches: copying such a lane would write the clip *flat*,
331- // path does, so routing a speeded lane there is the one line the equalizer348+ // silently.
332- // below takes. Left refused because this change is the equalizer's, and a349+ //
333- // speeded export turning silently from a copy into a re-encode is a change350+ // Only these: a timeline nobody has touched still leaves through the copy
334- // of its own to make on purpose.351+ // below, packet for packet, so no passthrough quietly becomes a generation
335- if let Some((at, speed)) = project352+ // of loss.
336- .lane(lane)353+ let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
337- .iter()
338- .find(|c| !c.speed.is_normal())
339- .map(|c| (c.start, c.speed))
340- {
341- return Err(format!(
342- "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \
343- no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x",
344- timecode(at, meta.frame_rate)
345- )
346- .into());
347- }
348- // ...and last, whether any clip on it carries an equalizer. An EQ is sample
349- // math and a copy never decodes, so copying such a lane would write the clip
350- // *flat*, silently -- the failure a missing audio track is. This lane is
351- // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and
352- // only this case is: a timeline nobody has equalized still leaves through
353- // the copy below, packet for packet, so no passthrough quietly becomes a
354- // generation of loss.
355 let equalized = (0..project.lane(lane).len())354 let equalized = (0..project.lane(lane).len())
356 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()));355 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()));
357- if equalized {356+ if speeded || equalized {
358 return encode_audio(project, meta);357 return encode_audio(project, meta);
359 }358 }
360- AudioSession::copy_multi_streams(&project.audio_sources(), segments)359+ // What is left is a copy the *sources* may still not be able to give: AAC
360+ // inside a Matroska file (readable, but not out of a sample table this walks
361+ // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
362+ // sources whose AAC parameters disagree. Every one of them decodes, and what
363+ // decodes can be encoded again, so the copy's refusal is now a route: the
364+ // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
365+ // which symphonia has no decoder for at any version -- is the one that comes
366+ // back, by name, from [`encode_audio`].
367+ match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
368+ Ok(copied) => Ok(copied),
369+ Err(_) => encode_audio(project, meta),
370+ }
361 }371 }
362 372
363 /// The same lane, *decoded*: what a packet copy cannot carry comes out here as373 /// The same lane, *decoded*: what a packet copy cannot carry comes out here as
@@ -393,7 +403,8 @@ fn encode_audio(
393 };403 };
394 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {404 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
395 format!(405 format!(
396- "{} Hz is not an AAC sample rate: export WAV or FLAC, which write it as it is",406+ "{} Hz is not an AAC sample rate: export WAV, FLAC or MP3, which write it as \
407+ it is",
397 audio.sample_rate408 audio.sample_rate
398 )409 )
399 })?;410 })?;
@@ -455,19 +466,19 @@ fn run(
455 let total = project.timeline_frames();466 let total = project.timeline_frames();
456 let sources = project.sources();467 let sources = project.sources();
457 // Audio first: a track has to be declared when the muxer is created, which468 // Audio first: a track has to be declared when the muxer is created, which
458- // happens as soon as the first coded picture arrives. None of it for AV1 --469+ // happens as soon as the first coded picture arrives -- and the Matroska
459- // that one is picture only, for the reason [`Format::Av1`] states -- and no470+ // muxer wants the packets themselves that early too, because it interleaves
460- // refusal of it either: a timeline with sound is exported as the video it471+ // them into the clusters as it writes. Every video format gets the same
461- // also is, and the front-end says the sound is not in the file *before* the472+ // track: none of them is picture-only any more.
462- // export starts rather than failing it here.473+ let audio = copy_audio(project, meta)?;
463- let audio = match settings.format {
464- Format::Av1 => None,
465- _ => copy_audio(project, meta)?,
466- };
467 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {474 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
468 freq_index: track.freq_index,475 freq_index: track.freq_index,
469 chan_conf: track.chan_conf,476 chan_conf: track.chan_conf,
477+ sample_rate: track.sample_rate,
470 });478 });
479+ // Taken by the Matroska muxer at creation; the mp4 one writes its track
480+ // after the picture, so for that path this is still `Some` at the end.
481+ let mut packets = audio.map(|(_, packets)| packets);
471 482
472 let mut encoder = Enc::open(meta, settings)?;483 let mut encoder = Enc::open(meta, settings)?;
473 let mut muxer = None;484 let mut muxer = None;
@@ -577,6 +588,7 @@ fn run(
577 meta,588 meta,
578 settings,589 settings,
579 audio_params.as_ref(),590 audio_params.as_ref(),
591+ &mut packets,
580 au,592 au,
581 key,593 key,
582 )?;594 )?;
@@ -596,6 +608,7 @@ fn run(
596 meta,608 meta,
597 settings,609 settings,
598 audio_params.as_ref(),610 audio_params.as_ref(),
611+ &mut packets,
599 au,612 au,
600 key,613 key,
601 )?;614 )?;
@@ -607,8 +620,10 @@ fn run(
607 let Some(muxer) = muxer else {620 let Some(muxer) = muxer else {
608 return Err("export produced no coded pictures".into());621 return Err("export produced no coded pictures".into());
609 };622 };
610- let muxer = match (muxer, audio) {623+ // The mp4's audio track after its picture -- the Matroska one interleaved
611- (Muxer::Mp4(mut mp4), Some((_, packets))) => {624+ // its own as it went and left `packets` empty behind it.
625+ let muxer = match (muxer, packets) {
626+ (Muxer::Mp4(mut mp4), Some(packets)) => {
612 for packet in packets {627 for packet in packets {
613 mp4.write_audio_packet(&packet.bytes)?;628 mp4.write_audio_packet(&packet.bytes)?;
614 }629 }
@@ -622,18 +637,6 @@ fn run(
622 Ok(())637 Ok(())
623 }638 }
624 639
625-/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
626-/// enough to sit inside a refusal and exact enough to go and find the clip.
627-/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
628-/// `00:00:12:07` in the middle of a sentence is a serial number.
629-fn timecode(frame: u32, fps: f64) -> String {
630- let secs = match fps.is_finite() && fps > 0.0 {
631- true => (f64::from(frame) / fps) as u32,
632- false => 0,
633- };
634- format!("{:02}:{:02}", secs / 60, secs % 60)
635-}
636-
637 /// The audio lanes alone, summed, as a WAV or a FLAC.640 /// The audio lanes alone, summed, as a WAV or a FLAC.
638 ///641 ///
639 /// Nothing here re-derives the edit: the play lists are642 /// Nothing here re-derives the edit: the play lists are
@@ -704,7 +707,10 @@ fn run_audio(
704 match format {707 match format {
705 Format::Wav => write_wav(out, &samples, &audio)?,708 Format::Wav => write_wav(out, &samples, &audio)?,
706 Format::Flac => write_flac(out, &samples, &audio)?,709 Format::Flac => write_flac(out, &samples, &audio)?,
707- Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"),710+ Format::Mp3 => write_mp3(out, &samples, &audio)?,
711+ Format::Mp4 | Format::Av1 | Format::Av1Mp4 => {
712+ unreachable!("the picture formats are `run`")
713+ }
708 }714 }
709 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);715 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
710 Ok(())716 Ok(())
@@ -731,6 +737,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()
731 Ok(())737 Ok(())
732 }738 }
733 739
740+/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure
741+/// Rust like every other encoder here, and the reason this format is a row at
742+/// all: the LGPL `shine-rs` was the only one when it was not.
743+///
744+/// 256 kbps CBR, for [`encode_audio`]'s reason: an export is a master a person
745+/// edits from again, not a delivery file, and this is a lossy generation over
746+/// sources that may already have been one. The rate is snapped to a legal Layer
747+/// III value by the encoder, and a sample rate MPEG has no frame for (anything
748+/// but 8-48 kHz) is refused there by name rather than written as something else.
749+///
750+/// ponytail: CBR only, and no rate is offered to the caller -- the export card
751+/// has one bitrate control and it is the *picture's*. Upgrade path is
752+/// `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
753+fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
754+ let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig {
755+ bitrate_kbps: 256,
756+ vbr_quality: None,
757+ });
758+ // The samples are the 16-bit ones a WAV of this timeline holds, so the two
759+ // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
760+ // engine's own decoders do.
761+ let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
762+ encoder
763+ .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
764+ .map_err(|e| format!("mp3 encode: {e}"))?;
765+ encoder.finish();
766+ let mut file = BufWriter::new(File::create(out)?);
767+ // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
768+ // header first: the loop ends on the only error it can see.
769+ while let Ok(frame) = encoder.next_packet() {
770+ file.write_all(&frame)?;
771+ }
772+ file.flush()?;
773+ Ok(())
774+}
775+
734 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to776 /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
735 /// text: they are not `Send + Sync`, and every one of them fails the export the777 /// text: they are not `Send + Sync`, and every one of them fails the export the
736 /// same way.778 /// same way.
@@ -831,34 +873,59 @@ fn write_video(
831 meta: &VideoMeta,873 meta: &VideoMeta,
832 settings: &ExportSettings,874 settings: &ExportSettings,
833 audio: Option<&AudioParams>,875 audio: Option<&AudioParams>,
876+ packets: &mut Option<Vec<crate::AacPacket>>,
834 au: &[u8],877 au: &[u8],
835 key: bool,878 key: bool,
836 ) -> crate::Result<()> {879 ) -> crate::Result<()> {
837- if settings.format == Format::Av1 {880+ if settings.format.is_av1() {
881+ // Every AV1 stream opens on a keyframe, and a keyframe carries the
882+ // sequence header the track has to declare: an encoder that handed back
883+ // neither has produced nothing a decoder can start. The same header goes
884+ // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
885+ fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result<Av1Params<'a>> {
886+ Ok(Av1Params {
887+ width: meta.width,
888+ height: meta.height,
889+ frame_rate: meta.frame_rate,
890+ config: crate::mux::av1_sequence_header(au)
891+ .ok_or("the first coded picture carries no AV1 sequence header")?,
892+ })
893+ }
894+ if settings.format == Format::Av1 {
895+ let muxer = match muxer {
896+ Some(Muxer::Mkv(mkv)) => mkv,
897+ Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
898+ none => {
899+ // The sound with it, all of it: the Matroska muxer writes the
900+ // packets into the clusters of the pictures they play under.
901+ let sound = audio.zip(packets.take());
902+ let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
903+ out,
904+ &params(meta, au)?,
905+ sound,
906+ )?)) else {
907+ unreachable!("just inserted a Matroska muxer")
908+ };
909+ mkv
910+ }
911+ };
912+ return muxer.write_frame(au, key);
913+ }
838 let muxer = match muxer {914 let muxer = match muxer {
839- Some(Muxer::Mkv(mkv)) => mkv,915+ Some(Muxer::Mp4(mp4)) => mp4,
840- Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),916+ Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
841 none => {917 none => {
842- // Every AV1 stream opens on a keyframe, and a keyframe carries918+ let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
843- // the sequence header the track has to declare: an encoder that
844- // handed back neither has produced nothing a decoder can start.
845- let config = crate::mux::av1_sequence_header(au)
846- .ok_or("the first coded picture carries no AV1 sequence header")?;
847- let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
848 out,919 out,
849- &Av1Params {920+ &params(meta, au)?,
850- width: meta.width,921+ audio,
851- height: meta.height,
852- frame_rate: meta.frame_rate,
853- config,
854- },
855 )?)) else {922 )?)) else {
856- unreachable!("just inserted a Matroska muxer")923+ unreachable!("just inserted an mp4 muxer")
857 };924 };
858- mkv925+ mp4
859 }926 }
860 };927 };
861- return muxer.write_frame(au, key);928+ return muxer.write_av1_frame(au, key);
862 }929 }
863 if !crate::mux::has_coded_slice(au) {930 if !crate::mux::has_coded_slice(au) {
864 return Ok(());931 return Ok(());
@@ -928,7 +995,9 @@ enum Enc {
928 995
929 impl Enc {996 impl Enc {
930 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {997 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
931- if settings.format == Format::Av1 {998+ // Which *codec* the picture is, not which container it goes in: both AV1
999+ // formats run the same encoder.
1000+ if settings.format.is_av1() {
932 return Self::open_av1(meta, settings);1001 return Self::open_av1(meta, settings);
933 }1002 }
934 // A caller's number goes through the same clamp as the computed one: a1003 // A caller's number goes through the same clamp as the computed one: a
crates/engine/src/mux.rsmodified+538 -19
@@ -5,10 +5,17 @@
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()?;
181- Ok(())286+ let Self {
287+ writer, av1c, path, ..
288+ } = self;
289+ // Not a `drop`: the buffered tail of `moov` has to be on disk before the
290+ // patch below reads it back, and a `BufWriter` swallows the error of
291+ // flushing it on drop.
292+ writer.into_writer().flush()?;
293+ match av1c {
294+ Some(av1c) => patch_av01(&path, &av1c),
295+ None => Ok(()),
296+ }
297+ }
298+}
299+
300+/// Rewrites the finished file's one video sample entry from the `avc1` the crate
301+/// wrote into the `av01` + `av1C` an AV1 track declares. Called once, on a
302+/// complete file, and only for a file [`Mp4Muxer::create_av1`] opened.
303+///
304+/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only
305+/// ever rewrites the tail of the file: no sample moves and no chunk offset in
306+/// `co64` changes. The box tree is rebuilt rather than patched in place, which
307+/// is what keeps every ancestor's size right by construction.
308+fn patch_av01(path: &Path, av1c: &[u8]) -> crate::Result<()> {
309+ let mut file = OpenOptions::new().read(true).write(true).open(path)?;
310+ let end = file.metadata()?.len();
311+ let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
312+ let patched = swap_av01(&payload, 0, av1c).ok_or("no avc1 sample entry to rewrite as av01")?;
313+ let mut out = Vec::with_capacity(patched.len() + 8);
314+ push_box(&mut out, b"moov", &patched);
315+ file.seek(SeekFrom::Start(at))?;
316+ file.write_all(&out)?;
317+ file.set_len(at + out.len() as u64)?;
318+ file.flush()?;
319+ Ok(())
320+}
321+
322+/// Offset and payload of the first top-level box of type `want`.
323+fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result<Option<(u64, Vec<u8>)>> {
324+ let mut at = 0u64;
325+ while at + 8 <= end {
326+ let mut header = [0u8; 8];
327+ file.seek(SeekFrom::Start(at))?;
328+ file.read_exact(&mut header)?;
329+ let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
330+ 0 => (end - at, 8),
331+ 1 => {
332+ let mut large = [0u8; 8];
333+ file.read_exact(&mut large)?;
334+ (u64::from_be_bytes(large), 16)
335+ }
336+ size => (u64::from(size), 8),
337+ };
338+ if size < head_len || at + size > end {
339+ return Err("truncated box in the file's top level".into());
340+ }
341+ if &header[4..8] == want {
342+ let mut payload = vec![0u8; (size - head_len) as usize];
343+ file.read_exact(&mut payload)?;
344+ return Ok(Some((at, payload)));
345+ }
346+ at += size;
182 }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
@@ -414,16 +414,19 @@ fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
414 }414 }
415 }415 }
416 416
417-/// The export copies AAC packets and has no encoder, so a timeline carrying an417+/// The *copy* path names what it cannot copy, by file and by format. That is a
418-/// mp3 cannot become an mp4 -- named, with its format, rather than exported418+/// fallback's reason rather than a user's refusal now -- `export::copy_audio`
419-/// silent or exported wrong.419+/// takes this `Err` as "not copyable" and decodes and re-encodes the timeline
420+/// instead (`tests/audio_export.rs` exports exactly this shape as an mp4 with
421+/// sound in it) -- but the words are what a caller with no encoder shows, so
422+/// they are still asserted here.
420 #[test]423 #[test]
421 fn an_export_refuses_audio_it_cannot_copy() {424 fn an_export_refuses_audio_it_cannot_copy() {
422 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];425 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];
423 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];426 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
424 assert_eq!(427 assert_eq!(
425 refusal(AudioSession::copy_multi_segments(&sources, &segs)),428 refusal(AudioSession::copy_multi_segments(&sources, &segs)),
426- "export needs AAC audio today; test_tone.mp3 is mp3"429+ "a packet copy needs AAC in an mp4; test_tone.mp3 is mp3"
427 );430 );
428 // A timeline of nothing but mp4 still exports, which is the invariant this431 // A timeline of nothing but mp4 still exports, which is the invariant this
429 // refusal must not have cost.432 // 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/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"