diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 35cc538..b40a03e 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -326,7 +326,7 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 21] = [ +pub const FIXED: [Fixed; 22] = [ // Not a chord at all but a way of pressing one, and the only place the // editor can say so: holding a key that moves a *value* runs it, and // holding anything else still does what one press did. @@ -365,6 +365,11 @@ pub const FIXED: [Fixed; 21] = [ label: "Step through the export quality rows", category: Category::File, }, + Fixed { + chord: "b", + label: "Step through the export sound bitrates", + category: Category::File, + }, Fixed { chord: "d", label: "Choose where the export is written", diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20be25f..68385ad 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -13,7 +13,7 @@ use engine::audio::StreamInfo; use engine::color::ColorParams; use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; -use engine::export::{ExportSettings, Format}; +use engine::export::{AUDIO_KBPS, DEFAULT_AUDIO_KBPS, ExportSettings, Format}; use engine::limiter::Limiter; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; @@ -757,6 +757,12 @@ struct Player { /// first one chose. quality: Quality, custom_mbps: u32, + /// What the *sound* is coded at, in kbps, for every format that encodes it + /// -- the AAC inside a video export as much as an MP3. Kept across closes + /// like the picture's quality, and starts at the figure this program wrote + /// before the row existed ([`engine::export::DEFAULT_AUDIO_KBPS`]), so a + /// user who never touches the row gets the file they always got. + audio_kbps: u32, /// Which file the card will write. Kept across closes like the quality, and /// what [`Player::export_path`](Player) is named after. format: Format, @@ -2214,7 +2220,8 @@ impl Player { let Some(session) = &self.session else { return; }; - let settings = export_settings(self.quality, self.custom_mbps, self.format); + let settings = + export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); if !self.export_open { return; } @@ -3262,6 +3269,29 @@ impl Player { self.quality = Quality::ALL[(at + 1) % Quality::ALL.len()]; } + /// The sound's rate by keyboard, wrapping through the offered ones -- the + /// picture's quality row for the other half of the file. Refused by name + /// where this timeline in this format has no rate to pick, exactly as + /// [`Player::cycle_quality`] is: a key that silently does nothing is the + /// card looking broken. + fn cycle_audio_kbps(&mut self) { + if let Some(why) = self.audio_rate_refusal() { + self.notice = Some(why.into()); + return; + } + self.audio_kbps = next_audio_kbps(self.audio_kbps); + } + + /// Why the sound row is not a choice right now, the engine answering about + /// the very project it would export. No session is the same answer as no + /// sound: there is nothing to write either way. + fn audio_rate_refusal(&self) -> Option<&'static str> { + match &self.session { + Some(session) => session.audio_rate_refusal(self.format), + None => Some("no sound to write"), + } + } + /// The custom bitrate by pointer: the typed digits were the only control in /// this card a mouse could not reach. Clamped to the range the row states /// (the engine's own 1..20 Mbps), and picking the row is part of the step -- @@ -3316,7 +3346,8 @@ impl Player { if self.export.is_some() { return; } - let settings = export_settings(self.quality, self.custom_mbps, self.format); + let settings = + export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); @@ -3521,6 +3552,10 @@ impl Render for Player { this.cycle_container(); } else if key == "q" { this.cycle_quality(); + } else if key == "b" { + // The sound's rate, `q`'s pair for the other half of + // the file. Not a digit: those are the picture's. + this.cycle_audio_kbps(); } else if key == "d" { // The save dialog, which was the one row here a // keyboard could not open. @@ -5103,6 +5138,36 @@ impl Player { } } } + // The other half of the file, and the one this card used to write at a + // fixed rate without saying so: what the *sound* is coded at, for every + // format that codes it -- the AAC inside a video export as much as an + // MP3. One row that cycles, like the container's, rather than four more + // rows above the fold; dimmed with the reason where this timeline has + // no rate to pick, like the quality rows are. + let sound = self.audio_rate_refusal(); + let mut r = entry( + ("sound", 0), + "b", + "Sound".into(), + match sound { + Some(why) => why.into(), + None => format!( + "{} kbps — b for {}", + self.audio_kbps, + next_audio_kbps(self.audio_kbps) + ) + .into(), + }, + false, + sound.is_none(), + ); + if sound.is_none() { + r = r.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.cycle_audio_kbps(); + cx.notify(); + })); + } + list.push(r.into_any_element()); let destination = entry( ("destination", 0), "d", @@ -5147,7 +5212,8 @@ impl Player { .session .as_ref() .map_or("", |s| s.planned_audio(self.format)); - let settings = export_settings(self.quality, self.custom_mbps, self.format); + let settings = + export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); let mb = estimated_mb( settings.bitrate.filter(|_| self.format.has_video()), self.session @@ -7552,7 +7618,7 @@ impl Quality { Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"), other => format!( "{} Mbps", - export_settings(other, 0, Format::Mp4) + export_settings(other, 0, Format::Mp4, DEFAULT_AUDIO_KBPS) .bitrate .unwrap_or_default() / 1_000_000 @@ -7606,12 +7672,7 @@ const FORMATS: [(&[Format], &str, &str, &str); 8] = [ ), (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"), (&[Format::Flac], "f", "FLAC", "lossless — audio only"), - ( - &[Format::Mp3], - "p", - "MP3", - "MPEG-1 Layer III, 256 kbps — audio only", - ), + (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"), (&[], "", "OGG", "no pure-Rust Vorbis or Opus encoder"), (&[], "", "VP9", "AV1 above replaces it"), ]; @@ -7660,6 +7721,14 @@ fn next_container(format: Format) -> Format { .unwrap_or(format) } +/// The next rate the Sound row offers, wrapping -- what its key does, and what +/// the row itself names so the stroke is never a guess. [`next_container`]'s +/// shape, for the same reason: one place decides what "next" means. +fn next_audio_kbps(kbps: u32) -> u32 { + let at = AUDIO_KBPS.iter().position(|&k| k == kbps).unwrap_or(0); + AUDIO_KBPS[(at + 1) % AUDIO_KBPS.len()] +} + /// Why the quality rows say nothing about this format, or `None` where they /// decide the picture. Only a picture encoder is given a bitrate here: the two /// lossless audio formats have none to give and MP3 is written at one fixed @@ -7667,7 +7736,7 @@ fn next_container(format: Format) -> Format { fn bitrate_refusal(format: Format) -> Option<&'static str> { match format { Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"), - Format::Mp3 => Some("MP3 is written at a fixed 256 kbps"), + Format::Mp3 => Some("sound only — its rate is the Sound row"), _ => None, } } @@ -7871,7 +7940,7 @@ fn format_line(format: Format) -> &'static str { // only field on this line that says nothing. Format::Wav => "16-bit PCM · WAV", Format::Flac => "FLAC · lossless", - Format::Mp3 => "MP3 · 256 kbps", + Format::Mp3 => "MP3 · lossy", } } @@ -7902,9 +7971,18 @@ fn retarget(path: &std::path::Path, format: Format) -> PathBuf { /// /// The bitrate travels even for an audio format, where the engine ignores it: /// one settings value, and a row the card has dimmed cannot have been changed. -fn export_settings(quality: Quality, custom_mbps: u32, format: Format) -> ExportSettings { +fn export_settings( + quality: Quality, + custom_mbps: u32, + format: Format, + audio_kbps: u32, +) -> ExportSettings { ExportSettings { format, + // Always travels, exactly as the picture's bitrate does above: the + // engine ignores it where nothing encodes the sound, and a row the card + // has dimmed cannot have been changed. + audio_kbps: Some(audio_kbps), bitrate: match quality { Quality::Auto => None, Quality::Low => Some(2_000_000), @@ -8845,22 +8923,23 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, - EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, - EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, FORMATS, Format, HEADER_GAP, - HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, - KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, - LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, - PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, - WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export, - clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y, - estimated_mb, export_path, export_settings, format_key, format_line, format_refusal, - fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, - keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h, - project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped, - source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, unseen_paths, - unseen_sources, whole_take, width_frac, window_title, + ACCENT, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, + DEFAULT_AUDIO_KBPS, EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, + EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, + EXPORT_W, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, + HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, + LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, + MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, + VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, bitrate_refusal, + can_add, cancels_export, clipboard_after_remove, color_snap, containers, envelope, + eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, + format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, + is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, next_audio_kbps, + next_container, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, + scrub_due, show_label, silence_rate, snapped, source_tint, span_partner, speed_at, + summary_head, summary_tail, timecode, unseen_paths, unseen_sources, whole_take, width_frac, + window_title, }; use super::{ LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, @@ -10771,34 +10850,40 @@ mod tests { // Auto is the one row that says nothing: the exporter derives it, and // a number typed against the custom row must not leak into it. let mp4 = Format::Mp4; - assert_eq!(export_settings(Quality::Auto, 7, mp4).bitrate, None); assert_eq!( - export_settings(Quality::Low, 0, mp4).bitrate, + export_settings(Quality::Auto, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, + None + ); + assert_eq!( + export_settings(Quality::Low, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, Some(2_000_000) ); assert_eq!( - export_settings(Quality::Medium, 0, mp4).bitrate, + export_settings(Quality::Medium, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, Some(6_000_000) ); assert_eq!( - export_settings(Quality::High, 0, mp4).bitrate, + export_settings(Quality::High, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, Some(12_000_000) ); // Megabits as typed, and as the row says it back. assert_eq!( - export_settings(Quality::Custom, 7, mp4).bitrate, + export_settings(Quality::Custom, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, Some(7_000_000) ); assert_eq!(Quality::Low.detail(0), "2 Mbps"); // The picked format travels, or the card's rows would be a picture of a // choice the engine never hears about. for format in [Format::Mp4, Format::Wav, Format::Flac] { - assert_eq!(export_settings(Quality::Auto, 0, format).format, format); + assert_eq!( + export_settings(Quality::Auto, 0, format, DEFAULT_AUDIO_KBPS).format, + format + ); } // Every fixed row sits inside the engine's clamp (export.rs:290), so no // row can promise a bitrate the exporter silently changes. for quality in Quality::ALL { - let settings = export_settings(quality, 7, mp4); + let settings = export_settings(quality, 7, mp4, DEFAULT_AUDIO_KBPS); if let Some(bitrate) = settings.bitrate { assert!( (1_000_000..=20_000_000).contains(&bitrate), @@ -10810,6 +10895,40 @@ mod tests { } } + /// The Sound row: what it offers, and that the pick travels to the engine + /// for a *video* export as much as for an MP3 -- both files carry sound, so + /// a row that only reached the audio formats would be half a control. + #[test] + fn the_sound_row_carries_its_rate_into_both_kinds_of_file() { + // Sorted and unique, so a row that says "b for the next one" is stepping + // up and not shuffling. + assert!(AUDIO_KBPS.windows(2).all(|w| w[0] < w[1])); + // The untouched figure is one of the offered rows, or the first press of + // `b` would jump somewhere nobody chose. + assert!(AUDIO_KBPS.contains(&DEFAULT_AUDIO_KBPS)); + // ...and it is what this program wrote before the row existed: the + // export of a user who never opens it must not change under them. + assert_eq!(DEFAULT_AUDIO_KBPS, 256); + for format in [Format::Mp4, Format::Av1, Format::Hevc, Format::Mp3] { + for kbps in AUDIO_KBPS { + assert_eq!( + export_settings(Quality::Auto, 0, format, kbps).audio_kbps, + Some(kbps), + "{format:?} at {kbps} kbps" + ); + } + } + // The wrap the row's key does, which is the row's own step function. + assert_eq!( + next_audio_kbps(AUDIO_KBPS[AUDIO_KBPS.len() - 1]), + AUDIO_KBPS[0] + ); + assert_eq!(next_audio_kbps(DEFAULT_AUDIO_KBPS), 320); + // A rate no list holds (a stale one, say) lands back on the first row + // rather than nowhere. + assert_eq!(next_audio_kbps(7), AUDIO_KBPS[1]); + } + #[test] fn a_typed_bitrate_stops_at_two_digits() { assert_eq!(push_digit(0, 8), 8); @@ -11187,7 +11306,14 @@ mod tests { ); } assert!(bitrate_refusal(Format::Wav).unwrap().contains("lossless")); - assert!(bitrate_refusal(Format::Mp3).unwrap().contains("256 kbps")); + // MP3 has a rate and it is the *Sound* row's: the quality rows are the + // picture's, and this refusal used to claim a fixed 256 kbps that the + // Sound row can now change under it. + assert!(bitrate_refusal(Format::Mp3).unwrap().contains("Sound row")); + assert!( + !format_line(Format::Mp3).contains("256"), + "the summary states a rate the Sound row can change under it" + ); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), @@ -11773,6 +11899,8 @@ fn main() { // bitrate the picture asks for. quality: Quality::Auto, custom_mbps: 0, + // ...and the rate the sound has always been written at. + audio_kbps: DEFAULT_AUDIO_KBPS, // Picture and sound, which is what an export was before // there was anything to pick. format: Format::default(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 08aa301..c7853f7 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -76,6 +76,21 @@ const BITS_PER_PIXEL: f64 = 0.1; const MIN_BITRATE: u64 = 1_000_000; const MAX_BITRATE: u64 = 20_000_000; +/// The rates the sound may be coded at, smallest first -- what a front-end +/// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of +/// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it +/// was given rather than the nearest one `rusty_mp3` snaps to. +pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320]; + +/// What the sound is coded at when nobody picked: the rate this project wrote +/// before the choice existed. 256 and not the encoders' own 128, because an +/// export is a master a person edits from again and this is a second lossy +/// generation over sources that may already have been one -- measured on the +/// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against +/// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone +/// is counting. +pub const DEFAULT_AUDIO_KBPS: u32 = 256; + /// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline /// on a build with no assembly, which is what this one is. const AV1_SPEED: u8 = 10; @@ -137,7 +152,8 @@ pub enum Format { Wav, /// The audio lanes alone, losslessly compressed. Flac, - /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`). + /// The audio lanes alone, MPEG-1 Layer III CBR (`rusty_mp3`) at the rate + /// [`ExportSettings::audio_kbps`] asks for. Mp3, } @@ -205,6 +221,13 @@ pub struct ExportSettings { /// The file to write. Defaults to [`Format::Mp4`], which is what every /// caller wrote before there was a choice. pub format: Format, + /// What the *sound* is coded at, in kbps, wherever an encoder writes it -- + /// the AAC of a video export as much as an MP3. `None` is + /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there + /// was a choice, so a settings value nobody touched writes the same bytes + /// it used to. Means nothing to WAV and FLAC, which code no rate, and + /// nothing to a *copied* AAC track, which carries its source's. + pub audio_kbps: Option, } struct Shared { @@ -313,7 +336,7 @@ pub fn start( ) .into()), format if format.has_video() => run(&project, &meta, &part, &worker, &settings), - format => run_audio(&project, &meta, &part, &worker, format), + _ => run_audio(&project, &meta, &part, &worker, &settings), }; let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); if result.is_err() { @@ -377,6 +400,16 @@ fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)) } +/// The rate the sound codes at: the caller's pick clamped into the offered +/// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused, +/// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and +/// not a file worth failing. +fn audio_kbps_of(settings: &ExportSettings) -> u32 { + settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| { + k.clamp(AUDIO_KBPS[0], AUDIO_KBPS[3]) + }) +} + /// The hardware seat for these settings, opened exactly as the export opens it /// -- the same pins, the same AV1 opt-in, the same dimensions a driver may /// refuse -- or `None` where the software encoder takes the file. The single @@ -473,6 +506,25 @@ pub fn planned_audio(project: &Project, format: Format) -> &'static str { audio_label(project, format, has_sound(project), None) } +/// Why the sound's rate is nothing this timeline can be asked about in this +/// format, or `None` where it is a real choice: there is no sound to write, the +/// format codes the samples themselves, or the packets are the source's own and +/// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a +/// prediction in the same way -- a copy that turns out impossible (a source no +/// mp4 sample table holds) falls through to [`encode_audio`], which codes at +/// [`ExportSettings::audio_kbps`] like every other encode. So the value travels +/// even where this refuses; what it cannot do is silently write a rate nobody +/// picked. +pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static str> { + match format { + _ if !has_sound(project) => Some("no sound to write"), + Format::Wav | Format::Flac => Some("lossless — the samples themselves, at no rate"), + Format::Mp3 => None, + _ if forces_encode(project) => None, + _ => Some("the source's own packets are copied — at the rate they hold"), + } +} + /// What [`start`] would encode the picture with, probed the way the export /// probes it -- the very encoder is opened and closed again -- so this is a /// measurement and not a promise. `None` for a format that carries no picture. @@ -517,7 +569,11 @@ pub(crate) struct ExportAudio { /// 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. -fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { +fn copy_audio( + project: &Project, + meta: &VideoMeta, + kbps: u32, +) -> 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 @@ -541,7 +597,7 @@ fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result crate::Result crate::Result encode_audio(project, meta), + Err(_) => encode_audio(project, meta, kbps), } } @@ -616,7 +672,11 @@ fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result crate::Result> { +fn encode_audio( + project: &Project, + meta: &VideoMeta, + kbps: u32, +) -> 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); @@ -654,14 +714,10 @@ fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result crate::Result<()> { + let format = settings.format; let sources = project.audio_sources(); let segs = project.audio_segments_from(0, meta.frame_rate); // The equalizers with them, so what is written is what is heard down to the @@ -1011,7 +1068,7 @@ fn run_audio( match format { Format::Wav => write_wav(out, &samples, &audio)?, Format::Flac => write_flac(out, &samples, &audio)?, - Format::Mp3 => write_mp3(out, &samples, &audio)?, + Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?, _ => unreachable!("the picture formats are `run`"), } shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); @@ -1043,18 +1100,17 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<() /// 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. +/// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every +/// offered rate is already a legal Layer III value, so the encoder's snap is a +/// backstop and not a silent substitution; 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<()> { +/// ponytail: CBR only -- the card offers rates and not a quality index. Upgrade +/// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own. +fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> { let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig { - bitrate_kbps: 256, + bitrate_kbps: kbps, vbr_quality: None, }); // The samples are the 16-bit ones a WAV of this timeline holds, so the two diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 12b149d..d7dc78e 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -741,6 +741,13 @@ impl PlaybackSession { crate::export::planned_audio(&self.project, format) } + /// Why the sound's rate is not a choice for this timeline in this format -- + /// [`crate::export::audio_rate_refusal`], asked of the project a front-end + /// is holding, and pure for the same reason. + pub fn audio_rate_refusal(&self, format: crate::export::Format) -> Option<&'static str> { + crate::export::audio_rate_refusal(&self.project, format) + } + /// Why this session plays silent although the file has sound -- an audio /// track in a codec we cannot decode, or one the decoder refused. `None` /// when there is audio, and for a file that never had any. A front-end diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 550a80d..1f62bbe 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -11,9 +11,13 @@ //! No picture is decoded anywhere here, so nothing needs the plugin and the //! whole file runs on any machine. +use std::fs::File; +use std::io::BufReader; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; +use mp4::{MediaType, Mp4Reader}; + use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; @@ -511,6 +515,164 @@ fn a_cancelled_audio_export_leaves_no_file() { assert!(!part_path(&out).exists(), "no half-written .part either"); } +/// The rate an MP3 file *declares*, read out of its own frame headers -- the +/// only place the claim can be checked, since a caller's kbps is a request until +/// the bytes say so. MPEG-1 Layer III, whose bitrate index is the high nibble of +/// the third header byte. +fn mp3_declared_kbps(path: &Path) -> u32 { + const KBPS: [u32; 16] = [ + 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0, + ]; + let bytes = std::fs::read(path).expect("read the mp3 back"); + let at = bytes + .windows(4) + .position(|w| w[0] == 0xFF && w[1] & 0xE0 == 0xE0) + .expect("an MPEG frame sync"); + let header = &bytes[at..at + 4]; + assert_eq!(header[1] >> 3 & 0x3, 0b11, "MPEG-1"); + assert_eq!(header[1] >> 1 & 0x3, 0b01, "Layer III"); + let kbps = KBPS[usize::from(header[2] >> 4)]; + assert!(kbps > 0, "a free-format or invalid bitrate index"); + kbps +} + +/// What an mp4's AAC track is really coded at: its sample bytes over the time +/// they play, in kbps. Every AAC-LC packet is 1024 frames per channel, so the +/// duration comes out of the packet count and needs no timescale of the file's +/// own -- and the bytes are what a player downloads, which is what a bitrate is. +fn mp4_aac_kbps(path: &Path, sample_rate: f64) -> f64 { + let file = File::open(path).expect("reopen the mp4"); + let size = file.metadata().unwrap().len(); + let mut reader = Mp4Reader::read_header(BufReader::new(file), size).expect("mp4 header"); + let track = reader + .tracks() + .values() + .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) + .expect("an AAC track") + .track_id(); + let count = reader.sample_count(track).expect("sample count"); + let mut bytes = 0usize; + for id in 1..=count { + bytes += reader + .read_sample(track, id) + .expect("read a sample") + .expect("a sample at every id") + .bytes + .len(); + } + let seconds = f64::from(count) * 1024.0 / sample_rate; + bytes as f64 * 8.0 / seconds / 1000.0 +} + +/// The sound's rate is the caller's, in both kinds of file -- and the file +/// nobody asked a rate of is the one this program always wrote. +/// +/// MP3 declares its rate in every frame header, so that half is exact. The AAC +/// half is measured off the mp4's own sample table: a rate control lands *near* +/// its target rather than on it, so the tolerance is a fifth, which is far +/// tighter than the gap between two offered rates. +#[test] +fn the_sound_is_written_at_the_rate_that_was_asked_for() { + // Untouched settings first: this is the byte-behaviour a user who never + // opens the row is entitled to keep. + for (kbps, want) in [ + (None, engine::export::DEFAULT_AUDIO_KBPS), + (Some(128), 128), + (Some(320), 320), + ] { + let out = out_path(&format!("mp3_{}", want), "mp3"); + let handle = engine::export::start( + mixed_project(), + meta(), + &out, + &ExportSettings { + format: Format::Mp3, + audio_kbps: kbps, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(120)).expect("mp3 export"); + let got = mp3_declared_kbps(&out); + println!("mp3 asked {kbps:?}, header says {got} kbps"); + assert_eq!(got, want, "the mp3 frames declare the rate that was picked"); + // ...and it is still the edit, not just bytes at the right rate. + let (meta, samples) = decode(&out); + let channels = usize::from(meta.channels); + assert!(rms(&samples, channels, 0.05, 0.95) > 0.01, "audible"); + std::fs::remove_file(&out).unwrap(); + } + + // The same choice inside a video export, where the sound is AAC: a song + // under a still, which no mp4 sample table can be copied from, so the + // encoder really runs. + let project = Project::from_parts( + vec![ + Source::new(asset("test_still.png"), 0), + Source::new(asset("test_tone.mp3"), 0), + ], + vec![ + ( + LaneKind::Video, + vec![Clip { + start: 0, + in_frame: 0, + out_frame: 60, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }], + ), + ( + LaneKind::Audio, + vec![Clip { + start: 0, + in_frame: 0, + out_frame: 60, + source: 1, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }], + ), + ], + Vec::new(), + Vec::new(), + ) + .expect("a still under a song"); + let meta = engine::VideoMeta { + width: 640, + height: 360, + frame_rate: 30.0, + frame_count: 60, + codec: engine::Codec::H264, + }; + for want in [128u32, 320] { + let out = out_path(&format!("mp4_aac_{want}"), "mp4"); + let handle = engine::export::start( + project.clone(), + meta, + &out, + &ExportSettings { + audio_kbps: Some(want), + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); + let got = mp4_aac_kbps(&out, f64::from(RATE)); + println!("mp4 asked {want} kbps, the track measures {got:.1}"); + assert!( + (got - f64::from(want)).abs() < f64::from(want) / 5.0, + "{got:.1} kbps for a {want} kbps request" + ); + std::fs::remove_file(&out).unwrap(); + } +} + /// A silent timeline cannot become an audio file, and says so rather than /// writing zero samples that a user would take for a broken microphone. #[test]