diff --git a/Cargo.lock b/Cargo.lock index 113256c..28ddcf2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -716,6 +716,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "built" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b" + [[package]] name = "built" version = "0.8.1" @@ -1238,6 +1244,21 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + [[package]] name = "crc32fast" version = "1.5.0" @@ -1609,6 +1630,8 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" name = "engine" version = "0.1.0" dependencies = [ + "flacenc", + "hound", "libloading", "mp4", "rusty_h264", @@ -1828,6 +1851,21 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" +[[package]] +name = "flacenc" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74c892c2b5fa08f967e8b5ad29121570b4762202f2402033ce08479ec65eccd0" +dependencies = [ + "built 0.7.7", + "crc", + "heapless", + "md-5", + "num-traits", + "rustversion", + "seq-macro", +] + [[package]] name = "flate2" version = "1.1.9" @@ -2559,6 +2597,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -2580,6 +2627,16 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.4.1" @@ -2648,6 +2705,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "hound" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" + [[package]] name = "http" version = "1.5.0" @@ -4420,7 +4483,7 @@ dependencies = [ "av-scenechange", "av1-grain", "bitstream-io", - "built", + "built 0.8.1", "cfg-if", "interpolate_name", "itertools 0.14.0", @@ -5002,6 +5065,12 @@ version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index c3cfea5..9bcb314 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -179,7 +179,7 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 3] = [ +pub const FIXED: [Fixed; 5] = [ Fixed { chord: "esc", label: "Close this card or clip menu, or cancel a capture", @@ -190,6 +190,16 @@ pub const FIXED: [Fixed; 3] = [ label: "Type a custom export bitrate", category: Category::File, }, + Fixed { + chord: "m / w / f", + label: "Pick the export format: MP4, WAV or FLAC", + category: Category::File, + }, + Fixed { + chord: "enter", + label: "Start the export the card is set to", + category: Category::File, + }, Fixed { chord: "backspace", label: "Erase a bitrate digit", diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index eda2b14..fd04cb5 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10,14 +10,14 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use engine::audio::StreamInfo; -use engine::export::ExportSettings; +use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source}; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ - AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent, + AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, - RenderImage, SharedString, Size, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, - div, img, point, prelude::*, px, relative, rgb, rgba, size, + RenderImage, SharedString, Size, Stateful, TitlebarOptions, Window, WindowBounds, WindowOptions, + canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, }; /// Editor chrome: three grays and one accent, all darker than the picture so the @@ -99,6 +99,10 @@ const KEYS_ROW_H: f32 = HIT_MIN; /// keeps the card inside the smallest window no matter how many actions the /// editor grows -- ten rows fit here, and the eleventh is a scroll away. const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; +/// The same for the export card, which carries a fixed-format line and a button +/// under its list and so has less room: destination, six formats and five +/// qualities are twelve rows, eight of them on screen. +const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; /// The menu a right-click on a clip opens: wide enough for the longest label /// beside the stroke that does the same thing, with the click targets `HIT_MIN` /// binds like every other list here. @@ -310,6 +314,9 @@ struct Player { /// first one chose. quality: Quality, custom_mbps: u32, + /// Which file the card will write. Kept across closes like the quality, and + /// what [`Player::export_path`](Player) is named after. + format: Format, /// The action whose row is waiting for a stroke. The next key that is /// neither escape nor a lone modifier becomes the whole of what reaches it. rebinding: Option, @@ -762,7 +769,9 @@ impl Player { // A fresh session comes up at full volume; the player's own // setting outlives the file, so it is pushed at every new one. self.apply_volume(); - self.export_path = export_path(path); + // Beside the new file, but still the format the card is set to: + // opening another clip is not a change of mind about that. + self.export_path = retarget(&export_path(path), self.format); self.project_path = project_path(path); self.name = file_name(path).into(); self.reset_after_reseek(); @@ -815,7 +824,7 @@ impl Player { let silent = audio_notice(&session); // A project is named after itself but still exports beside its // media: that is the only place an export has ever landed. - self.export_path = export_path(&session.sources()[0].path); + self.export_path = retarget(&export_path(&session.sources()[0].path), self.format); self.session = Some(session); self.apply_volume(); self.project_path = path.to_path_buf(); @@ -985,6 +994,14 @@ impl Player { cx.notify(); } + /// A format row was clicked. The destination follows it at once -- a WAV + /// written to a path ending in `.mp4` is a file every player will lie + /// about -- keeping whatever stem the save dialog last left there. + fn set_format(&mut self, format: Format) { + self.format = format; + self.export_path = retarget(&self.export_path, format); + } + /// The card's Destination row: the desktop's save dialog, on a background /// thread like the import chooser -- the user may sit in it and the window /// behind must not freeze. No chooser at all leaves the default path, which @@ -1003,7 +1020,9 @@ impl Player { return; } match picked { - Ok(Some(path)) => this.export_path = path, + // The stem is the user's, the extension is the format's: a + // FLAC named `.mp4` is a file every player lies about. + Ok(Some(path)) => this.export_path = retarget(&path, this.format), // Cancelled: the default stands, as it did before. Ok(None) => {} Err(text) => { @@ -1028,7 +1047,7 @@ impl Player { if self.export.is_some() { return; } - let settings = export_settings(self.quality, self.custom_mbps); + let settings = export_settings(self.quality, self.custom_mbps, self.format); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); @@ -1190,6 +1209,18 @@ impl Render for Player { if this.export_open { if key == ESCAPE { this.export_open = false; + } else if key == "enter" { + // The card's own button, by keyboard: the one thing in + // it that writes a file must not be pointer-only either. + this.start_export(cx); + } else if let Some(format) = format_key(key) { + // The format rows by their initial, so the card can be + // driven without a mouse -- the same card-local input + // the typed bitrate is, and for the same reason: a + // choice reachable only by pointer is not reachable by + // everyone. Not a keymap binding: it means nothing + // outside this card, exactly like the digits. + this.set_format(format); } else if let Ok(digit) = key.parse::() { this.custom_mbps = push_digit(this.custom_mbps, digit); this.quality = Quality::Custom; @@ -1987,19 +2018,52 @@ impl Player { .gap(px(12.)) .px(px(6.)) .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) }; + // A row that cannot be picked is dimmed and takes no click, exactly as + // an inapplicable item in the clip menu is: it still says its piece. + let live = |d: Stateful
, enabled: bool| { + d.when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))) + }) + }; + // The formats first: the quality rows below are *video* bitrate, so + // which file is being written decides whether they mean anything. + let formats: Vec<_> = FORMATS + .into_iter() + .enumerate() + .map(|(i, (format, label, detail))| { + let picked = format == Some(self.format); + live(row(("format", i)), format.is_some()) + .when(picked, |d| d.bg(rgb(SELECTED))) + .when_some(format, |d, format| { + d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_format(format); + cx.notify(); + })) + }) + .child(label) + .child( + div() + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(detail), + ) + }) + .collect(); + let video = self.format.has_video(); let rows: Vec<_> = Quality::ALL .into_iter() .enumerate() .map(|(i, quality)| { - row(("quality", i)) - .when(self.quality == quality, |d| d.bg(rgb(SELECTED))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.quality = quality; - cx.notify(); - })) + live(row(("quality", i)), video) + .when(video && self.quality == quality, |d| d.bg(rgb(SELECTED))) + .when(video, |d| { + d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.quality = quality; + cx.notify(); + })) + }) .child(quality.label()) .child( div() @@ -2040,34 +2104,47 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "pick a quality, then Export — esc closes".into() + "pick a format (m/w/f), then Export — esc closes".into() })), ) + // Capped and scrolling like the keybindings list: the + // destination, six formats and five qualities are more + // rows than a 360 px window has room for, and it is the + // list that scrolls, never the card that grows. .child( - row(("destination", 0)) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.pick_destination(cx) - })) - .child("Destination") + div() + .id("export-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(EXPORT_ROWS_H)) + .overflow_y_scroll() .child( - div() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(file_name(&self.export_path)), - ), + live(row(("destination", 0)), true) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.pick_destination(cx) + })) + .child("Destination") + .child( + div() + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(file_name(&self.export_path)), + ), + ) + .children(formats) + .children(rows), ) - .children(rows) - // Not offered, so said: these are what this program can - // write, and a menu of one is a lie about the other - // entries. `moov` last is the muxer's own shape -- the - // file is playable only once it is finished. + // What the picked row really writes. `moov` last is the + // muxer's own shape -- an mp4 is playable only once it + // is finished. .child( div() .flex_none() .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child("H.264 · MP4 · moov at end"), + .child(format_line(self.format)), ) .child( div() @@ -2932,19 +3009,74 @@ impl Quality { Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"), other => format!( "{} Mbps", - export_settings(other, 0).bitrate.unwrap_or_default() / 1_000_000 + export_settings(other, 0, Format::Mp4) + .bitrate + .unwrap_or_default() + / 1_000_000 ), } } } +/// 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. +/// +/// `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. +const FORMATS: [(Option, &str, &str); 6] = [ + (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), + (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", "no pure-Rust AAC encoder"), +]; + +/// 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. +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) +} + +/// The line under the rows: what the picked format really writes, in the terms +/// a file is judged by afterwards. +fn format_line(format: Format) -> &'static str { + match format { + Format::Mp4 => "H.264 · MP4 · moov at end", + Format::Wav => "16-bit PCM · WAV · timeline audio only", + Format::Flac => "FLAC · lossless · timeline audio only", + } +} + +/// The destination under a format: `take.export.mp4` becomes `take.export.wav`. +/// The stem is untouched, so a name typed into the save dialog survives a +/// change of mind about the format -- only the extension is the format's to say. +fn retarget(path: &std::path::Path, format: Format) -> PathBuf { + let mut path = path.to_path_buf(); + path.set_extension(format.ext()); + path +} + /// The card's rows as the engine takes them. `Auto` leaves the bitrate to the /// exporter, which derives it from the picture; the fixed rows are figures that /// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the /// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this /// must not clamp it a second time and disagree about where the edge is. -fn export_settings(quality: Quality, custom_mbps: u32) -> ExportSettings { +/// +/// 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 { ExportSettings { + format, bitrate: match quality { Quality::Auto => None, Quality::Low => Some(2_000_000), @@ -3297,14 +3429,15 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, - KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, - Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, - SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, - applicable, can_add, cancels_export, envelope, export_path, export_settings, frac_along, - frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise, - project_path, push_digit, scrub_due, show_label, source_frames, source_tint, start_frac, - timecode, unseen_paths, unseen_sources, width_frac, window_title, + ACCENT, CONTROL_H, Clip, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, + INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, + LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, + RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, + WAVE_BPS, WAVE_COL, Wave, applicable, can_add, cancels_export, envelope, export_path, + export_settings, format_line, frac_along, frame_at, is_bare_modifier, is_project, keymap, + lane_clips, marked, menu_at, normalise, project_path, push_digit, retarget, scrub_due, + show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, + width_frac, window_title, }; use super::{file_name, library_rows}; use engine::PlaybackSession; @@ -4012,17 +4145,32 @@ mod tests { fn a_quality_row_is_the_bitrate_it_promises() { // 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. - assert_eq!(export_settings(Quality::Auto, 7).bitrate, None); - assert_eq!(export_settings(Quality::Low, 0).bitrate, Some(2_000_000)); - assert_eq!(export_settings(Quality::Medium, 0).bitrate, Some(6_000_000)); - assert_eq!(export_settings(Quality::High, 0).bitrate, Some(12_000_000)); + let mp4 = Format::Mp4; + assert_eq!(export_settings(Quality::Auto, 7, mp4).bitrate, None); + assert_eq!(export_settings(Quality::Low, 0, mp4).bitrate, Some(2_000_000)); + assert_eq!( + export_settings(Quality::Medium, 0, mp4).bitrate, + Some(6_000_000) + ); + assert_eq!( + export_settings(Quality::High, 0, mp4).bitrate, + Some(12_000_000) + ); // Megabits as typed, and as the row says it back. - assert_eq!(export_settings(Quality::Custom, 7).bitrate, Some(7_000_000)); + assert_eq!( + export_settings(Quality::Custom, 7, mp4).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); + } // 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); + let settings = export_settings(quality, 7, mp4); if let Some(bitrate) = settings.bitrate { assert!( (1_000_000..=20_000_000).contains(&bitrate), @@ -4049,24 +4197,61 @@ mod tests { #[test] fn the_export_card_fits_the_smallest_window() { - // Same 640x360 floor the keybindings card is measured against: a - // destination row, one row per quality, the fixed-format line and the - // confirm button, under a title and a status line. - let rows = Quality::ALL.len() as f32 + 1.; + // Same 640x360 floor the keybindings card is measured against: the + // capped row list, the fixed-format line and the confirm button, under + // a title and a status line. let title = 17.; let status = 28.; let fixed = 17.; - let gaps = (rows + 3.) * 2.; + let gaps = 4. * 2.; let padding = 24.; assert!( - title + status + rows * KEYS_ROW_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., + title + status + EXPORT_ROWS_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., "card too tall" ); + // The cap is only honest if enough of the list is on screen to read as + // one -- the destination and the first formats, not a slot. + assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 6.); // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's. assert!(KEYS_ROW_H >= HIT_MIN); assert!(CONTROL_H >= HIT_MIN); } + #[test] + fn every_format_row_is_offered_or_says_why_not() { + // The three this program can write are rows that pick, each named after + // its own extension so a destination can never disagree with its bytes. + let offered: Vec = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); + assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]); + for (format, label, _) in FORMATS { + match format { + 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 { + assert!(!detail.is_empty(), "{label} says nothing"); + // Only mp4 carries the picture, so only mp4 leaves the bitrate rows + // live -- the card dims them off exactly this. + assert_eq!( + format.is_some_and(Format::has_video), + format == Some(Format::Mp4) + ); + } + // The destination follows the format and keeps the stem, mp4 included. + assert_eq!( + retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), + std::path::Path::new("/a/take.export.wav") + ); + assert_eq!( + retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4), + std::path::Path::new("/a/take.export.mp4") + ); + assert!(format_line(Format::Flac).contains("audio only")); + } + #[test] fn nothing_clickable_is_smaller_than_the_wcag_minimum() { // Every hit target in the panel, including the scrub strip -- whose bar @@ -4411,6 +4596,9 @@ fn main() { // bitrate the picture asks for. quality: Quality::Auto, custom_mbps: 0, + // Picture and sound, which is what an export was before + // there was anything to pick. + format: Format::default(), rebinding: None, notice: notice.clone().map(SharedString::from), // Nothing pushed yet, and never a real title: the first diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 220a17b..05c63e7 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -5,6 +5,12 @@ edition.workspace = true # No UI dependency here, ever: the engine must stay reusable across front-ends. [dependencies] +# The two audio-only export formats. Pure Rust, both of them, which is the whole +# reason they are the two: `hound` writes the RIFF header and the PCM, `flacenc` +# encodes FLAC. No default features on flacenc -- its `par` (rayon), `log` and +# `serde` are for its own command-line front-end, and this needs none of them. +hound = "3.5.1" +flacenc = { version = "0.5.1", default-features = false } libloading = "0.8" mp4 = "0.14" rusty_h264 = { version = "0.8", default-features = false } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index d9a58d3..117a287 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,9 +1,13 @@ -//! Export: the edit list rendered back out as one mp4. +//! Export: the edit list rendered back out as one mp4 — or, picture left +//! behind, as one WAV or FLAC 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, because there is no -//! pure-Rust AAC encoder to re-encode with. The worker owns everything: the -//! caller gets an [`ExportHandle`] and polls it from its render loop. +//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such +//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so +//! those are *decoded* out of the timeline instead of copied. The worker owns +//! everything: the caller gets an [`ExportHandle`] and polls it from its render +//! loop. //! //! 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 @@ -20,7 +24,10 @@ use std::thread; use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; -use crate::audio::AudioSession; +use flacenc::component::BitRepr; +use flacenc::error::Verify; + +use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; @@ -36,18 +43,55 @@ const BITS_PER_PIXEL: f64 = 0.1; const MIN_BITRATE: u64 = 1_000_000; const MAX_BITRATE: u64 = 20_000_000; -/// What the caller gets to decide about the output. The codec and container are -/// not among it: H.264 in mp4 is the only pair with both an encoder and a -/// decoder under this project's no-install rule, so offering a choice would be -/// offering files we cannot read back. +/// What an export writes. Three, not more: H.264-in-mp4 is the only *video* +/// pair with both an encoder and a decoder under this project's no-install +/// rule, and WAV and FLAC are the only 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, Opus and AAC have none. A +/// front-end says so rather than hiding the rows. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Format { + /// Picture and sound: video re-encoded, AAC copied. + #[default] + Mp4, + /// The audio lane alone, 16-bit PCM. + Wav, + /// The audio lane alone, losslessly compressed. + Flac, +} + +impl Format { + /// The extension a file of this format is named with -- a front-end builds + /// 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::Wav => "wav", + Self::Flac => "flac", + } + } + + /// Whether this format carries the picture. The bitrate settings are video + /// settings and mean nothing to the other two. + pub fn has_video(self) -> bool { + matches!(self, Self::Mp4) + } +} + +/// What the caller gets to decide about the output. The codec is not among it: +/// [`Format`] names a container *and* what goes in it, because every pair we +/// can write is a pair we can also read back. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct ExportSettings { /// Bits per second, clamped to the same sane range the automatic value uses. - /// `None` picks it from the picture size and frame rate. + /// `None` picks it from the picture size and frame rate. Video only. pub bitrate: Option, /// Skip the hardware encoder even where it is available -- an escape hatch /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin. pub force_sw: bool, + /// The file to write. Defaults to [`Format::Mp4`], which is what every + /// caller wrote before there was a choice. + pub format: Format, } struct Shared { @@ -118,8 +162,11 @@ pub fn start( // The rename is the last step and the only one that publishes a file // under the name the caller asked for; it stays on the same directory, // so it is atomic. - let result = run(&project, &meta, &part, &worker, &settings) - .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); + let written = match settings.format { + Format::Mp4 => 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)); if result.is_err() { // The muxer -- and with it the file handle -- died with `run`. let _ = std::fs::remove_file(&part); @@ -232,6 +279,127 @@ fn run( Ok(()) } +/// The audio lane alone, as a WAV or a FLAC. +/// +/// Nothing here re-derives the edit: the play list is +/// [`Project::segments_from`] and it is handed to the very +/// [`AudioSession::open_multi_streams`] playback feeds from, so what is written +/// is what was heard -- gaps included, which arrive as real silence from that +/// choke point rather than as a hole this would have to invent. +/// +/// The length is the *timeline's*: each segment resolves its window to whole +/// samples on its own, so the sum can miss the timeline by a sample or two, and +/// a source that runs out early would leave the file short. Both are settled by +/// one `resize` at the end -- padding with silence, trimming what overshot -- +/// so an exported file is exactly as long as what was edited. +fn run_audio( + project: &Project, + meta: &VideoMeta, + out: &Path, + shared: &Shared, + format: Format, +) -> crate::Result<()> { + let sources = project.audio_sources(); + let segs = project.segments_from(0, meta.frame_rate); + let Some((audio, chunks)) = AudioSession::open_multi_streams(&sources, &segs)? else { + return Err("this timeline has no audio to export".into()); + }; + let channels = usize::from(audio.channels); + let frames = (f64::from(project.timeline_frames()) / meta.frame_rate + * f64::from(audio.sample_rate)) + .round() as u64; + let total = frames as usize * channels; + // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB + // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and + // the mp4 path already collects its copied AAC track the same. Upgrade path + // is hound's incremental writer plus flacenc's `Source` trait. + let mut samples: Vec = Vec::with_capacity(total); + for chunk in chunks { + cancelled(shared)?; + // ponytail: the per-segment EQ goes here -- `EqState::process` on this + // same interleaved f32 buffer, before the quantisation below, which is + // the point playback's feeder will call it from too. Not wired: the EQ + // slice owns that, this is only the seat kept for it. + samples.extend( + chunk + .samples + .iter() + .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32), + ); + let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1); + shared.progress.store(done as u32, Ordering::Relaxed); + } + samples.resize(total, 0); + // Written in one go and still cancellable up to here, exactly as the mp4 + // path is up to its `finish`: the `.part` is what either gets renamed or + // deleted. + cancelled(shared)?; + match format { + Format::Wav => write_wav(out, &samples, &audio)?, + Format::Flac => write_flac(out, &samples, &audio)?, + Format::Mp4 => unreachable!("the mp4 path is `run`"), + } + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); + Ok(()) +} + +/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in +/// this engine, so what the decoder handed over is what the header says. +fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { + let mut writer = hound::WavWriter::create( + out, + hound::WavSpec { + channels: audio.channels, + sample_rate: audio.sample_rate, + bits_per_sample: 16, + sample_format: hound::SampleFormat::Int, + }, + )?; + for &sample in samples { + writer.write_sample(sample as i16)?; + } + // Not `drop`: this is what rewrites the RIFF sizes in the header, and its + // failure is the difference between a finished file and a truncated one. + writer.finalize()?; + 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. +fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { + let config = flacenc::config::Encoder::default() + .into_verified() + .map_err(|(_, e)| format!("flac encoder config: {e}"))?; + let source = flacenc::source::MemSource::from_samples( + samples, + usize::from(audio.channels), + 16, + audio.sample_rate as usize, + ); + let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size) + .map_err(|e| format!("flac encode: {e}"))?; + // The block sizes are stated fixed, which is what the frames themselves say + // (they are numbered, not sample-addressed). flacenc's single-threaded path + // instead writes the *last* frame's length as the minimum, and a short final + // frame is the normal case -- a stream whose `streaminfo` then disagrees + // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia, + // which is this engine's own reader, rejects every frame header and reads + // to EOF looking for a good one. Written this way the file reopens here, + // which is the only test of an export that counts. (Same value flacenc's + // own `par` path writes; the reference encoder does it too.) + stream + .stream_info_mut() + .set_block_sizes(config.block_size, config.block_size) + .map_err(|e| format!("flac block size: {e}"))?; + let mut sink = flacenc::bitsink::ByteSink::new(); + stream + .write(&mut sink) + .map_err(|e| format!("flac write: {e}"))?; + std::fs::write(out, sink.as_slice())?; + Ok(()) +} + /// The I420 planes of one black picture, allocated once for a whole export: a /// gap in the video lane is encoded, not skipped, or every frame after it would /// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs new file mode 100644 index 0000000..8f8454d --- /dev/null +++ b/crates/engine/tests/audio_export.rs @@ -0,0 +1,274 @@ +//! The timeline's audio written out on its own, as a WAV or a FLAC, and read +//! straight back in through the engine's own reader — which is the check that +//! matters: a file this program cannot reopen is a file it had no business +//! writing. +//! +//! The fixtures carry a 1 Hz volume pulse (`gen_fixtures.sh`), so a second of +//! exported audio has a measurable shape and not just a level: the pattern is +//! asserted as a peak/dip *ratio*, never an absolute level, because ffmpeg's +//! sine fixtures peak around 0.12. +//! +//! No picture is decoded anywhere here, so nothing needs the plugin and the +//! whole file runs on any machine. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::Source; +use engine::{AudioSession, Clip, ExportHandle, Project}; + +const RATE: u32 = 44_100; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Per-run unique, like the mp4 suite's: two suites at once must not delete +/// each other's output. +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = + std::env::temp_dir().join(format!("ve_audio_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(part_path(&path)); + path +} + +fn part_path(out: &Path) -> PathBuf { + PathBuf::from(format!("{}.part", out.display())) +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < limit, "export did not finish in {limit:?}"); + std::thread::sleep(Duration::from_millis(10)); + } + handle.result().expect("a finished export has an outcome") +} + +/// 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. +fn mixed_project() -> Project { + let clip = |start, source| Clip { + start, + in_frame: 0, + out_frame: 30, + source, + link: None, + }; + Project::from_parts( + vec![ + Source::new(asset("test_av.mp4"), 0), + Source::new(asset("test_tone.mp3"), 0), + ], + // The picture is beside the point here, but a project has two lanes and + // the timeline's length is the longer of them: three seconds of video + // is what makes the third second of audio part of the timeline. + vec![Clip { + start: 0, + in_frame: 0, + out_frame: 90, + source: 0, + link: None, + }], + vec![clip(0, 0), clip(60, 1)], + ) + .expect("a two-source project with a hole in the audio lane") +} + +fn meta() -> engine::VideoMeta { + engine::demux::Demuxer::open(&asset("test_av.mp4")) + .expect("open test_av") + .0 +} + +/// Interleaved samples of a written file, through the engine's own reader -- +/// the same door an import comes in through, so a pass here means the export +/// can be brought back into a timeline. +fn decode(path: &Path) -> (engine::AudioMeta, Vec) { + let (meta, chunks) = AudioSession::open(path) + .expect("reopen the export") + .expect("the export has audio"); + let mut samples = Vec::new(); + for chunk in chunks { + samples.extend(chunk.samples); + } + (meta, samples) +} + +/// Root mean square of `[from, to)` seconds of an interleaved stereo buffer. +fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 { + let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels; + let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())]; + assert!(!window.is_empty(), "no samples in [{from}, {to})"); + (window.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() / window.len() as f64).sqrt() +} + +/// What every audio export must be, whatever encoded it: exactly as long as the +/// timeline, silent where the timeline is empty, and audible where it is not -- +/// with the fixtures' 1 Hz pulse still in it, which is what says the samples are +/// the *edit's* and not just noise of the right length. +fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) { + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded"); + let channels = usize::from(meta.channels); + // Three seconds of timeline, to the sample: the segments round their own + // windows and the mp3 need not end where the second does, so this is the + // export's own trim/pad and not an accident of the sources. + let frames = (3.0 * f64::from(RATE)) as usize; + assert_eq!(samples.len(), frames * channels, "timeline length in samples"); + + // Second 0 is test_av, second 2 is the mp3; both carry the tone. + let av = rms(samples, channels, 0.05, 0.95); + let tone = rms(samples, channels, 2.05, 2.95); + // Second 1 is the hole. Silence, not a stall and not a skip: it occupies + // its full second, which is what the sample count above already proved. + let gap = rms(samples, channels, 1.0, 2.0); + println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}"); + assert!(av > 0.01, "the first second is audible"); + assert!(tone > 0.01, "the mp3 second is audible"); + assert_eq!(gap, 0.0, "the gap is exact silence"); + + // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at + // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level. + let peak = rms(samples, channels, 0.2, 0.3); + let dip = rms(samples, channels, 0.7, 0.8); + println!("pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}", peak / dip); + assert!( + peak > dip * 4.0, + "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}" + ); +} + +/// The RIFF header itself, byte for byte: hound writes it, but what a player +/// reads is the bytes, and a wrong rate or a wrong `data` size is a file that +/// decodes at the wrong speed rather than one that fails to open. +fn assert_wav_header(path: &Path, frames: usize) { + let bytes = std::fs::read(path).expect("read the wav back"); + let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]); + let u32_at = |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); + assert_eq!(&bytes[0..4], b"RIFF"); + assert_eq!(&bytes[8..12], b"WAVE"); + assert_eq!(&bytes[12..16], b"fmt "); + assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size"); + assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag"); + assert_eq!(u16_at(22), 2, "stereo"); + assert_eq!(u32_at(24), RATE, "sample rate"); + assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2"); + assert_eq!(u16_at(32), 4, "block align"); + assert_eq!(u16_at(34), 16, "bits per sample"); + // The `data` chunk carries every sample and nothing else. hound may write a + // `fact` chunk first, so it is found rather than assumed to be at 36. + let data = bytes + .windows(4) + .position(|w| w == b"data") + .expect("a data chunk"); + assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size"); +} + +#[test] +fn exports_the_timeline_as_a_wav() { + let out = out_path("wav", "wav"); + let handle = engine::export::start( + mixed_project(), + meta(), + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).expect("wav 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_timeline_shape(&meta, &samples); + assert_wav_header(&out, samples.len() / usize::from(meta.channels)); + std::fs::remove_file(&out).unwrap(); +} + +#[test] +fn exports_the_timeline_as_a_flac() { + let out = out_path("flac", "flac"); + let handle = engine::export::start( + mixed_project(), + meta(), + &out, + &ExportSettings { + format: Format::Flac, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).expect("flac export"); + assert_eq!(handle.progress(), 1.0, "finished at full progress"); + + let bytes = std::fs::read(&out).expect("read the flac back"); + assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic"); + // Lossless is a claim about the samples, so it is checked on the samples: + // the same shape the WAV of the same timeline has. + let (meta, samples) = decode(&out); + assert_timeline_shape(&meta, &samples); + // Smaller than the PCM it encodes, or the whole point of the row is gone. + let pcm = samples.len() * 2; + println!("flac {} bytes for {pcm} bytes of PCM", bytes.len()); + assert!(bytes.len() < pcm, "compressed"); + 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. +#[test] +fn a_cancelled_audio_export_leaves_no_file() { + let source = asset("test_av.mp4"); + let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av"); + let mut project = Project::single(&source, meta.frame_count); + for _ in 0..11 { + assert!(project.append_clip(0, meta.frame_count), "a minute of it"); + } + let out = out_path("cancel", "wav"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + handle.cancel(); + let outcome = wait(&handle, Duration::from_secs(120)); + let text = outcome.expect_err("a cancelled export fails").to_string(); + assert!(text.contains("cancelled"), "{text}"); + assert!(!out.exists(), "no output file"); + assert!(!part_path(&out).exists(), "no half-written .part either"); +} + +/// 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] +fn a_silent_timeline_refuses_an_audio_export() { + let source = asset("test_mismatch.mp4"); // video only, no audio track + let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); + let out = out_path("silent", "wav"); + let handle = engine::export::start( + Project::single(&source, meta.frame_count), + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + let text = wait(&handle, Duration::from_secs(60)) + .expect_err("no audio to export") + .to_string(); + assert!(text.contains("no audio"), "{text}"); + assert!(!out.exists() && !part_path(&out).exists(), "nothing written"); +} diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index cc5154f..fe3f788 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -374,6 +374,7 @@ fn a_higher_bitrate_writes_a_bigger_file() { let settings = ExportSettings { bitrate: Some(bitrate), force_sw: true, + ..Default::default() }; let handle = session.export_to_with(&out, &settings); wait(&handle, Duration::from_secs(180)).expect("export");