diff --git a/Cargo.lock b/Cargo.lock index af112da..3ac3b68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1640,6 +1640,7 @@ dependencies = [ "rav1e", "rusty_aac", "rusty_h264", + "rusty_mp3", "symphonia", "symphonia-codec-aac", "symphonia-core", @@ -4924,6 +4925,12 @@ dependencies = [ "rusty_h264-common", ] +[[package]] +name = "rusty_mp3" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a99f339ec9a2d84eec8fc2a42baa92426966b25238c498e79d57b4e49b14fbad" + [[package]] name = "rustybuzz" version = "0.14.1" diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 2cedaf1..a1be829 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -337,8 +337,8 @@ pub const FIXED: [Fixed; 16] = [ category: Category::File, }, Fixed { - chord: "m / a / w / f", - label: "Pick the export format: MP4, AV1, WAV or FLAC", + chord: "m / a / v / w / f / p", + label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, WAV, FLAC or MP3", category: Category::File, }, Fixed { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index bebcf4c..1751d83 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -2090,7 +2090,15 @@ impl Player { return; }; let settings = export_settings(self.quality, self.custom_mbps, self.format); - if !self.export_open || !settings.format.has_video() { + if !self.export_open { + return; + } + // A format with no picture has no seat to probe -- and the *last* + // format's is not its answer: cleared rather than left standing, or + // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW + // (rusty_mp3)", which names an encoder that will not run. + if !settings.format.has_video() { + self.export_seat = None; return; } let meta = *session.meta(); @@ -4710,7 +4718,7 @@ impl Player { let formats: Vec<_> = FORMATS .into_iter() .enumerate() - .map(|(i, (format, label, detail))| { + .map(|(i, (format, _, label, detail))| { // Per row, because the two picture formats are refused by // different things: an audio-only timeline greys both, a second // audio lane only the mp4. @@ -4794,7 +4802,7 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "pick a format (m/a/w/f), then Export — esc closes".into() + "pick a format (m/a/v/w/f/p), then Export — esc closes".into() })), ) // Capped and scrolling like the keybindings list: the @@ -6927,48 +6935,67 @@ impl Quality { } } -/// The export card's format rows: what this program can write, and what it -/// cannot with the reason it cannot. A format with no entry at all would read -/// as an oversight, and a menu of three as a claim that nothing else exists -- -/// so the refusals are rows too, dimmed and unclickable. +/// The export card's format rows: the key that picks one, its name, and what it +/// writes -- or, where this program cannot write it, the reason it cannot. A +/// format with no entry at all would read as an oversight, and a menu of three +/// as a claim that nothing else exists -- so the refusals are rows too, dimmed +/// and unclickable. /// -/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a -/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a -/// decision about this project rather than about the code, and the row says so -/// instead of pretending the encoder does not exist. HEVC and VP9 are the two -/// this program *reads* and cannot write -- the plugin decodes both and there is -/// no encoder for either here -- so they are rows for the same reason: a codec -/// that opens but never comes back out is exactly the gap a user would other- -/// wise go looking for. -const FORMATS: [(Option, &str, &str); 9] = [ - (Some(Format::Mp4), "MP4", "H.264 picture + AAC sound"), +/// `None` is exactly that kind of row, and there are three left. MP3 stopped +/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL +/// `shine-rs` was the licence question, and it is not the only encoder any +/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the +/// plugin decodes both and there is no encoder for either here -- so they are +/// rows for the same reason: a codec that opens but never comes back out is +/// exactly the gap a user would otherwise go looking for. AAC is not a row at +/// all: it is what both containers' sound *is*, never a file of its own. +/// +/// AV1 is two rows because a codec and a container are two choices: the same +/// picture and the same AAC track go into a Matroska file or into an mp4, and +/// which one a user needs is about what has to play the file, not about the +/// encode. +const FORMATS: [(Option, &str, &str, &str); 9] = [ + (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"), ( Some(Format::Av1), - "AV1", - "AV1 picture in .mkv — no sound: export WAV or FLAC for that", + "a", + "AV1 · MKV", + "AV1 picture + AAC sound in .mkv", + ), + ( + Some(Format::Av1Mp4), + "v", + "AV1 · MP4", + "the same AV1 picture and sound in .mp4", + ), + (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"), + (Some(Format::Flac), "f", "FLAC", "lossless — audio only"), + ( + Some(Format::Mp3), + "p", + "MP3", + "MPEG-1 Layer III, 256 kbps — audio only", ), - (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), - (Some(Format::Flac), "FLAC", "lossless — audio only"), - (None, "MP3", "encoder is LGPL — licence decision pending"), - (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), - (None, "AAC", "an MP4's sound here, not a file of its own"), + (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"), ( None, + "", "HEVC", "no encoder in this stack, and patent-encumbered", ), - (None, "VP9", "superseded by AV1, which is the row above"), + (None, "", "VP9", "superseded by AV1, which is the row above"), ]; -/// The format a key picks while the export card is up: the row's own initial, -/// which is unambiguous across the three that can be picked. `None` for -/// everything else, digits included -- those are the bitrate's. +/// The format a key picks while the export card is up. A letter of the row's +/// own name, spelled out in the table rather than taken from the initial: `MP4` +/// and `MP3` share one, and so do the two AV1 containers, so an initial cannot +/// tell six rows apart. Never a digit -- those are the bitrate's. `None` for +/// everything else, the rows that cannot be picked included. fn format_key(key: &str) -> Option { FORMATS .into_iter() - .filter_map(|(format, label, _)| format.zip(label.get(..1))) - .find(|(_, initial)| initial.eq_ignore_ascii_case(key)) - .map(|(format, _)| format) + .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key)) + .find_map(|(format, ..)| format) } /// What one of the colour card's own strokes does. Its keys are card-local -- @@ -7138,9 +7165,11 @@ fn export_line( fn format_line(format: Format) -> &'static str { match format { Format::Mp4 => "H.264 · MP4 · moov at end", - Format::Av1 => "AV1 · Matroska · picture only, no audio track", + Format::Av1 => "AV1 · Matroska · picture and sound", + Format::Av1Mp4 => "AV1 · MP4 · picture and sound", Format::Wav => "16-bit PCM · WAV · timeline audio only", Format::Flac => "FLAC · lossless · timeline audio only", + Format::Mp3 => "MP3 · 256 kbps · timeline audio only", } } @@ -7150,7 +7179,7 @@ fn format_label(format: Format) -> &'static str { FORMATS .iter() .find(|(row, ..)| *row == Some(format)) - .map_or("EXPORT", |(_, label, _)| *label) + .map_or("EXPORT", |(_, _, label, _)| *label) } /// The destination under a format: `take.export.mp4` becomes `take.export.wav`. @@ -7270,11 +7299,12 @@ fn is_bare_modifier(key: &str) -> bool { /// refuses it too (`export::start`); this is what greys the row before a /// destination has been picked. /// -/// The second reason is the mp4 path's alone: it *copies* one AAC track and -/// there is no encoder here to mix several with, so a timeline whose sound is -/// spread over more than one audio lane is refused by the engine -/// (`export::run`). An AV1 export carries no sound at all -- said on its row as -/// its detail, not as a refusal -- so no count of audio lanes stops it. +/// It is the *only* reason left. A second audio lane, a speeded clip, a source +/// no mp4 sample table holds: each of those used to grey the MP4 row, because +/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy +/// cannot say what the timeline says (`export::copy_audio`), so none of them is +/// a refusal any more -- and every video format carries the sound, so there is +/// nothing here that is one format's alone. fn format_refusal(session: &PlaybackSession, format: Format) -> Option { if !format.has_video() { return None; @@ -7283,43 +7313,13 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option { .lanes() .into_iter() .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); - if !picture { - return Some(format!( - "no picture — {} would be black; export WAV or FLAC", + match picture { + true => None, + false => Some(format!( + "no picture — {} would be black; export WAV, FLAC or MP3", format.name() - )); - } - if format != Format::Mp4 { - return None; + )), } - let audio: Vec = session - .lanes() - .into_iter() - .filter(|&lane| lane.kind == LaneKind::Audio && !session.lane_clips(lane).is_empty()) - .collect(); - if audio.len() > 1 { - return Some(format!("{} audio lanes — an mp4 copies one", audio.len())); - } - // ...and the third reason, the same path's: a copied AAC packet carries no - // rate, so a speeded clip on the lane being copied would come back at 1.00x - // under a picture the export *does* re-time. The engine refuses it by name - // (`export::copy_audio`); this greys the row before anyone picks a - // destination. The picture's own rate is no reason at all -- the export walk - // honours that -- so only this one lane is asked. - audio - .first() - .and_then(|&lane| { - session - .lane_clips(lane) - .iter() - .find(|c| !c.speed.is_normal()) - }) - .map(|c| { - format!( - "sound at {} — an mp4 copies packets, which carry no rate", - c.speed - ) - }) } /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap @@ -8302,14 +8302,19 @@ mod tests { // and are never refused. assert_eq!( format_refusal(&session, Format::Mp4).as_deref(), - Some("no picture — an mp4 would be black; export WAV or FLAC") + Some("no picture — an mp4 would be black; export WAV, FLAC or MP3") ); assert_eq!( format_refusal(&session, Format::Av1).as_deref(), - Some("no picture — an AV1 export would be black; export WAV or FLAC") + Some("no picture — an AV1 Matroska would be black; export WAV, FLAC or MP3") + ); + assert_eq!( + format_refusal(&session, Format::Av1Mp4).as_deref(), + Some("no picture — an AV1 mp4 would be black; export WAV, FLAC or MP3") ); assert_eq!(format_refusal(&session, Format::Wav), None); assert_eq!(format_refusal(&session, Format::Flac), None); + assert_eq!(format_refusal(&session, Format::Mp3), None); } fn info( @@ -9061,28 +9066,24 @@ mod tests { assert!(session.lane_clips(v2).is_empty()); assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put"); - // A second audio lane carrying sound is what an mp4 export cannot - // write, so the card greys that row before a destination is picked. + // A second audio lane used to be what an mp4 export could not write -- + // it copied one AAC track and a mix is not a copy. It mixes now + // (`export::copy_audio`), so no row is greyed by a count of lanes. assert_eq!(format_refusal(&session, Format::Mp4), None); let a2 = session.add_lane(LaneKind::Audio); assert_eq!(a2.label(), "A2"); - assert_eq!( - format_refusal(&session, Format::Mp4), - None, - "an empty lane carries nothing" - ); assert!( session .place_stream_at(0.0, &path, 0, Some(a2)) .expect("its own file is on this timeline") ); - assert_eq!( - format_refusal(&session, Format::Mp4).as_deref(), - Some("2 audio lanes — an mp4 copies one") - ); - // ...and the one thing that does not stop an AV1 export, which carries - // no sound to have too much of. - assert_eq!(format_refusal(&session, Format::Av1), None); + for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] { + assert_eq!( + format_refusal(&session, format), + None, + "two audio lanes are a mix, not a refusal" + ); + } // Undo, one edit at a time and backwards: the drop on A2, the lane A2 // itself, the lift, the drop on V2, and last the lane V2 -- an added @@ -10241,59 +10242,80 @@ mod tests { #[test] fn every_format_row_is_offered_or_says_why_not() { - // The four this program can write are rows that pick. Three are named + // The six this program can write are rows that pick. Four are named // after their own extension, so a destination cannot disagree with its - // bytes; the fourth is named after its *codec*, because AV1 arrives and - // leaves in a Matroska file and "MKV" would name the box rather than - // what is in it. + // bytes; the AV1 pair is named after codec *and* container, because the + // same picture goes into either box and the row is the choice between + // them. let offered: Vec = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); assert_eq!( offered, - vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac] + vec![ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Wav, + Format::Flac, + Format::Mp3 + ] ); assert_eq!(Format::Av1.ext(), "mkv"); - for (format, label, _) in FORMATS { + assert_eq!(Format::Av1Mp4.ext(), "mp4"); + for (format, _, label, _) in FORMATS { match format { - Some(Format::Av1) => assert_eq!(label, "AV1"), + Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"), + Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"), Some(format) => assert_eq!(format.ext(), label.to_lowercase()), // A refused format is a row with a reason, never a hidden one: // an empty detail column would read as an oversight. None => assert!(!label.is_empty()), } } - for (format, label, detail) in FORMATS { + for (format, stroke, label, detail) in FORMATS { assert!(!detail.is_empty(), "{label} says nothing"); - // Only the two picture formats leave the bitrate rows live -- the - // card dims them off exactly this. + // Only the picture formats leave the bitrate rows live -- the card + // dims them off exactly this. assert_eq!( format.is_some_and(Format::has_video), - matches!(format, Some(Format::Mp4 | Format::Av1)) + matches!(format, Some(Format::Mp4 | Format::Av1 | Format::Av1Mp4)) ); + // Every row that can be picked has a key of its own, and no two + // share one: the card is drivable without a pointer. + assert_eq!(format.is_some(), !stroke.is_empty(), "{label}"); + if !stroke.is_empty() { + assert_eq!(format_key(stroke), format, "{label} keys to itself"); + assert!( + stroke.parse::().is_err(), + "{label} takes a digit the bitrate needs" + ); + } } // The two codecs this program reads and cannot write are rows of their // own, refused by name rather than absent -- HEVC for want of an encoder // (and for its patents), VP9 because AV1 is the row that replaced it. for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] { - let (format, _, detail) = FORMATS + let (format, _, _, detail) = FORMATS .into_iter() - .find(|(_, row, _)| *row == label) + .find(|(_, _, row, _)| *row == label) .unwrap_or_else(|| panic!("{label} has no row")); assert!(format.is_none(), "{label} is not offered"); assert!(detail.contains(word), "{label}: {detail}"); } - // The AV1 row says on the row itself that it carries no sound, which is - // the one thing a user could otherwise only find out by playing the file. - let (_, _, av1) = FORMATS - .into_iter() - .find(|(f, ..)| *f == Some(Format::Av1)) - .expect("an AV1 row"); - assert!(av1.contains("no sound"), "{av1}"); - assert!(format_line(Format::Av1).contains("picture only")); - assert_eq!( - format_key("a"), - Some(Format::Av1), - "its own initial picks it" - ); + // Both AV1 rows say they carry sound: the file used to be picture only, + // and a row that still said so would be the lie a user plays the file + // to find out about. + for format in [Format::Av1, Format::Av1Mp4] { + let (_, _, _, detail) = FORMATS + .into_iter() + .find(|(f, ..)| *f == Some(format)) + .expect("an AV1 row"); + assert!(detail.contains("sound"), "{detail}"); + assert!(format_line(format).contains("picture and sound")); + } + assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one"); + assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one"); + assert_eq!(format_key("p"), Some(Format::Mp3)); + assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p"); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 16efde8..bc6648f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -35,6 +35,11 @@ rusty_h264 = { version = "0.8", default-features = false } # Fraunhofer's C library, which this project's no-install rule forbids. Built # from `vendor/rusty_aac` -- see the patch table in the workspace manifest. rusty_aac = "0.5" +# The MP3 encoder, so that format is a row a user can pick rather than a licence +# note: pure Rust, Apache-2.0, CBR and VBR. The decoder side of mp3 is +# symphonia's below -- an mp3 has always been importable here, and until this it +# was the one format the editor could read and never write. +rusty_mp3 = "0.6" symphonia-core = "0.6" symphonia-codec-aac = "0.6" # The umbrella crate for the standalone audio files: one dependency instead of diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index cc78fce..ef4885d 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -802,8 +802,9 @@ impl AudioSession { } /// One AAC-LC access unit of silence, for the gaps in an exported timeline — -/// the export copies packets and has no AAC encoder, so the only silence it can -/// write is one spelled out by hand. +/// this is the *copy* path, which never encodes anything, so the only silence it +/// can write is one spelled out by hand. (The re-encode path next door has a +/// real encoder and needs none of this: its gaps are zero samples.) /// /// It is the shortest legal `raw_data_block` there is: one element carrying /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no @@ -848,11 +849,12 @@ fn source_at<'a>( /// A source's track for the *copy* path, which needs raw AAC access units. /// -/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by -/// name and by format rather than exported silent or, worse, exported as noise: -/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]), -/// so a timeline carrying one of those simply cannot become an mp4 today. The -/// wording is what a front-end shows. +/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name +/// and by format. That is no longer the end of the road: `export::copy_audio` +/// takes it as the answer "not copyable" and decodes and re-encodes the timeline +/// instead, so these words are a fallback's reason rather than a user's refusal. +/// They are still worded for a person, because a caller with no encoder to fall +/// back on shows them verbatim. /// /// `Ok(None)` for a file with no audio at all, which is a silent export. fn copy_track(path: &Path, stream: usize) -> crate::Result> { @@ -862,16 +864,18 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result> { // A Matroska source gets its own words: its packets *are* AAC, so // "export needs AAC audio today" would read as a contradiction. What // they are not is packets of an mp4 sample table, which is what the - // copy walks -- and refusing beats writing a film with no sound in it. + // copy walks. The export decodes such a source and encodes it again + // rather than showing this, so a film's sound reaches an mp4 either way; + // the words stay for a caller that copies and cannot re-encode. // // ponytail: the ceiling is the copy path being written against the mp4 - // reader, not anything about the bytes. Upgrade path is the same one - // every other refusal here names -- an AAC encoder, or a `copy_segments` - // that walks a Matroska track -- and either would let this through. + // reader, not anything about the bytes. Upgrade path is a + // `copy_segments` that walks a Matroska track, which would make this a + // copy again instead of a re-encode. Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!( - "{}'s sound is AAC inside a Matroska file, which an mp4 export cannot copy: \ - it copies packets out of an mp4's own sample table. Export WAV or FLAC for \ - the sound, or AV1 for the picture alone", + "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \ + a copy walks an mp4's own sample table. It is decoded and encoded again \ + instead", path.file_name() .unwrap_or(path.as_os_str()) .to_string_lossy(), @@ -879,17 +883,18 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result> { .into()), Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` - // sample table can hold, and there is no AAC encoder here to turn it - // into one. A WAV/FLAC export of the same timeline decodes fine. + // sample table can hold. The export decodes it and encodes AAC, exactly + // as it does for every other source no copy reaches. Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), } } -/// The one wording for "this source's audio cannot be copied into an mp4", -/// shared by every format that cannot be: a front-end shows it verbatim. +/// The one wording for "this source's audio cannot be *copied* into an mp4", +/// shared by every format that cannot be. What the export does about it is +/// decode and re-encode; this is the reason it had to. fn uncopyable(path: &Path, codec: &str) -> crate::Error { format!( - "export needs AAC audio today; {} is {codec}", + "a packet copy needs AAC in an mp4; {} is {codec}", path.file_name() .unwrap_or(path.as_os_str()) .to_string_lossy(), diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index d41b1e1..caed1c6 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -7,7 +7,10 @@ //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists -- //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in //! practice -- and HEVC rides the same walk, because that is the other codec a -//! `.mkv` off a disc arrives in. +//! `.mkv` off a disc arrives in. An AV1 *mp4* is read here too, its sample entry +//! picked out of the `stsd` by hand for the same reason `mux` writes it by hand: +//! this project exports one, and a file this cannot reopen is a file it had no +//! business writing. use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; @@ -131,9 +134,9 @@ pub struct Mp4Demuxer { /// (`audio::priming_samples`), and frame indices count from there. first_sample: u32, codec: Codec, - /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), - /// re-injected ahead of every sync sample. Empty for VP9, which carries no - /// out-of-band parameter sets. + /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or + /// the sequence header OBU for AV1, re-injected ahead of every sync sample. + /// Empty for VP9, which carries no out-of-band parameter sets. parameter_sets: Vec, /// Bytes of the NAL length prefix each sample is written with, off `avcC` /// or `hvcC`. Unused by VP9. @@ -160,20 +163,26 @@ impl Mp4Demuxer { Ok(MediaType::H265) => Some((t, Codec::Hevc)), Ok(MediaType::VP9) => Some((t, Codec::Vp9)), // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry - // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple - // and ffmpeg's mov muxer write in practice -- reports no media - // type at all, and the file used to read back as having no - // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are - // parsed regardless of the entry the crate dropped, so only the - // fourcc has to be read here by hand. hvc1 differs from hev1 in - // that the parameter sets may not repeat in-band, which costs - // nothing: they are re-injected out of `hvcC` ahead of every - // sync sample either way. - _ => (matches!(t.track_type(), Ok(TrackType::Video)) - && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1")) - .then_some((t, Codec::Hevc)), + // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC + // track -- what Apple and ffmpeg's mov muxer write in practice + // -- and every AV1 track report no media type, and such a file + // used to read back as having no video. Its sample tables + // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the + // entry the crate dropped, so only the fourcc has to be read + // here by hand. hvc1 differs from hev1 in that the parameter + // sets may not repeat in-band, which costs nothing: they are + // re-injected out of `hvcC` ahead of every sync sample either + // way, exactly as an AV1 sequence header is out of `av1C`. + _ => matches!(t.track_type(), Ok(TrackType::Video)) + .then(|| sample_entry(path, t.track_id()).ok()) + .flatten() + .and_then(|(kind, _)| match &kind { + b"hvc1" => Some((t, Codec::Hevc)), + b"av01" => Some((t, Codec::Av1)), + _ => None, + }), }) - .ok_or("no H.264, HEVC or VP9 video track in file")?; + .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?; let (track, codec) = track; let track_id = track.track_id(); @@ -216,10 +225,19 @@ impl Mp4Demuxer { parameter_sets = sets; bit_depth = depth; } - // No parameter sets: a VP9 sample is self-contained, and AV1 never - // reaches this arm at all -- `mp4 0.14` knows no `av01` sample - // entry, so AV1 only ever arrives through [`MkvDemuxer`]. - Codec::Vp9 | Codec::Av1 => {} + // The sequence header OBU out of `av1C`, re-injected ahead of every + // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` -- + // the same record in the same bytes, which is what makes an AV1 mp4 + // written here and an AV1 Matroska written here one stream in two + // containers. + Codec::Av1 => { + let (_, entry) = sample_entry(path, track_id)?; + let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C") + .ok_or("no av1C box in the AV1 sample entry")?; + parameter_sets = parse_av1c(av1c)?; + } + // No parameter sets: a VP9 sample is self-contained. + Codec::Vp9 => {} } let sync_samples = track .trak @@ -273,6 +291,16 @@ impl Mp4Demuxer { if self.codec == Codec::Vp9 { return Ok(Some(sample.bytes.to_vec())); } + // An AV1 one is a whole temporal unit, likewise unframed -- with the + // sequence header in front of it where a decoder may start. + if self.codec == Codec::Av1 { + let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len()); + if sample.is_sync { + au.extend_from_slice(&self.parameter_sets); + } + au.extend_from_slice(&sample.bytes); + return Ok(Some(au)); + } let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); if sample.is_sync { @@ -1075,7 +1103,7 @@ fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result>> /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first /// malformed header rather than erroring: every caller is looking for one box /// and reports its own absence. -fn boxes(mut buf: &[u8]) -> impl Iterator { +pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator { std::iter::from_fn(move || { let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?; let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 5329048..bbf26a6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,28 +1,36 @@ -//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska — -//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone. +//! Export: the edit list rendered back out as one mp4 (H.264 or AV1) or one +//! AV1-in-Matroska — or, picture left behind, as one WAV, FLAC or MP3 of the +//! timeline's audio alone. //! //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it //! is impossible — while audio is copied packet for packet wherever a copy can //! say what the timeline says: a copy is exact, free and never a generation of -//! loss. Where it *cannot* — an equalized lane, which is sample math no packet -//! copy can reach — that lane is decoded, mixed and encoded again with -//! `rusty_aac` ([`encode_audio`]). The audio-only formats have no such split: -//! `hound` writes PCM and `flacenc` encodes FLAC, so those are always *decoded* -//! out of the timeline. The worker owns everything: the caller gets an +//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an +//! equalized one, a source that is not AAC inside an mp4's own sample table — +//! the sound is decoded, mixed and encoded again with `rusty_aac` +//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes +//! PCM, `flacenc` encodes FLAC and `rusty_mp3` encodes MP3, so those are always +//! *decoded* out of the timeline. The worker owns everything: the caller gets an //! [`ExportHandle`] and polls it from its render loop. //! +//! **Every video format here carries the timeline's sound**, in whichever +//! container: the mp4 muxer writes an AAC track and so does the Matroska one. +//! Nothing is written picture-only and nothing is left silent without saying so +//! — the only sound that does not come out is sound this engine cannot decode at +//! all (Opus and AC-3 inside a Matroska file), and that is an error by name. +//! //! A **speeded** clip splits along the same line, and for the same reason. The //! picture is re-encoded, so the frame walk honours a rate: it takes the source //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the //! very frame preview holds there) and encodes a held one again rather than //! decoding it twice. A clip whose *file* was shot at another rate than the //! timeline goes through the same walk with one more conversion on the end -//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. The sound is *copied* unless a filter forces a decode, and -//! a packet carries no rate -- so a speeded clip on the one audio lane an mp4 -//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x -//! under a re-timed picture. -//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are -//! decoded and resampled, so they honour a rate like the picture does. +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. +//! The sound is *copied* unless something forces a decode, and a packet carries +//! no rate — so a speeded lane is one of the things that forces one +//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed +//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate +//! like the picture does. //! //! Nothing partial survives a failure: the worker writes to `.part` and //! renames it onto `out` only once the file is closed and complete, so the @@ -32,6 +40,8 @@ //! behind (only in-process cleanup is promised), which is an orphan a user can //! delete rather than a file that plays for two seconds and stops. +use std::fs::File; +use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; @@ -63,37 +73,42 @@ const MAX_BITRATE: u64 = 20_000_000; /// on a build with no assembly, which is what this one is. const AV1_SPEED: u8 = 10; -/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are -/// the only *video* pairs with both an encoder and a decoder under this -/// project's no-install rule, and WAV and FLAC are the only *standalone* audio -/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under -/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis -/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp4 -/// track is encoded with -- but AAC is an mp4's own audio, never a file of its -/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import -/// through the plugin and stop there). A front-end says so rather than hiding -/// the rows. +/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the +/// user's pick of container -- are the only *video* pairs with both an encoder +/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are +/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and +/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is +/// what a re-encoded video track's sound leaves through -- but AAC is a +/// container's own audio, never a file of its own here.) HEVC and VP9 have no +/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there). +/// A front-end says so rather than hiding the rows. +/// +/// **Every video format carries sound.** Which way it carries it is the only +/// difference: copied packet for packet where a copy can say what the timeline +/// says, decoded and encoded again ([`encode_audio`]) where it cannot. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Format { /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too, - /// where a copy could not carry the edit (an equalized lane). Either way it - /// carries **one** audio lane: a timeline whose sound is spread over two is - /// refused by name here and mixed by the other two formats, which decode. + /// where a copy could not carry the edit (a second audio lane to mix in, a + /// speeded clip, an equalized one, a source no mp4 sample table holds). #[default] Mp4, - /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound - /// this project can *write*: this engine's Matroska writer has no audio - /// track at all, and the copy path walks an mp4 sample table, which a - /// Matroska file has none of. (*Reading* one's AAC is a different question, - /// and since this engine gained a Matroska demuxer the answer is yes -- - /// `audio::Track::open` does it through symphonia's mkv reader.) The sound - /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up - /// front. + /// AV1 in Matroska, with the timeline's AAC beside it: this engine's + /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its + /// reader reads one back, symphonia's `mkv` reader being what + /// `audio::Track::open` opens it with. Av1, - /// The audio lane alone, 16-bit PCM. + /// The same AV1 stream in an mp4, for everything that plays mp4 and not + /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand + /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, + /// unchanged. + Av1Mp4, + /// The audio lanes alone, 16-bit PCM. Wav, - /// The audio lane alone, losslessly compressed. + /// The audio lanes alone, losslessly compressed. Flac, + /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`). + Mp3, } impl Format { @@ -101,26 +116,36 @@ impl Format { /// the destination path from it, so the name never disagrees with the bytes. pub fn ext(self) -> &'static str { match self { - Self::Mp4 => "mp4", + Self::Mp4 | Self::Av1Mp4 => "mp4", Self::Av1 => "mkv", Self::Wav => "wav", Self::Flac => "flac", + Self::Mp3 => "mp3", } } /// Whether this format carries the picture. The bitrate settings are video - /// settings and mean nothing to the audio two. + /// settings and mean nothing to the audio-only ones. pub fn has_video(self) -> bool { - matches!(self, Self::Mp4 | Self::Av1) + matches!(self, Self::Mp4 | Self::Av1 | Self::Av1Mp4) + } + + /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs + /// and which of the two AV1 containers is being written are separate + /// questions, and this is the first. + fn is_av1(self) -> bool { + matches!(self, Self::Av1 | Self::Av1Mp4) } /// What the format is called where a refusal names it. pub fn name(self) -> &'static str { match self { Self::Mp4 => "an mp4", - Self::Av1 => "an AV1 export", + Self::Av1 => "an AV1 Matroska", + Self::Av1Mp4 => "an AV1 mp4", Self::Wav => "a WAV", Self::Flac => "a FLAC", + Self::Mp3 => "an MP3", } } } @@ -241,12 +266,12 @@ pub fn start( Err("the timeline is empty: there is nothing to export".into()) } format if format.has_video() && !has_picture(&project) => Err(format!( - "the timeline has no picture: {} would be black. Export WAV or \ - FLAC, which are the sound itself", + "the timeline has no picture: {} would be black. Export WAV, \ + FLAC or MP3, which are the sound itself", format.name() ) .into()), - Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings), + format if format.has_video() => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); @@ -314,9 +339,12 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; let bitrate = bitrate_of(meta, settings); match settings.format { - // Opt-in only, for the reason [`Enc::open_av1`] states in full. - Format::Av1 if !forced("VE_HW_AV1") => None, - Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate), + // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both + // AV1 formats sit on it: the container is not the encoder's business. + format if format.is_av1() && !forced("VE_HW_AV1") => None, + format if format.is_av1() => { + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) + } _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), } } @@ -327,34 +355,65 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { /// place, so what a card says before an export and what its progress line says /// during one cannot drift apart. fn video_label(format: Format, hw: bool) -> &'static str { - match (format, hw) { - (Format::Av1, true) => "HW encode (VA-API)", - (Format::Av1, false) => "SW encode (rav1e)", + match (format.is_av1(), hw) { (_, true) => "HW encode (VA-API)", - (_, false) => "SW encode (rusty_h264)", + (true, false) => "SW encode (rav1e)", + (false, false) => "SW encode (rusty_h264)", } } +/// The cheap half of "does this timeline's sound have to be re-encoded": what +/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a +/// copy; a speeded lane is resampled; an equalizer is sample math. The other +/// half -- whether the sources can be copied out of at all -- costs a file open +/// each and belongs to [`copy_audio`], which may re-encode where this says copy. +fn forces_encode(project: &Project) -> bool { + let lanes: Vec<_> = project + .audio_lanes() + .into_iter() + .filter(|&lane| !project.lane(lane).is_empty()) + .collect(); + lanes.len() > 1 + || lanes + .iter() + .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) + || equalized(project) +} + /// What the sound is written by. Every audio encoder here is software -- there -/// is no hardware AAC, PCM or FLAC seat -- so this names *which* one, and -/// whether an mp4 escapes encoding altogether by copying the packets it was -/// given. Empty for AV1, which carries no audio at all: a caller joins this to -/// a line that already says so, and repeating it would cost a line of card. -fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str { +/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and +/// whether a container escapes encoding altogether by copying the packets it was +/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the +/// timeline's sound too, so leaving it unnamed would be the old lie. +/// +/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a +/// card asking before the export has no way to know (a source that cannot be +/// copied out of is only found by opening it). `None` predicts from the edit +/// alone. +fn audio_label( + project: &Project, + format: Format, + sound: bool, + copied: Option, +) -> &'static str { + if !sound { + return "no sound to write"; + } match format { - Format::Av1 => "", - _ if !sound => "no sound to write", - Format::Mp4 if equalized(project) => "AAC · SW encode (rusty_aac)", - Format::Mp4 => "AAC copy", Format::Wav => "PCM · SW (hound)", Format::Flac => "FLAC · SW (flacenc)", + Format::Mp3 => "MP3 · SW (rusty_mp3)", + _ => match copied.unwrap_or(!forces_encode(project)) { + true => "AAC copy", + false => "AAC · SW encode (rusty_aac)", + }, } } /// What [`start`] would write this timeline's sound with, before one is /// started. Pure: no probe and no file opened, so a card may ask it per repaint. pub fn planned_audio(project: &Project, format: Format) -> &'static str { - audio_label(project, format, has_sound(project)) + audio_label(project, format, has_sound(project), None) } /// What [`start`] would encode the picture with, probed the way the export @@ -376,19 +435,32 @@ fn settle(shared: &Shared, result: crate::Result<()>) { shared.finished.store(true, Ordering::Release); } -/// The timeline's one audio lane, copied packet for packet: the mp4 path's -/// sound, and the reason that path carries only one lane of it. A lane an -/// equalizer has been put on cannot be *copied* at all and leaves through -/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit. +/// The audio track an export writes, and how it was made -- a copy is the +/// source's own packets, bit for bit, and anything else is this project's +/// encoder over the decoded mix. [`run`] publishes which of the two really +/// happened, so the encoder line a user reads is measured and not promised. +pub(crate) struct ExportAudio { + pub params: crate::AacTrackParams, + pub packets: Vec, + /// Whether those packets are the source's, untouched. + pub copied: bool, +} + +/// The timeline's audio track for a file that carries picture: copied packet for +/// packet where a copy says exactly what the timeline says, and decoded, mixed +/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, +/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample +/// table. Nothing is refused for being uncopyable any more; the only refusals +/// left below the copy are about sound this engine cannot *decode* either, and +/// those come out of the decode path by name. +/// +/// The copy is still the default and still bit-exact: a timeline nobody has +/// touched leaves as the very packets its source holds. /// /// ponytail: this holds the whole exported AAC track in memory (~3 kB per /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming /// `copy_segments` that yields packets instead of collecting them. -#[allow(clippy::type_complexity)] -fn copy_audio( - project: &Project, - meta: &VideoMeta, -) -> crate::Result)>> { +fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning // files stays in sync. A source whose AAC parameters disagree with the @@ -399,16 +471,10 @@ fn copy_audio( // is the same list `PlaybackSession::seek` hands the decoder, so an export // of a timeline playing a file's second audio track carries *that* track. // - // One lane, because this path *copies* AAC packets and a mix is not a copy: - // summing two lanes means decoding both, and only the one thing a copy - // cannot express at all -- an equalizer -- is decoded here today. Refused by - // name rather than silently exporting the first lane, which is a file - // missing half its sound: the one failure a user would not notice. - // - // ponytail: the ceiling is this routing, not the codec any more. - // [`encode_audio`] already mixes *every* audio lane (it is the WAV path's - // own opener), so lifting this refusal is routing a second case to it -- - // deliberately not done here, where the change under test is the equalizer. + // One lane is the only shape a *copy* has: summing two means decoding both, + // and a sum is not a copy. Two or more go to [`encode_audio`], which is the + // very mix the WAV path writes -- it used to be a refusal, and a refusal is + // what a file missing half its sound deserves, not what a mix does. // // *Which* lane is the same question `audio_segments_from` answers for // playback, and it is asked here rather than assumed: the lane that holds @@ -418,68 +484,59 @@ fn copy_audio( // whole comment is about. let lanes = project.audio_segments_from(0, meta.frame_rate); let [segments] = &lanes[..] else { - return Err(format!( - "this timeline has {} audio lanes and an mp4 export copies one: \ - export WAV or FLAC, which are mixed, or put the sound on one lane", - lanes.len() - ) - .into()); + return encode_audio(project, meta); }; // ...and the same list names *which* lane those clips sit on, which is the // only way to ask what has been done to them. let lane = project.audio_lanes()[0]; // ...and the same list decides whether any clip this would copy plays at a - // rate other than the one it was recorded at. A copy hands the mp4 the very - // AAC packets the source holds and there is no rate inside a packet to + // rate other than the one it was recorded at. A copy hands the muxer the + // very AAC packets the source holds and there is no rate inside a packet to // change: the picture would come out re-timed (the walk in [`run`] honours // it) over sound at 1.00x, which is the drift a person finds only after the - // file has gone somewhere. Refused by name -- and only *here*, on the lane - // being copied: AV1 carries no audio at all and never reaches this, so it - // honours a speed like WAV and FLAC do. + // file has gone somewhere. Decoded and resampled instead, by the same worker + // playback feeds from. // - // ponytail: the ceiling is the packet copy itself, not the rate, and the way - // off it is now next door -- [`encode_audio`] resamples exactly as the WAV - // path does, so routing a speeded lane there is the one line the equalizer - // below takes. Left refused because this change is the equalizer's, and a - // speeded export turning silently from a copy into a re-encode is a change - // of its own to make on purpose. - if let Some((at, speed)) = project - .lane(lane) - .iter() - .find(|c| !c.speed.is_normal()) - .map(|c| (c.start, c.speed)) - { - return Err(format!( - "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \ - no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x", - timecode(at, meta.frame_rate) - ) - .into()); - } - // A frame *rate* of its own is not one of those, and that is deliberate: - // do not "fix" this into a re-encode. A clip counts the **timeline's** - // frames whatever its file was shot at ([`Rate`]), so the window this copy - // trims a source's sound to is `start..end` in whole timeline frames -- - // exactly the seconds the picture covers -- and the file is read at the - // pitch it was recorded at, which is what playing at the rate it was shot at - // means. There is no per-clip stretch to express, so the packets are already - // the right sound in the right place; re-encoding a conformed lane would buy - // nothing and cost a generation of loss on every mixed-rate export + // ...and whether any clip on it carries an equalizer, which is sample math a + // copy never reaches: copying such a lane would write the clip *flat*, + // silently. + // + // A frame *rate* of its own is not one of those, and that is deliberate: do + // not "fix" this into a re-encode. A clip counts the **timeline's** frames + // whatever its file was shot at ([`crate::project::Rate`]), so the window + // this copy trims a source's sound to is `start..end` in whole timeline + // frames -- exactly the seconds the picture covers -- and the file is read + // at the pitch it was recorded at, which is what playing at the rate it was + // shot at means. There is no per-clip stretch to express, so the packets are + // already the right sound in the right place; re-encoding a conformed lane + // would buy nothing and cost a generation of loss on every mixed-rate export // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` // measures the copied sound against the picture). A *speed* is different - // because it resamples, which is why it is refused above. + // because it resamples, which is why it leaves through the re-encode above. // - // ...and last, whether any clip on it carries an equalizer. An EQ is sample - // math and a copy never decodes, so copying such a lane would write the clip - // *flat*, silently -- the failure a missing audio track is. This lane is - // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and - // only this case is: a timeline nobody has equalized still leaves through - // the copy below, packet for packet, so no passthrough quietly becomes a - // generation of loss. - if equalized(project) { + // Only these: a timeline nobody has touched still leaves through the copy + // below, packet for packet, so no passthrough quietly becomes a generation + // of loss. + let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); + if speeded || equalized(project) { return encode_audio(project, meta); } - AudioSession::copy_multi_streams(&project.audio_sources(), segments) + // What is left is a copy the *sources* may still not be able to give: AAC + // inside a Matroska file (readable, but not out of a sample table this walks + // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two + // sources whose AAC parameters disagree. Every one of them decodes, and what + // decodes can be encoded again, so the copy's refusal is now a route: the + // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file, + // which symphonia has no decoder for at any version -- is the one that comes + // back, by name, from [`encode_audio`]. + match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { + Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { + params, + packets, + copied: true, + })), + Err(_) => encode_audio(project, meta), + } } /// The same lane, *decoded*: what a packet copy cannot carry comes out here as @@ -499,11 +556,7 @@ fn copy_audio( /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers /// the whole stream anyway, since it encodes its frames in parallel. Upgrade /// path is a chunked push once that encoder streams. -#[allow(clippy::type_complexity)] -fn encode_audio( - project: &Project, - meta: &VideoMeta, -) -> crate::Result)>> { +fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { let sources = project.audio_sources(); let segs = project.audio_segments_from(0, meta.frame_rate); let eqs = project.audio_eqs_from(0, meta.frame_rate); @@ -515,7 +568,8 @@ fn encode_audio( }; let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| { format!( - "{} Hz is not an AAC sample rate: export WAV or FLAC, which write it as it is", + "{} Hz is not an AAC sample rate: export WAV, FLAC or MP3, which write it as \ + it is", audio.sample_rate ) })?; @@ -555,8 +609,8 @@ fn encode_audio( samples: packet.duration, }); } - Ok(Some(( - crate::AacTrackParams { + Ok(Some(ExportAudio { + params: crate::AacTrackParams { freq_index, // 1 and 2 are the ISO channel configurations for mono and stereo, // and the opener refuses anything wider than stereo already. @@ -564,7 +618,8 @@ fn encode_audio( sample_rate: audio.sample_rate, }, packets, - ))) + copied: false, + })) } fn run( @@ -577,19 +632,22 @@ fn run( let total = project.timeline_frames(); let sources = project.sources(); // Audio first: a track has to be declared when the muxer is created, which - // happens as soon as the first coded picture arrives. None of it for AV1 -- - // that one is picture only, for the reason [`Format::Av1`] states -- and no - // refusal of it either: a timeline with sound is exported as the video it - // also is, and the front-end says the sound is not in the file *before* the - // export starts rather than failing it here. - let audio = match settings.format { - Format::Av1 => None, - _ => copy_audio(project, meta)?, - }; - let audio_params = audio.as_ref().map(|(track, _)| AudioParams { - freq_index: track.freq_index, - chan_conf: track.chan_conf, + // happens as soon as the first coded picture arrives -- and the Matroska + // muxer wants the packets themselves that early too, because it interleaves + // them into the clusters as it writes. Every video format gets the same + // track: none of them is picture-only any more. + let audio = copy_audio(project, meta)?; + let audio_params = audio.as_ref().map(|track| AudioParams { + freq_index: track.params.freq_index, + chan_conf: track.params.chan_conf, + sample_rate: track.params.sample_rate, }); + // What the track *is*, kept before the packets are handed to a muxer: the + // encoder line names a copy or an encode and only `copy_audio` knows which. + let sound = audio.as_ref().map(|track| track.copied); + // Taken by the Matroska muxer at creation; the mp4 one writes its track + // after the picture, so for that path this is still `Some` at the end. + let mut packets = audio.map(|track| track.packets); // One header parse per source, before any of them is decoded: what rate // each file was shot at against the timeline's ([`Rate`]), which is how the @@ -607,13 +665,11 @@ fn run( // refused reads as the software one that took over rather than as the hope // it replaced -- and the sound says whether it was copied or encoded, which // `copy_audio` decided a few lines up. - *shared.encoders.lock().unwrap() = Some( - match audio_label(project, settings.format, audio.is_some()) { - // AV1: no sound in the file and none to name. - "" => encoder.label().to_string(), - sound => format!("{} · {sound}", encoder.label()), - }, - ); + *shared.encoders.lock().unwrap() = Some(format!( + "{} · {}", + encoder.label(), + audio_label(project, settings.format, sound.is_some(), sound) + )); let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -739,6 +795,7 @@ fn run( meta, settings, audio_params.as_ref(), + &mut packets, au, key, )?; @@ -758,6 +815,7 @@ fn run( meta, settings, audio_params.as_ref(), + &mut packets, au, key, )?; @@ -769,8 +827,10 @@ fn run( let Some(muxer) = muxer else { return Err("export produced no coded pictures".into()); }; - let muxer = match (muxer, audio) { - (Muxer::Mp4(mut mp4), Some((_, packets))) => { + // The mp4's audio track after its picture -- the Matroska one interleaved + // its own as it went and left `packets` empty behind it. + let muxer = match (muxer, packets) { + (Muxer::Mp4(mut mp4), Some(packets)) => { for packet in packets { mp4.write_audio_packet(&packet.bytes)?; } @@ -802,18 +862,6 @@ fn source_rate(path: &Path, timeline_fps: f64) -> Rate { } } -/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short -/// enough to sit inside a refusal and exact enough to go and find the clip. -/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a -/// `00:00:12:07` in the middle of a sentence is a serial number. -fn timecode(frame: u32, fps: f64) -> String { - let secs = match fps.is_finite() && fps > 0.0 { - true => (f64::from(frame) / fps) as u32, - false => 0, - }; - format!("{:02}:{:02}", secs / 60, secs % 60) -} - /// The audio lanes alone, summed, as a WAV or a FLAC. /// /// Nothing here re-derives the edit: the play lists are @@ -855,7 +903,7 @@ fn run_audio( }; // The picture path's line, for a file that is sound alone: there is sound // by the line above, so this names the encoder writing it. - *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true).to_string()); + *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); let channels = usize::from(audio.channels); let frames = (f64::from(project.timeline_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) @@ -887,7 +935,10 @@ fn run_audio( match format { Format::Wav => write_wav(out, &samples, &audio)?, Format::Flac => write_flac(out, &samples, &audio)?, - Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"), + Format::Mp3 => write_mp3(out, &samples, &audio)?, + Format::Mp4 | Format::Av1 | Format::Av1Mp4 => { + unreachable!("the picture formats are `run`") + } } shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); Ok(()) @@ -914,6 +965,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<() Ok(()) } +/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure +/// Rust like every other encoder here, and the reason this format is a row at +/// all: the LGPL `shine-rs` was the only one when it was not. +/// +/// 256 kbps CBR, for [`encode_audio`]'s reason: an export is a master a person +/// edits from again, not a delivery file, and this is a lossy generation over +/// sources that may already have been one. The rate is snapped to a legal Layer +/// III value by the encoder, and a sample rate MPEG has no frame for (anything +/// but 8-48 kHz) is refused there by name rather than written as something else. +/// +/// ponytail: CBR only, and no rate is offered to the caller -- the export card +/// has one bitrate control and it is the *picture's*. Upgrade path is +/// `Mp3EncoderConfig::vbr_quality` behind a setting of its own. +fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { + let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig { + bitrate_kbps: 256, + vbr_quality: None, + }); + // The samples are the 16-bit ones a WAV of this timeline holds, so the two + // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this + // engine's own decoders do. + let pcm: Vec = samples.iter().map(|&s| s as i16).collect(); + encoder + .push_pcm_s16(&pcm, audio.channels, audio.sample_rate) + .map_err(|e| format!("mp3 encode: {e}"))?; + encoder.finish(); + let mut file = BufWriter::new(File::create(out)?); + // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info + // header first: the loop ends on the only error it can see. + while let Ok(frame) = encoder.next_packet() { + file.write_all(&frame)?; + } + file.flush()?; + Ok(()) +} + /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to /// text: they are not `Send + Sync`, and every one of them fails the export the /// same way. @@ -1014,34 +1101,59 @@ fn write_video( meta: &VideoMeta, settings: &ExportSettings, audio: Option<&AudioParams>, + packets: &mut Option>, au: &[u8], key: bool, ) -> crate::Result<()> { - if settings.format == Format::Av1 { + if settings.format.is_av1() { + // Every AV1 stream opens on a keyframe, and a keyframe carries the + // sequence header the track has to declare: an encoder that handed back + // neither has produced nothing a decoder can start. The same header goes + // into a `CodecPrivate` and into an `av1C` -- one record, two containers. + fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result> { + Ok(Av1Params { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + config: crate::mux::av1_sequence_header(au) + .ok_or("the first coded picture carries no AV1 sequence header")?, + }) + } + if settings.format == Format::Av1 { + let muxer = match muxer { + Some(Muxer::Mkv(mkv)) => mkv, + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + none => { + // The sound with it, all of it: the Matroska muxer writes the + // packets into the clusters of the pictures they play under. + let sound = audio.zip(packets.take()); + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( + out, + ¶ms(meta, au)?, + sound, + )?)) else { + unreachable!("just inserted a Matroska muxer") + }; + mkv + } + }; + return muxer.write_frame(au, key); + } let muxer = match muxer { - Some(Muxer::Mkv(mkv)) => mkv, - Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + Some(Muxer::Mp4(mp4)) => mp4, + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), none => { - // Every AV1 stream opens on a keyframe, and a keyframe carries - // the sequence header the track has to declare: an encoder that - // handed back neither has produced nothing a decoder can start. - let config = crate::mux::av1_sequence_header(au) - .ok_or("the first coded picture carries no AV1 sequence header")?; - let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1( out, - &Av1Params { - width: meta.width, - height: meta.height, - frame_rate: meta.frame_rate, - config, - }, + ¶ms(meta, au)?, + audio, )?)) else { - unreachable!("just inserted a Matroska muxer") + unreachable!("just inserted an mp4 muxer") }; - mkv + mp4 } }; - return muxer.write_frame(au, key); + return muxer.write_av1_frame(au, key); } if !crate::mux::has_coded_slice(au) { return Ok(()); @@ -1123,7 +1235,9 @@ impl Enc { } fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { - if settings.format == Format::Av1 { + // Which *codec* the picture is, not which container it goes in: both AV1 + // formats run the same encoder. + if settings.format.is_av1() { return Self::open_av1(meta, settings); } // A caller's number goes through the same clamp as the computed one: a diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 5344c58..bc629ac 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -5,10 +5,17 @@ //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all, //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read //! as EBML by hand ([`MkvMuxer`]). +//! +//! AV1 goes into an **mp4** too, and the missing sample entry is written by hand +//! there as well ([`Mp4Muxer::create_av1`]): the crate writes the file with an +//! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the +//! spec asks for, which is the only box in a whole mp4 the crate cannot spell. +//! Both containers carry the timeline's AAC, so no format here writes a picture +//! whose sound was silently left behind. -use std::fs::File; -use std::io::{BufWriter, Seek, SeekFrom, Write}; -use std::path::Path; +use std::fs::{File, OpenOptions}; +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; use mp4::{ AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, @@ -41,20 +48,31 @@ pub struct VideoParams<'a> { pub pps: &'a [u8], } -/// Read straight off the source file's `esds`: export copies AAC packets, it -/// never re-encodes, so the decoder config is passed through unchanged. +/// What the audio track declares: read straight off the source file's `esds` +/// where the export copies packets, and off this project's own encoder where it +/// re-encodes ([`crate::export`] decides which). `sample_rate` says the same +/// thing `freq_index` does and is carried beside it because Matroska states the +/// rate as a number rather than as an index into the AAC table. pub struct AudioParams { pub freq_index: u8, pub chan_conf: u8, + pub sample_rate: u32, } -/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores +/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so /// every sample handed over must carry an exact duration or the tracks drift. pub struct Mp4Muxer { writer: Mp4Writer>, frame_duration: u32, has_audio: bool, + /// The `av1C` record an AV1 file's sample entry is patched to carry at + /// [`finish`](Mp4Muxer::finish); `None` for H.264, which the crate spells + /// itself. See [`create_av1`](Mp4Muxer::create_av1). + av1c: Option>, + /// Where the file is, for that patch: the writer owns the handle it wrote + /// through and the patch reopens the finished file. + path: PathBuf, } const VIDEO_TRACK: u32 = 1; @@ -65,6 +83,61 @@ impl Mp4Muxer { path: &Path, video: &VideoParams, audio: Option<&AudioParams>, + ) -> crate::Result { + Self::open(path, video, audio, None) + } + + /// The same file with an AV1 track in it. `mp4 0.14` writes no `av01` sample + /// entry -- it has no AV1 anything -- so the file is written with an `avc1` + /// entry of placeholder parameter sets and that one entry is rewritten at + /// [`finish`](Mp4Muxer::finish) into the `av01` + `av1C` pair AV1-ISOBMFF + /// §2.2 asks for. Everything else in an mp4 is codec-blind (the sample + /// tables, the audio track, the movie header), so the entry is the only box + /// this has to spell by hand -- and the `moov` it lives in is written *after* + /// `mdat`, so growing it moves no sample and invalidates no chunk offset. + /// + /// The record's layout is the one OxideAV's `oxideav-mp4` writes + /// (`src/sample_entries.rs`, MIT): a `VisualSampleEntry` header verbatim, + /// then `av1C` -- the very four bytes and sequence header OBU [`MkvMuxer`] + /// puts in `CodecPrivate`, which is what makes the two containers' AV1 one + /// stream written twice rather than two. + /// + /// ponytail: the ceiling is that one entry. A second video track, or an AV1 + /// track beside an H.264 one, would need the walk in [`patch_av01`] to be + /// told *which* track it is patching; the upgrade path is passing the track + /// id it already knows down that walk. + pub fn create_av1( + path: &Path, + video: &Av1Params, + audio: Option<&AudioParams>, + ) -> crate::Result { + if video.config.is_empty() { + return Err("no AV1 sequence header for the track's av1C record".into()); + } + let mut av1c = AV1C_HEAD.to_vec(); + av1c.extend_from_slice(video.config); + Self::open( + path, + &VideoParams { + width: video.width, + height: video.height, + frame_rate: video.frame_rate, + // Never read by anything: the entry that holds them is replaced + // whole at `finish`. Four bytes because `AvcCBox::new` indexes + // `sps[1..=3]` for the profile it will never be asked for. + sps: &[0x67, 0x42, 0x00, 0x1E], + pps: &[0x68, 0xCE, 0x3C, 0x80], + }, + audio, + Some(av1c), + ) + } + + fn open( + path: &Path, + video: &VideoParams, + audio: Option<&AudioParams>, + av1c: Option>, ) -> crate::Result { if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { return Err(format!("bad frame rate {}", video.frame_rate).into()); @@ -88,10 +161,15 @@ impl Mp4Muxer { &Mp4Config { major_brand: FourCC::from(*b"isom"), minor_version: 512, + // The codec's own brand among them, so a reader that picks a + // parser off `ftyp` is told which of the two this is. compatible_brands: vec![ FourCC::from(*b"isom"), FourCC::from(*b"iso2"), - FourCC::from(*b"avc1"), + FourCC::from(match av1c { + Some(_) => *b"av01", + None => *b"avc1", + }), FourCC::from(*b"mp41"), ], // The video track's own, deliberately: `mp4` converts every @@ -116,6 +194,9 @@ impl Mp4Muxer { })?; if let Some(audio) = audio { let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; + // The index's own rate, not `audio.sample_rate`: this is the clock + // an `stts` counts in and the `esds` states the index, so the two + // must not be able to disagree. let sample_rate = freq_index.freq(); writer.add_track(&TrackConfig { track_type: TrackType::Audio, @@ -134,6 +215,8 @@ impl Mp4Muxer { writer, frame_duration, has_audio: audio.is_some(), + av1c, + path: path.to_path_buf(), }) } @@ -154,6 +237,28 @@ impl Mp4Muxer { Ok(()) } + /// One coded picture as an AV1 temporal unit, written verbatim: an mp4 AV1 + /// sample is the low-overhead OBU stream the encoder handed over, exactly as + /// a Matroska block is, so there is nothing to reframe. `key` is the + /// encoder's own word for a unit a decoder may start on -- an mp4 says it in + /// `stss` where Matroska says it in the block flags. + pub fn write_av1_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { + if obus.is_empty() { + return Err("an empty AV1 temporal unit".into()); + } + self.writer.write_sample( + VIDEO_TRACK, + &Mp4Sample { + start_time: 0, + duration: self.frame_duration, + rendering_offset: 0, + is_sync: key, + bytes: Bytes::copy_from_slice(obus), + }, + )?; + Ok(()) + } + /// One raw AAC packet (no ADTS header), copied verbatim from the source -- /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. @@ -178,8 +283,119 @@ impl Mp4Muxer { pub fn finish(mut self) -> crate::Result<()> { self.writer.write_end()?; - Ok(()) + let Self { + writer, av1c, path, .. + } = self; + // Not a `drop`: the buffered tail of `moov` has to be on disk before the + // patch below reads it back, and a `BufWriter` swallows the error of + // flushing it on drop. + writer.into_writer().flush()?; + match av1c { + Some(av1c) => patch_av01(&path, &av1c), + None => Ok(()), + } + } +} + +/// Rewrites the finished file's one video sample entry from the `avc1` the crate +/// wrote into the `av01` + `av1C` an AV1 track declares. Called once, on a +/// complete file, and only for a file [`Mp4Muxer::create_av1`] opened. +/// +/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only +/// ever rewrites the tail of the file: no sample moves and no chunk offset in +/// `co64` changes. The box tree is rebuilt rather than patched in place, which +/// is what keeps every ancestor's size right by construction. +fn patch_av01(path: &Path, av1c: &[u8]) -> crate::Result<()> { + let mut file = OpenOptions::new().read(true).write(true).open(path)?; + let end = file.metadata()?.len(); + let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; + let patched = swap_av01(&payload, 0, av1c).ok_or("no avc1 sample entry to rewrite as av01")?; + let mut out = Vec::with_capacity(patched.len() + 8); + push_box(&mut out, b"moov", &patched); + file.seek(SeekFrom::Start(at))?; + file.write_all(&out)?; + file.set_len(at + out.len() as u64)?; + file.flush()?; + Ok(()) +} + +/// Offset and payload of the first top-level box of type `want`. +fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result)>> { + let mut at = 0u64; + while at + 8 <= end { + let mut header = [0u8; 8]; + file.seek(SeekFrom::Start(at))?; + file.read_exact(&mut header)?; + let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) { + 0 => (end - at, 8), + 1 => { + let mut large = [0u8; 8]; + file.read_exact(&mut large)?; + (u64::from_be_bytes(large), 16) + } + size => (u64::from(size), 8), + }; + if size < head_len || at + size > end { + return Err("truncated box in the file's top level".into()); + } + if &header[4..8] == want { + let mut payload = vec![0u8; (size - head_len) as usize]; + file.read_exact(&mut payload)?; + return Ok(Some((at, payload))); + } + at += size; } + Ok(None) +} + +/// `moov` down to the sample descriptions, which is where the entry lives. +const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"]; + +/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry replaced. +/// `None` where this branch holds no such entry -- an audio `trak` is walked +/// into and comes back untouched, which is how the *video* track is found +/// without being told which id it has. +fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option> { + if depth == STSD_PATH.len() { + // stsd is a FullBox (4) plus entry_count (4), then the sample entries. + let mut out = payload.get(..8)?.to_vec(); + let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?; + if kind != b"avc1" { + return None; + } + // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all) + // before its codec box, and `av01` carries exactly the same ones -- so + // the header is kept and only the configuration box is swapped. + let mut swapped = entry.get(..78)?.to_vec(); + push_box(&mut swapped, b"av1C", av1c); + push_box(&mut out, b"av01", &swapped); + return Some(out); + } + let mut out = Vec::with_capacity(payload.len()); + let mut done = false; + for (kind, child) in crate::demux::boxes(payload) { + let patched = match !done && kind == STSD_PATH[depth] { + true => swap_av01(child, depth + 1, av1c), + false => None, + }; + match patched { + Some(child) => { + push_box(&mut out, kind, &child); + done = true; + } + None => push_box(&mut out, kind, child), + } + } + done.then_some(out) +} + +/// One mp4 box: 32-bit size, four-character type, payload. Every box inside a +/// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never +/// rewrites. +fn push_box(out: &mut Vec, kind: &[u8; 4], payload: &[u8]) { + out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(payload); } // Matroska element ids, written with the leading length marker they carry in the @@ -210,6 +426,10 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +const AUDIO: u32 = 0xE1; +const SAMPLING_FREQUENCY: u32 = 0xB5; +const CHANNELS: u32 = 0x9F; +const CODEC_DELAY: u32 = 0x56AA; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; @@ -251,11 +471,17 @@ pub struct Av1Params<'a> { pub config: &'a [u8], } -/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project -/// has no encoder for any sound Matroska carries, and copying the timeline's AAC -/// in would write a track its own reader refuses (`audio::AudioSession::open` -/// leaves a Matroska file silent) -- so the sound is named as left out by the -/// front-end rather than written unplayable. +/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC +/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the +/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what +/// symphonia's `mkv` reader -- this project's own way back in -- configures its +/// decoder from. An AV1 export used to be picture alone; a video file whose +/// sound was silently left behind is exactly the failure nobody notices until +/// the file has gone somewhere. +/// +/// The sound is *interleaved*: each packet is written into the cluster of the +/// picture it plays under, so a player has both by the time it needs them rather +/// than a file it must read to the end of to hear. /// /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size /// and the duration -- so a killed process leaves an unfinished file rather than @@ -272,10 +498,36 @@ pub struct MkvMuxer { cluster: Vec, cluster_ts: i64, frames: u64, + /// The AAC track, if the timeline has sound, and how far it has been + /// written. + audio: Option, +} + +/// The sound waiting to be interleaved into the clusters. +struct MkvAudio { + packets: Vec, + /// Packets already written. + next: usize, + /// Frames already written, which is what the next packet's timestamp is + /// counted from: every AAC-LC packet says its own length and they are not + /// assumed equal here. + samples: u64, + sample_rate: u32, } impl MkvMuxer { - pub fn create(path: &Path, video: &Av1Params) -> crate::Result { + /// `audio` is the whole track at once -- the export has it before it has a + /// single coded picture, and interleaving needs to look ahead of the frame + /// being written. + /// + /// ponytail: that is the copy path's own ceiling reappearing (the track sits + /// in memory, ~500 MB an hour); the upgrade path is the same streaming + /// `copy_segments` `export::copy_audio` names. + pub fn create( + path: &Path, + video: &Av1Params, + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { return Err(format!("bad frame rate {}", video.frame_rate).into()); } @@ -335,6 +587,9 @@ impl MkvMuxer { elem(&mut entry, VIDEO, &dims); let mut tracks = Vec::new(); elem(&mut tracks, TRACK_ENTRY, &entry); + if let Some((audio, _)) = &audio { + elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); + } elem(&mut head, TRACKS, &tracks); let mut file = File::create(path)?; @@ -347,6 +602,12 @@ impl MkvMuxer { cluster: Vec::new(), cluster_ts: 0, frames: 0, + audio: audio.map(|(params, packets)| MkvAudio { + packets, + next: 0, + samples: 0, + sample_rate: params.sample_rate.max(1), + }), }) } @@ -373,14 +634,58 @@ impl MkvMuxer { self.cluster_ts = ts; uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); } - let mut block = Vec::with_capacity(obus.len() + 4); - block.push(0x81); // track number 1, as a one-byte EBML integer + // The sound this picture plays under goes in first, into the cluster the + // picture opened: a player reads the two together. + self.drain_audio(ts)?; + self.block(1, ts, key, obus); + self.frames += 1; + Ok(()) + } + + /// Every audio packet whose timestamp has been reached, into the current + /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left -- + /// the sound of a timeline can outlast its last picture by a packet. + fn drain_audio(&mut self, until: i64) -> crate::Result<()> { + loop { + let Some(audio) = &mut self.audio else { + return Ok(()); + }; + let Some(packet) = audio.packets.get_mut(audio.next) else { + return Ok(()); + }; + // The packet's own start, in whole milliseconds: every AAC-LC packet + // states its length, so a track of them is counted rather than + // assumed to be 1024 frames each. + let rate = i64::from(audio.sample_rate); + let ts = (audio.samples as i64 * 1000 + rate / 2) / rate; + if ts > until { + return Ok(()); + } + // Taken, not copied: the packet is written once and the track can be + // hundreds of megabytes. + let bytes = std::mem::take(&mut packet.bytes); + audio.samples += u64::from(packet.samples); + audio.next += 1; + // A cluster of its own where the sound has run past what a 16-bit + // relative timestamp reaches, which only the tail drain can do. + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { + self.flush()?; + self.cluster_ts = ts; + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + } + self.block(2, ts, true, &bytes); + } + } + + /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC + /// packet is a keyframe; a picture is one when the encoder said so. + fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { + let mut block = Vec::with_capacity(payload.len() + 4); + block.push(0x80 | track); // the track number as a one-byte EBML integer block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); block.push(if key { 0x80 } else { 0 }); - block.extend_from_slice(obus); + block.extend_from_slice(payload); elem(&mut self.cluster, SIMPLE_BLOCK, &block); - self.frames += 1; - Ok(()) } fn flush(&mut self) -> crate::Result<()> { @@ -399,6 +704,9 @@ impl MkvMuxer { /// Closes the last cluster and patches the two fields that could not be /// known while writing: the segment's size and the presentation duration. pub fn finish(mut self) -> crate::Result<()> { + // Whatever sound outlasts the last picture, before the last cluster is + // closed: a track cut short here is a file that goes silent at the end. + self.drain_audio(i64::MAX)?; self.flush()?; if self.frames == 0 { return Err("no frames were written to the Matroska file".into()); @@ -417,6 +725,52 @@ impl MkvMuxer { } } +/// The `TrackEntry` of the AAC track: `A_AAC`, whose `CodecPrivate` is the +/// two-byte `AudioSpecificConfig` an mp4 states inside its `esds` -- object type +/// 2 (AAC-LC), the sample rate as its index into the AAC table, and the channel +/// configuration. symphonia's `mkv` reader hands exactly these bytes to its AAC +/// decoder, which is how a file written here reads back here. +/// +/// `CodecDelay` is one packet: the first AAC access unit of both paths that +/// reach this -- a copy, whose head packet is the source's priming, and this +/// project's own encoder, whose delay is one 1024-frame block -- is that delay, +/// and an mp4 reader drops it by convention where Matroska has to be told in +/// nanoseconds. +fn aac_track_entry(audio: &AudioParams) -> crate::Result> { + let rate = audio.sample_rate; + if rate == 0 || audio.chan_conf == 0 { + return Err(format!( + "an AAC track at {rate} Hz with {} channels", + audio.chan_conf + ) + .into()); + } + let mut entry = Vec::new(); + uint(&mut entry, TRACK_NUMBER, 2); + uint(&mut entry, TRACK_UID, 2); + uint(&mut entry, TRACK_TYPE, 2); // audio + uint(&mut entry, FLAG_LACING, 0); + elem(&mut entry, CODEC_ID, b"A_AAC"); + // 5 bits object type, 4 bits sample rate index, 4 bits channel config, and + // three zero bits to the byte -- the whole of an AAC-LC AudioSpecificConfig. + let asc = (2u16 << 11) + | (u16::from(audio.freq_index & 0xF) << 7) + | (u16::from(audio.chan_conf & 0xF) << 3); + elem(&mut entry, CODEC_PRIVATE, &asc.to_be_bytes()); + uint( + &mut entry, + CODEC_DELAY, + u64::from(AAC_PACKET_SAMPLES) * 1_000_000_000 / u64::from(rate), + ); + let mut audio_elem = Vec::new(); + put_id(&mut audio_elem, SAMPLING_FREQUENCY); + put_size(&mut audio_elem, 8); + audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes()); + uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf)); + elem(&mut entry, AUDIO, &audio_elem); + Ok(entry) +} + /// The sequence header OBU of a coded temporal unit, for the track's /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe /// of a stream never may -- no decoder can start without it. @@ -750,6 +1104,7 @@ mod tests { Some(&AudioParams { freq_index: 4, // 44100 chan_conf: 2, + sample_rate: 44_100, }), ) .unwrap(); @@ -840,6 +1195,168 @@ mod tests { assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]); } + /// One second of a 440 Hz tone as AAC-LC packets, through the very encoder + /// an export re-encodes with: real bitstream, so a file written with it is + /// one a decoder either plays or does not. + fn tone_packets(rate: u32, channels: u16) -> Vec { + let frames = rate as usize; + let mut pcm = Vec::with_capacity(frames * usize::from(channels)); + for i in 0..frames { + let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5; + for _ in 0..channels { + pcm.push(s); + } + } + let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig::default()); + encoder.push_pcm(&pcm, channels, rate).unwrap(); + encoder.finish(); + let mut packets = Vec::new(); + while let Ok(packet) = encoder.next_packet() { + packets.push(crate::AacPacket { + bytes: packet.data, + samples: packet.duration, + }); + } + assert!(packets.len() > 10, "a second of audio is many packets"); + packets + } + + /// The Matroska file carries **sound**, and this project's own reader is + /// what hears it: picture and an AAC track out through the muxer, then the + /// picture back through our EBML reader and the sound back through the + /// symphonia `mkv` reader `audio::Track::open` uses. An AV1 export used to be + /// picture alone, which is a file whose sound went missing with nobody told. + #[test] + fn a_matroska_file_carries_its_picture_and_its_sound() { + let sequence = obu(1, &[0x11, 0x22, 0x33]); + let mut key = sequence.clone(); + key.extend_from_slice(&obu(6, &[0xAA; 8])); + let inter = obu(6, &[0xBB; 5]); + let packets = tone_packets(48_000, 2); + let heard: usize = packets.iter().map(|p| p.samples as usize).sum(); + + let out = std::env::temp_dir().join(format!("ve_mkv_sound_{}.mkv", std::process::id())); + let mut muxer = MkvMuxer::create( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config: av1_sequence_header(&key).unwrap(), + }, + Some(( + &AudioParams { + freq_index: 3, // 48000 + chan_conf: 2, + sample_rate: 48_000, + }, + packets, + )), + ) + .unwrap(); + // Half a second of picture under a second of sound: the tail of the + // audio outlives the last frame and must still be in the file. + muxer.write_frame(&key, true).unwrap(); + for _ in 0..14 { + muxer.write_frame(&inter, false).unwrap(); + } + muxer.finish().unwrap(); + + // The picture is untouched by the sound beside it: same units, same + // count, same sequence header in front of the keyframe. + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); + assert_eq!(meta.frame_count, 15); + assert_eq!(meta.codec, crate::demux::Codec::Av1); + let first = demuxer.next_access_unit().unwrap().unwrap(); + assert_eq!(&first[sequence.len()..], &key[..]); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + + // ...and the sound is there, by name and then by ear. + assert_eq!( + crate::demux::matroska_audio_codec(&out).unwrap().as_deref(), + Some("A_AAC") + ); + let probe = crate::audio::AudioSession::probe(&out, 0) + .unwrap() + .expect("the file has an audio track"); + assert_eq!((probe.sample_rate, probe.channels), (48_000, 2)); + let (audio, chunks) = crate::audio::AudioSession::open(&out) + .unwrap() + .expect("decodes through symphonia's mkv reader"); + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let frames = samples.len() / 2; + assert!( + frames + 1024 >= heard && frames <= heard + 2048, + "{frames} frames read back of {heard} written" + ); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len() as f32).sqrt(); + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } + + /// The same stream in the other container: AV1 into an mp4, whose `av01` + /// sample entry is written by hand, read back through our own demuxer -- + /// which is the only test that the patched box tree is still an mp4. + #[test] + fn an_av1_track_round_trips_through_an_mp4() { + let sequence = obu(1, &[0x11, 0x22, 0x33]); + let mut key = sequence.clone(); + key.extend_from_slice(&obu(6, &[0xAA; 8])); + let inter = obu(6, &[0xBB; 5]); + let packets = tone_packets(48_000, 2); + + let out = std::env::temp_dir().join(format!("ve_mp4_av1_{}.mp4", std::process::id())); + let mut muxer = Mp4Muxer::create_av1( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config: av1_sequence_header(&key).unwrap(), + }, + Some(&AudioParams { + freq_index: 3, + chan_conf: 2, + sample_rate: 48_000, + }), + ) + .unwrap(); + muxer.write_av1_frame(&key, true).unwrap(); + muxer.write_av1_frame(&inter, false).unwrap(); + muxer.write_av1_frame(&inter, false).unwrap(); + for packet in &packets { + muxer.write_audio_packet(&packet.bytes).unwrap(); + } + muxer.finish().unwrap(); + + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); + assert_eq!(meta.codec, crate::demux::Codec::Av1, "read back as AV1"); + assert_eq!((meta.width, meta.height), (640, 360)); + assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{}", meta.frame_rate); + assert_eq!(meta.frame_count, 3); + // The sequence header off `av1C` in front of the keyframe, exactly as + // the Matroska reader puts the one off `CodecPrivate` there. + let first = demuxer.next_access_unit().unwrap().unwrap(); + assert_eq!(&first[..sequence.len()], &sequence[..]); + assert_eq!(&first[sequence.len()..], &key[..]); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert!(demuxer.next_access_unit().unwrap().is_none()); + assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0, "one keyframe"); + + // ...and the audio track beside it is the mp4 path's own, unchanged by + // the patch: same packets, playable through the same reader. + let (audio, chunks) = crate::audio::AudioSession::open(&out) + .unwrap() + .expect("the mp4's AAC track"); + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len() as f32).sqrt(); + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } + /// The Matroska half of the round trip, with no encoder in it: three coded /// units out through the muxer and back in through our own demuxer, which is /// where the hand-written EBML meets the hand-written EBML reader. @@ -861,6 +1378,7 @@ mod tests { frame_rate: 30.0, config, }, + None, ) .unwrap(); muxer.write_frame(&key, true).unwrap(); @@ -903,6 +1421,7 @@ mod tests { frame_rate: 30.0, config: &[], }, + None, ) .is_err() ); diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index 4348dc4..d259ab9 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -160,8 +160,10 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { } } -/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC -/// encoder here -- and that refusal is named, never a silent silent export. +/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the +/// *copy* path names it and hands the export on to the re-encode (which decodes +/// this very source: the downmix above is what it encodes). Named either way -- +/// never a silent export. #[test] fn an_ac3_source_refuses_an_mp4_audio_copy() { 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() { }; let err = err.to_string(); assert!( - err.contains("needs AAC audio") && err.contains("AC-3"), + err.contains("needs AAC in an mp4") && err.contains("AC-3"), "unhelpful refusal: {err}" ); } diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 416e4df..587c19e 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -55,8 +55,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`. /// /// Three things at once: a cut, a gap (which must arrive as silence), and a -/// source the mp4 export flatly refuses — there is no AAC encoder here, so an -/// mp3 on the timeline can *only* leave through this door. +/// source no mp4 sample table holds — an mp3, which the mp4 path decodes and +/// re-encodes today and once refused outright. fn mixed_project() -> Project { let clip = |start, source| Clip { start, @@ -252,6 +252,116 @@ fn exports_the_timeline_as_a_flac() { std::fs::remove_file(&out).unwrap(); } +/// The third audio row, and the one that used to be a licence note: `rusty_mp3` +/// encodes it, and the file is read straight back through symphonia's mp3 +/// decoder -- the very door an mp3 *import* comes in through, so an export can +/// be dropped back onto the timeline it came from. +/// +/// The shape is checked loosely where MP3 cannot be exact: the encoder pads its +/// tail to a whole 1152-frame frame and the decoder hands back the padding, so +/// the length is asserted to within a frame instead of to the sample. What is +/// exact is the edit -- audible, silent, audible -- and the fixtures' 1 Hz +/// pulse inside the first second. +#[test] +fn exports_the_timeline_as_an_mp3() { + let out = out_path("mp3", "mp3"); + let handle = engine::export::start( + mixed_project(), + meta(), + &out, + &ExportSettings { + format: Format::Mp3, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(120)).expect("mp3 export"); + assert_eq!(handle.progress(), 1.0, "finished at full progress"); + assert!(!part_path(&out).exists(), "the .part was renamed away"); + + let (meta, samples) = decode(&out); + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2)); + let channels = usize::from(meta.channels); + let frames = samples.len() / channels; + let timeline = (3.0 * f64::from(RATE)) as usize; + assert!( + frames >= timeline && frames <= timeline + 2 * 1152, + "{frames} frames for a three-second timeline ({timeline})" + ); + let av = rms(&samples, channels, 0.05, 0.95); + let gap = rms(&samples, channels, 1.1, 1.9); + let tone = rms(&samples, channels, 2.05, 2.95); + println!("mp3 rms: av {av:.4} gap {gap:.6} mp3 second {tone:.4}"); + assert!(av > 0.01, "the first second is audible"); + assert!(tone > 0.01, "the mp3 second is audible"); + assert!(gap < av / 20.0, "the hole is silence: {gap:.6}"); + let peak = rms(&samples, channels, 0.2, 0.3); + let dip = rms(&samples, channels, 0.7, 0.8); + assert!( + peak > dip * 4.0, + "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// The failure a user hit, as a test: a still picture and a song, exported as an +/// **mp4**. There is no AAC track anywhere in that timeline to copy -- an mp3 +/// holds no such packets and a png holds nothing at all -- so this used to be +/// refused by name and the only way out was a WAV beside a picture nobody had. +/// The song is decoded and encoded as AAC instead (`export::copy_audio` falls +/// through to `encode_audio`), and the file comes back with picture *and* sound. +#[test] +fn a_still_and_a_song_export_as_an_mp4_with_sound() { + let song = asset("test_tone.mp3"); + let still = asset("test_still.png"); + let clip = |source, frames| Clip { + start: 0, + in_frame: 0, + out_frame: frames, + source, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + // Two seconds of each at the project's own 30 fps: a still has no length of + // its own and the song is longer than what is placed. + let project = Project::from_parts( + vec![Source::new(still, 0), Source::new(song, 0)], + vec![ + (LaneKind::Video, vec![clip(0, 60)]), + (LaneKind::Audio, vec![clip(1, 60)]), + ], + Vec::new(), + Vec::new(), + ) + .expect("a still under a song"); + // The project's own picture size and rate: the still decides the one and + // the scaffold the other, exactly as opening a png in the editor does. + let meta = engine::VideoMeta { + width: 640, + height: 360, + frame_rate: 30.0, + frame_count: 60, + codec: engine::Codec::H264, + }; + let out = out_path("still_song", "mp4"); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); + + // Picture: two seconds of it, through the demuxer an import uses. + let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!((written.width, written.height), (640, 360)); + assert_eq!(written.frame_count, 60, "two seconds at 30 fps"); + // ...and sound, which is the half that used to be missing. + let (audio, samples) = decode(&out); + let channels = usize::from(audio.channels); + let heard = rms(&samples, channels, 0.2, 1.8); + println!("still+song: {} Hz, rms {heard:.4}", audio.sample_rate); + assert!(heard > 0.01, "the song is in the file (rms {heard:.4})"); + std::fs::remove_file(&out).unwrap(); +} + /// Cancel leaves nothing behind -- not the output, not the `.part`. The /// timeline is long enough (a minute of audio) that the escape lands mid-decode /// rather than after the file is already closed. @@ -307,9 +417,9 @@ fn a_silent_timeline_refuses_an_audio_export() { ); } -/// An AC-3 source leaves through this door and no other: the mp4 export cannot -/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the -/// same timeline decodes, downmixes and reopens through the engine's own reader. +/// An AC-3 source through the audio-only door: the mp4 export cannot +/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline +/// decodes, downmixes and reopens through the engine's own reader. #[test] fn a_51_ac3_source_round_trips_through_a_wav() { let source = asset("test_ac3_51.mp4"); diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index c0dc532..d1d018f 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -273,7 +273,7 @@ fn an_audio_only_project_saves_reloads_and_exports_its_sound() { assert_eq!( e.to_string(), "the timeline has no picture: an mp4 would be black. \ - Export WAV or FLAC, which are the sound itself" + Export WAV, FLAC or MP3, which are the sound itself" ); assert!(!mp4.exists(), "the refusal wrote a file anyway"); @@ -415,16 +415,19 @@ fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { } } -/// The export copies AAC packets and has no encoder, so a timeline carrying an -/// mp3 cannot become an mp4 -- named, with its format, rather than exported -/// silent or exported wrong. +/// The *copy* path names what it cannot copy, by file and by format. That is a +/// fallback's reason rather than a user's refusal now -- `export::copy_audio` +/// takes this `Err` as "not copyable" and decodes and re-encodes the timeline +/// instead (`tests/audio_export.rs` exports exactly this shape as an mp4 with +/// sound in it) -- but the words are what a caller with no encoder shows, so +/// they are still asserted here. #[test] fn an_export_refuses_audio_it_cannot_copy() { let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")]; let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; assert_eq!( refusal(AudioSession::copy_multi_segments(&sources, &segs)), - "export needs AAC audio today; test_tone.mp3 is mp3" + "a packet copy needs AAC in an mp4; test_tone.mp3 is mp3" ); // A timeline of nothing but mp4 still exports, which is the invariant this // refusal must not have cost. diff --git a/crates/engine/tests/audio_segments.rs b/crates/engine/tests/audio_segments.rs index d66538f..39ad7ce 100644 --- a/crates/engine/tests/audio_segments.rs +++ b/crates/engine/tests/audio_segments.rs @@ -185,7 +185,7 @@ fn a_gap_segment_is_silence_of_its_own_length() { ); } -/// The copy side of a gap: there is no AAC encoder here, so the hole is copied +/// The copy side of a gap: a copy never encodes, so the hole is copied /// as hand-written silent packets -- real access units, one 1024-frame stts /// entry each, the rounding debt carried through them like any other segment. /// Every packet after the gap therefore still lands at its timeline position. diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index b7a0134..4eb6ed4 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -195,39 +195,45 @@ fn a_seek_lands_on_the_frame_it_asked_for() { assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for"); } -/// An mp4 export of a Matroska source is refused by name, and says where the -/// sound can go instead. +/// An mp4 export of a Matroska source carries its sound. /// -/// It used to *succeed*, silently, and only because this engine could not read -/// a Matroska file's audio at all: the export wrote picture with no sound in it -/// and nobody was told. Now that the sound is read (`tests/hevc_mkv.rs`), the -/// rule the whole mp4 path is built on applies to it like to any other source -/// it cannot copy -- an AC-3 mp4 has always been refused in the same breath. -/// The picture half of the same export is [`an_av1_export_reopens_through_our_own_demuxer`]. +/// Three lives, this one. It used to *succeed* silently and write picture with +/// no sound, because this engine could not read a Matroska file's audio at all. +/// Then the sound became readable and this became a refusal by name, because +/// the mp4 path could only *copy* AAC out of an mp4's own sample table and a +/// Matroska file has none. Now the copy that cannot be made is a decode and a +/// re-encode (`export::copy_audio` -> `encode_audio`), so the export carries the +/// film's sound instead of naming what it cannot do with it. The picture half of +/// the same export is [`an_av1_export_reopens_through_our_own_demuxer`]. #[test] #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] -fn an_mp4_export_of_a_matroska_source_is_refused_by_name() { +fn an_mp4_export_of_a_matroska_source_carries_its_sound() { let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv"); let meta = *session.meta(); - let project = Project::single(asset("test_av1.mkv"), meta.frame_count); + // A short one: the picture is re-encoded frame by frame and what is under + // test here is the sound reaching the file, not H.264 throughput. + let project = Project::single(asset("test_av1.mkv"), 15); let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id())); let _ = std::fs::remove_file(&out); let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); let started = Instant::now(); while !handle.is_finished() { - assert!(started.elapsed() < Duration::from_secs(120), "export hung"); + assert!(started.elapsed() < Duration::from_secs(300), "export hung"); std::thread::sleep(Duration::from_millis(20)); } - let refused = handle + handle .result() .expect("outcome") - .expect_err("an mkv's AAC cannot be copied into an mp4") - .to_string(); - assert!(refused.contains("test_av1.mkv"), "{refused}"); - assert!(refused.contains("Matroska"), "{refused}"); - assert!(refused.contains("WAV or FLAC"), "{refused}"); - assert!(!out.exists(), "a refused export leaves no file behind"); + .expect("an mkv's AAC is decoded and encoded again into the mp4"); + let (audio, chunks) = AudioSession::open(&out) + .expect("reopen the export") + .expect("the export has an audio track"); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len().max(1) as f32).sqrt(); + println!("mkv -> mp4: {} Hz, rms {rms:.4}", audio.sample_rate); + assert!(rms > 0.001, "the film's sound is in the mp4 (rms {rms})"); + std::fs::remove_file(&out).unwrap(); } /// 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() { std::fs::remove_file(&out).unwrap(); } +/// A timeline with sound, exported as AV1 into **both** containers: the file +/// carries the picture *and* the timeline's audio, and this project's own +/// readers are what say so -- the demuxer for the picture, the audio session for +/// the sound. An AV1 export used to be picture only, which is a file whose sound +/// went missing with nobody told. +/// +/// Two frames of 720p: `rav1e` is built here without its assembly, so the length +/// of the timeline is the length of the test, and what is under test is the +/// wiring from the format to the muxer, not the encoder. +#[test] +fn an_av1_export_carries_the_timelines_sound_in_either_container() { + for (format, ext) in [ + (engine::export::Format::Av1, "mkv"), + (engine::export::Format::Av1Mp4, "mp4"), + ] { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av"); + assert!(session.cut_at(2.0 / 30.0), "two frames of it"); + assert!(session.delete_clip(engine::project::Lane::V1, 1)); + let out = std::env::temp_dir().join(format!("ve_av1_sound_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&out); + let settings = ExportSettings { + format, + force_sw: true, + ..Default::default() + }; + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(300), "export hung"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("an AV1 export"); + + // The picture, through the demuxer an import comes in by -- an `av01` + // sample entry in the mp4 and a `V_AV1` track in the Matroska file, both + // of them written by hand and read back by hand. + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(meta.codec, Codec::Av1, "{ext}: an AV1 export is AV1"); + assert_eq!((meta.width, meta.height), (1280, 720), "{ext}"); + assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there"); + + // ...and the sound beside it, which is the half that used to be absent. + let (audio, chunks) = AudioSession::open(&out) + .expect("reopen for its sound") + .expect("an AV1 export has an audio track"); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len().max(1) as f32).sqrt(); + println!( + "{ext}: {} Hz x{}, rms {rms:.4}", + audio.sample_rate, audio.channels + ); + assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } +} + /// An audio-only timeline is refused an AV1 export by name, exactly as it is /// refused an mp4: every frame of it is a gap, so the file would be black. #[test] diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs index 35e1979..0a995e0 100644 --- a/crates/engine/tests/backends.rs +++ b/crates/engine/tests/backends.rs @@ -96,49 +96,70 @@ fn a_playing_session_reports_the_seat_the_probe_named() { /// picture's seat is probed by opening the very encoder the export opens, and /// the sound's is decided outright. A drift between them is a front-end lying /// about the machine, which is exactly what this whole surface is for. +/// +/// Every picture format, because each one is a different pair of seats: H.264 +/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either +/// container -- a container is not an encoder, and the card must not say it is. #[test] fn the_planned_encoders_are_the_ones_the_job_opens() { - let settings = ExportSettings { - format: Format::Mp4, - ..ExportSettings::default() - }; - let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - let planned = format!( - "{} · {}", - engine::export::planned_video(session.meta(), &settings).expect("an mp4 carries picture"), - session.planned_audio(Format::Mp4) - ); - let out = out_path("planned", "mp4"); - let handle = session.export_to_with(&out, &settings); - let started = Instant::now(); - let opened = loop { - if let Some(line) = handle.encoders() { - break line; - } - assert!( - !handle.is_finished(), - "the export settled before it opened an encoder: {:?}", - handle.result().map(|r| r.err()) + for (format, ext) in [ + (Format::Mp4, "mp4"), + (Format::Av1, "mkv"), + (Format::Av1Mp4, "mp4"), + ] { + let settings = ExportSettings { + format, + ..ExportSettings::default() + }; + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let planned = format!( + "{} · {}", + engine::export::planned_video(session.meta(), &settings) + .expect("these formats carry picture"), + session.planned_audio(format) ); - assert!( - started.elapsed() < Duration::from_secs(60), - "no encoder was published" - ); - std::thread::sleep(Duration::from_millis(10)); - }; - // Nothing here wants the file, only the seat it was going to be written - // with: cancelling deletes the `.part` the worker had started. - handle.cancel(); - wind_down(&handle); - assert_eq!(opened, planned); + let out = out_path("planned", ext); + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + !handle.is_finished(), + "the export settled before it opened an encoder: {:?}", + handle.result().map(|r| r.err()) + ); + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + // Nothing here wants the file, only the seat it was going to be written + // with: cancelling deletes the `.part` the worker had started. + handle.cancel(); + wind_down(&handle); + assert_eq!(opened, planned, "{ext}"); + // ...and the sound is named on both, AV1 included: an AV1 export + // carries the timeline's audio now, so a line that said nothing about + // it would be the old picture-only lie in a new place. + assert!(planned.contains("AAC"), "{ext}: {planned}"); + } } /// A WAV job has no picture at all and still names what writes it, so an audio /// export is not a progress line with nothing to say. #[test] fn an_audio_only_job_names_its_encoder() { + for format in [Format::Wav, Format::Flac, Format::Mp3] { + audio_only_job_names_its_encoder(format); + } +} + +fn audio_only_job_names_its_encoder(format: Format) { let settings = ExportSettings { - format: Format::Wav, + format, ..ExportSettings::default() }; assert_eq!( @@ -149,11 +170,11 @@ fn an_audio_only_job_names_its_encoder() { &settings ), None, - "a WAV has no video seat to name" + "an audio-only format has no video seat to name" ); let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - let planned = session.planned_audio(Format::Wav); - let out = out_path("wav", "wav"); + let planned = session.planned_audio(format); + let out = out_path("audio", format.ext()); let handle = session.export_to_with(&out, &settings); let started = Instant::now(); let opened = loop { @@ -169,7 +190,7 @@ fn an_audio_only_job_names_its_encoder() { handle.cancel(); wind_down(&handle); let _ = std::fs::remove_file(&out); - assert_eq!(opened, planned); + assert_eq!(opened, planned, "{}", format.ext()); } /// Waits for a cancelled job to settle, so its `.part` is gone before the test diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index 90a7e37..fe2f5fa 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -363,14 +363,48 @@ fn two_audio_lanes_are_summed() { out_two / out_one ); - // The mp4 path *copies* AAC packets and cannot mix: it refuses by name - // rather than writing a file missing half its sound. + // ...and the mp4 of the same timeline carries that very mix. It used to be + // a refusal by name -- the mp4 path *copies* AAC packets and a mix is not a + // copy -- and a refusal is what a file missing half its sound deserves; + // this decodes both lanes and encodes the sum instead (`export::copy_audio` + // routes to `encode_audio`), which is the same mix the WAV above measured. let out = out_path("mixed", "mp4"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); - let err = wait(&handle, Duration::from_secs(120)).expect_err("mp4 cannot mix"); - println!("mp4 refusal: {err}"); - assert!(err.to_string().contains("2 audio lanes"), "{err}"); - assert!(!out.exists(), "a refused export leaves no file"); + wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes"); + let (audio, chunks) = engine::AudioSession::open(&out) + .expect("reopen the export") + .expect("it has an audio track"); + let coded: Vec = chunks + .into_iter() + .flat_map(|c| c.samples) + .map(|s| f64::from(s) * f64::from(i16::MAX)) + .collect(); + let per = f64::from(audio.sample_rate) / FPS * f64::from(audio.channels); + let window = |from: u32, to: u32| { + let (a, b) = ( + (f64::from(from) * per) as usize, + (f64::from(to) * per) as usize, + ); + let w = &coded[a.min(coded.len())..b.min(coded.len())]; + (w.iter().map(|s| s * s).sum::() / w.len().max(1) as f64).sqrt() + }; + let (coded_over, coded_out) = ( + window(TOP_IN + 5, TOP_OUT - 5), + window(TOP_OUT + 5, TOTAL - 5), + ); + println!("mp4 rms: under A2 {coded_over:.1}, past it {coded_out:.1}"); + // Against the WAV of the same timeline, not against a figure: one lossy + // generation moves the level by a fraction of a dB and nothing here is + // measuring the encoder. + assert!( + (coded_over / over_two - 1.0).abs() < 0.1, + "the mp4's overlap is {coded_over:.1} against the mix's {over_two:.1}" + ); + assert!( + (coded_out / out_two - 1.0).abs() < 0.1, + "past A2 the mp4 is {coded_out:.1} against the mix's {out_two:.1}" + ); + std::fs::remove_file(&out).unwrap(); } /// A project with one lane of each kind is what it always was: the composite of diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs index a0ce632..f60bad0 100644 --- a/crates/engine/tests/speed.rs +++ b/crates/engine/tests/speed.rs @@ -301,25 +301,33 @@ fn a_wav_export_of_a_2x_timeline_matches_the_preview() { std::fs::remove_file(&out).ok(); } -/// The half that refuses: an mp4 *copies* AAC packets and a packet carries no -/// rate, so a speeded clip **on the lane being copied** is refused by name -- -/// never written out at 1.00x under a re-timed picture. Only that lane: the -/// picture honours a rate (below), and AV1 has no audio to copy at all. +/// The other half of the same rule, and it used to be a refusal: an mp4 *copies* +/// AAC packets and a packet carries no rate, so a speeded clip on the lane being +/// copied could only have come out at 1.00x under a re-timed picture. It is +/// decoded, resampled and encoded again now (`export::copy_audio` routes a +/// speeded lane to `encode_audio`), so the file carries the sound that was +/// heard -- measured the way the WAV above is, by where the beep lands. #[test] -fn an_mp4_export_refuses_a_speeded_sound_clip_by_name() { +fn an_mp4_export_resamples_a_speeded_sound_clip() { let (mut project, meta) = sync_project(); project .set_speed(Lane::A1, 0, Speed::from_permille(2000)) .expect("room enough"); - let out = out_path("refuse", "mp4"); + let heard = beep_at(&play(&project)); + let out = out_path("speeded", "mp4"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); - let text = wait(&handle, Duration::from_secs(120)) - .expect_err("an mp4 export cannot carry a rate in a copied packet") - .to_string(); - assert!(text.contains("2.00x"), "{text}"); - assert!(text.contains("00:00"), "{text}"); - assert!(text.contains("WAV or FLAC"), "{text}"); - assert!(!out.exists(), "a refused export writes no file"); + wait(&handle, Duration::from_secs(180)).expect("an mp4 of a speeded sound clip"); + let (audio, chunks) = AudioSession::open(&out) + .expect("reopen the export") + .expect("it has an audio track"); + assert_eq!(audio.sample_rate, RATE); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let in_file = beep_at(&samples); + assert!( + (in_file - heard).abs() <= 1.0 / FPS, + "the beep is at {in_file:.3}s in the file and was at {heard:.3}s in the preview" + ); + std::fs::remove_file(&out).ok(); } /// 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() { std::fs::remove_file(&out).ok(); } -/// AV1 carries no audio at all, so nothing about a rate reaches a packet copy -/// there: it honours a speeded picture with no detaching and no refusal. +/// AV1 honours a speeded picture with no detaching and no refusal -- and its +/// sound, which it now carries, is resampled exactly as the mp4's is. #[test] fn an_av1_export_honours_a_speeded_take_whole() { let (mut project, meta) = sync_project(); @@ -413,10 +421,7 @@ fn an_av1_export_honours_a_speeded_take_whole() { }, ); wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take"); - assert!( - out.exists(), - "AV1 never refuses a rate: it has no audio lane" - ); + assert!(out.exists(), "AV1 never refuses a rate"); assert!( std::fs::metadata(&out).expect("the export").len() > 0, "and it wrote something"