Merge branch 'worktree-agent-a79e9f7518437da23'
Browse files at this commit7 changed files +784 -68
- Cargo.lock +70 -1
- crates/app/src/keymap.rs +11 -1
- crates/app/src/main.rs +243 -55
- crates/engine/Cargo.toml +6 -0
- crates/engine/src/export.rs +179 -11
- crates/engine/tests/audio_export.rs +274 -0
- crates/engine/tests/export.rs +1 -0
Cargo.lockmodified+70 -1
| @@ -716,6 +716,12 @@ dependencies = [ | |||
| 716 | "serde_core", | 716 | "serde_core", |
| 717 | ] | 717 | ] |
| 718 | 718 | ||
| 719 | +[[package]] | ||
| 720 | +name = "built" | ||
| 721 | +version = "0.7.7" | ||
| 722 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 723 | +checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b" | ||
| 724 | + | ||
| 719 | [[package]] | 725 | [[package]] |
| 720 | name = "built" | 726 | name = "built" |
| 721 | version = "0.8.1" | 727 | version = "0.8.1" |
| @@ -1238,6 +1244,21 @@ dependencies = [ | |||
| 1238 | "libc", | 1244 | "libc", |
| 1239 | ] | 1245 | ] |
| 1240 | 1246 | ||
| 1247 | +[[package]] | ||
| 1248 | +name = "crc" | ||
| 1249 | +version = "3.4.0" | ||
| 1250 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1251 | +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" | ||
| 1252 | +dependencies = [ | ||
| 1253 | + "crc-catalog", | ||
| 1254 | +] | ||
| 1255 | + | ||
| 1256 | +[[package]] | ||
| 1257 | +name = "crc-catalog" | ||
| 1258 | +version = "2.5.0" | ||
| 1259 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1260 | +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" | ||
| 1261 | + | ||
| 1241 | [[package]] | 1262 | [[package]] |
| 1242 | name = "crc32fast" | 1263 | name = "crc32fast" |
| 1243 | version = "1.5.0" | 1264 | version = "1.5.0" |
| @@ -1609,6 +1630,8 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" | |||
| 1609 | name = "engine" | 1630 | name = "engine" |
| 1610 | version = "0.1.0" | 1631 | version = "0.1.0" |
| 1611 | dependencies = [ | 1632 | dependencies = [ |
| 1633 | + "flacenc", | ||
| 1634 | + "hound", | ||
| 1612 | "libloading", | 1635 | "libloading", |
| 1613 | "mp4", | 1636 | "mp4", |
| 1614 | "rusty_h264", | 1637 | "rusty_h264", |
| @@ -1828,6 +1851,21 @@ version = "0.1.10" | |||
| 1828 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1851 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1829 | checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" | 1852 | checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" |
| 1830 | 1853 | ||
| 1854 | +[[package]] | ||
| 1855 | +name = "flacenc" | ||
| 1856 | +version = "0.5.1" | ||
| 1857 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1858 | +checksum = "74c892c2b5fa08f967e8b5ad29121570b4762202f2402033ce08479ec65eccd0" | ||
| 1859 | +dependencies = [ | ||
| 1860 | + "built 0.7.7", | ||
| 1861 | + "crc", | ||
| 1862 | + "heapless", | ||
| 1863 | + "md-5", | ||
| 1864 | + "num-traits", | ||
| 1865 | + "rustversion", | ||
| 1866 | + "seq-macro", | ||
| 1867 | +] | ||
| 1868 | + | ||
| 1831 | [[package]] | 1869 | [[package]] |
| 1832 | name = "flate2" | 1870 | name = "flate2" |
| 1833 | version = "1.1.9" | 1871 | version = "1.1.9" |
| @@ -2559,6 +2597,15 @@ dependencies = [ | |||
| 2559 | "zerocopy", | 2597 | "zerocopy", |
| 2560 | ] | 2598 | ] |
| 2561 | 2599 | ||
| 2600 | +[[package]] | ||
| 2601 | +name = "hash32" | ||
| 2602 | +version = "0.3.1" | ||
| 2603 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2604 | +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" | ||
| 2605 | +dependencies = [ | ||
| 2606 | + "byteorder", | ||
| 2607 | +] | ||
| 2608 | + | ||
| 2562 | [[package]] | 2609 | [[package]] |
| 2563 | name = "hashbrown" | 2610 | name = "hashbrown" |
| 2564 | version = "0.14.5" | 2611 | version = "0.14.5" |
| @@ -2580,6 +2627,16 @@ version = "0.17.1" | |||
| 2580 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2627 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2581 | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" | 2628 | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" |
| 2582 | 2629 | ||
| 2630 | +[[package]] | ||
| 2631 | +name = "heapless" | ||
| 2632 | +version = "0.8.0" | ||
| 2633 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2634 | +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" | ||
| 2635 | +dependencies = [ | ||
| 2636 | + "hash32", | ||
| 2637 | + "stable_deref_trait", | ||
| 2638 | +] | ||
| 2639 | + | ||
| 2583 | [[package]] | 2640 | [[package]] |
| 2584 | name = "heck" | 2641 | name = "heck" |
| 2585 | version = "0.4.1" | 2642 | version = "0.4.1" |
| @@ -2648,6 +2705,12 @@ dependencies = [ | |||
| 2648 | "windows-sys 0.61.2", | 2705 | "windows-sys 0.61.2", |
| 2649 | ] | 2706 | ] |
| 2650 | 2707 | ||
| 2708 | +[[package]] | ||
| 2709 | +name = "hound" | ||
| 2710 | +version = "3.5.1" | ||
| 2711 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2712 | +checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" | ||
| 2713 | + | ||
| 2651 | [[package]] | 2714 | [[package]] |
| 2652 | name = "http" | 2715 | name = "http" |
| 2653 | version = "1.5.0" | 2716 | version = "1.5.0" |
| @@ -4420,7 +4483,7 @@ dependencies = [ | |||
| 4420 | "av-scenechange", | 4483 | "av-scenechange", |
| 4421 | "av1-grain", | 4484 | "av1-grain", |
| 4422 | "bitstream-io", | 4485 | "bitstream-io", |
| 4423 | - "built", | 4486 | + "built 0.8.1", |
| 4424 | "cfg-if", | 4487 | "cfg-if", |
| 4425 | "interpolate_name", | 4488 | "interpolate_name", |
| 4426 | "itertools 0.14.0", | 4489 | "itertools 0.14.0", |
| @@ -5002,6 +5065,12 @@ version = "1.0.28" | |||
| 5002 | source = "registry+https://github.com/rust-lang/crates.io-index" | 5065 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 5003 | checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" | 5066 | checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" |
| 5004 | 5067 | ||
| 5068 | +[[package]] | ||
| 5069 | +name = "seq-macro" | ||
| 5070 | +version = "0.3.6" | ||
| 5071 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5072 | +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" | ||
| 5073 | + | ||
| 5005 | [[package]] | 5074 | [[package]] |
| 5006 | name = "serde" | 5075 | name = "serde" |
| 5007 | version = "1.0.229" | 5076 | version = "1.0.229" |
crates/app/src/keymap.rsmodified+11 -1
| @@ -179,7 +179,7 @@ pub struct Fixed { | |||
| 179 | pub category: Category, | 179 | pub category: Category, |
| 180 | } | 180 | } |
| 181 | 181 | ||
| 182 | -pub const FIXED: [Fixed; 3] = [ | 182 | +pub const FIXED: [Fixed; 5] = [ |
| 183 | Fixed { | 183 | Fixed { |
| 184 | chord: "esc", | 184 | chord: "esc", |
| 185 | label: "Close this card or clip menu, or cancel a capture", | 185 | label: "Close this card or clip menu, or cancel a capture", |
| @@ -190,6 +190,16 @@ pub const FIXED: [Fixed; 3] = [ | |||
| 190 | label: "Type a custom export bitrate", | 190 | label: "Type a custom export bitrate", |
| 191 | category: Category::File, | 191 | category: Category::File, |
| 192 | }, | 192 | }, |
| 193 | + Fixed { | ||
| 194 | + chord: "m / w / f", | ||
| 195 | + label: "Pick the export format: MP4, WAV or FLAC", | ||
| 196 | + category: Category::File, | ||
| 197 | + }, | ||
| 198 | + Fixed { | ||
| 199 | + chord: "enter", | ||
| 200 | + label: "Start the export the card is set to", | ||
| 201 | + category: Category::File, | ||
| 202 | + }, | ||
| 193 | Fixed { | 203 | Fixed { |
| 194 | chord: "backspace", | 204 | chord: "backspace", |
| 195 | label: "Erase a bitrate digit", | 205 | label: "Erase a bitrate digit", |
crates/app/src/main.rsmodified+243 -55
| @@ -10,14 +10,14 @@ use std::sync::Arc; | |||
| 10 | use std::time::{Duration, Instant}; | 10 | use std::time::{Duration, Instant}; |
| 11 | 11 | ||
| 12 | use engine::audio::StreamInfo; | 12 | use engine::audio::StreamInfo; |
| 13 | -use engine::export::ExportSettings; | 13 | +use engine::export::{ExportSettings, Format}; |
| 14 | use engine::project::{Lane, LaneKind, Source}; | 14 | use engine::project::{Lane, LaneKind, Source}; |
| 15 | use engine::{Clip, ExportHandle, Frame, PlaybackSession}; | 15 | use engine::{Clip, ExportHandle, Frame, PlaybackSession}; |
| 16 | use gpui::{ | 16 | use gpui::{ |
| 17 | - AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent, | 17 | + AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, |
| 18 | MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, | 18 | MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, |
| 19 | - RenderImage, SharedString, Size, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, | 19 | + RenderImage, SharedString, Size, Stateful, TitlebarOptions, Window, WindowBounds, WindowOptions, |
| 20 | - div, img, point, prelude::*, px, relative, rgb, rgba, size, | 20 | + canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, |
| 21 | }; | 21 | }; |
| 22 | 22 | ||
| 23 | /// Editor chrome: three grays and one accent, all darker than the picture so the | 23 | /// 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; | |||
| 99 | /// keeps the card inside the smallest window no matter how many actions the | 99 | /// keeps the card inside the smallest window no matter how many actions the |
| 100 | /// editor grows -- ten rows fit here, and the eleventh is a scroll away. | 100 | /// editor grows -- ten rows fit here, and the eleventh is a scroll away. |
| 101 | const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; | 101 | const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; |
| 102 | +/// The same for the export card, which carries a fixed-format line and a button | ||
| 103 | +/// under its list and so has less room: destination, six formats and five | ||
| 104 | +/// qualities are twelve rows, eight of them on screen. | ||
| 105 | +const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; | ||
| 102 | /// The menu a right-click on a clip opens: wide enough for the longest label | 106 | /// The menu a right-click on a clip opens: wide enough for the longest label |
| 103 | /// beside the stroke that does the same thing, with the click targets `HIT_MIN` | 107 | /// beside the stroke that does the same thing, with the click targets `HIT_MIN` |
| 104 | /// binds like every other list here. | 108 | /// binds like every other list here. |
| @@ -310,6 +314,9 @@ struct Player { | |||
| 310 | /// first one chose. | 314 | /// first one chose. |
| 311 | quality: Quality, | 315 | quality: Quality, |
| 312 | custom_mbps: u32, | 316 | custom_mbps: u32, |
| 317 | + /// Which file the card will write. Kept across closes like the quality, and | ||
| 318 | + /// what [`Player::export_path`](Player) is named after. | ||
| 319 | + format: Format, | ||
| 313 | /// The action whose row is waiting for a stroke. The next key that is | 320 | /// The action whose row is waiting for a stroke. The next key that is |
| 314 | /// neither escape nor a lone modifier becomes the whole of what reaches it. | 321 | /// neither escape nor a lone modifier becomes the whole of what reaches it. |
| 315 | rebinding: Option<ActionId>, | 322 | rebinding: Option<ActionId>, |
| @@ -762,7 +769,9 @@ impl Player { | |||
| 762 | // A fresh session comes up at full volume; the player's own | 769 | // A fresh session comes up at full volume; the player's own |
| 763 | // setting outlives the file, so it is pushed at every new one. | 770 | // setting outlives the file, so it is pushed at every new one. |
| 764 | self.apply_volume(); | 771 | self.apply_volume(); |
| 765 | - self.export_path = export_path(path); | 772 | + // Beside the new file, but still the format the card is set to: |
| 773 | + // opening another clip is not a change of mind about that. | ||
| 774 | + self.export_path = retarget(&export_path(path), self.format); | ||
| 766 | self.project_path = project_path(path); | 775 | self.project_path = project_path(path); |
| 767 | self.name = file_name(path).into(); | 776 | self.name = file_name(path).into(); |
| 768 | self.reset_after_reseek(); | 777 | self.reset_after_reseek(); |
| @@ -815,7 +824,7 @@ impl Player { | |||
| 815 | let silent = audio_notice(&session); | 824 | let silent = audio_notice(&session); |
| 816 | // A project is named after itself but still exports beside its | 825 | // A project is named after itself but still exports beside its |
| 817 | // media: that is the only place an export has ever landed. | 826 | // media: that is the only place an export has ever landed. |
| 818 | - self.export_path = export_path(&session.sources()[0].path); | 827 | + self.export_path = retarget(&export_path(&session.sources()[0].path), self.format); |
| 819 | self.session = Some(session); | 828 | self.session = Some(session); |
| 820 | self.apply_volume(); | 829 | self.apply_volume(); |
| 821 | self.project_path = path.to_path_buf(); | 830 | self.project_path = path.to_path_buf(); |
| @@ -985,6 +994,14 @@ impl Player { | |||
| 985 | cx.notify(); | 994 | cx.notify(); |
| 986 | } | 995 | } |
| 987 | 996 | ||
| 997 | + /// A format row was clicked. The destination follows it at once -- a WAV | ||
| 998 | + /// written to a path ending in `.mp4` is a file every player will lie | ||
| 999 | + /// about -- keeping whatever stem the save dialog last left there. | ||
| 1000 | + fn set_format(&mut self, format: Format) { | ||
| 1001 | + self.format = format; | ||
| 1002 | + self.export_path = retarget(&self.export_path, format); | ||
| 1003 | + } | ||
| 1004 | + | ||
| 988 | /// The card's Destination row: the desktop's save dialog, on a background | 1005 | /// The card's Destination row: the desktop's save dialog, on a background |
| 989 | /// thread like the import chooser -- the user may sit in it and the window | 1006 | /// thread like the import chooser -- the user may sit in it and the window |
| 990 | /// behind must not freeze. No chooser at all leaves the default path, which | 1007 | /// behind must not freeze. No chooser at all leaves the default path, which |
| @@ -1003,7 +1020,9 @@ impl Player { | |||
| 1003 | return; | 1020 | return; |
| 1004 | } | 1021 | } |
| 1005 | match picked { | 1022 | match picked { |
| 1006 | - Ok(Some(path)) => this.export_path = path, | 1023 | + // The stem is the user's, the extension is the format's: a |
| 1024 | + // FLAC named `.mp4` is a file every player lies about. | ||
| 1025 | + Ok(Some(path)) => this.export_path = retarget(&path, this.format), | ||
| 1007 | // Cancelled: the default stands, as it did before. | 1026 | // Cancelled: the default stands, as it did before. |
| 1008 | Ok(None) => {} | 1027 | Ok(None) => {} |
| 1009 | Err(text) => { | 1028 | Err(text) => { |
| @@ -1028,7 +1047,7 @@ impl Player { | |||
| 1028 | if self.export.is_some() { | 1047 | if self.export.is_some() { |
| 1029 | return; | 1048 | return; |
| 1030 | } | 1049 | } |
| 1031 | - let settings = export_settings(self.quality, self.custom_mbps); | 1050 | + let settings = export_settings(self.quality, self.custom_mbps, self.format); |
| 1032 | let Some(session) = &mut self.session else { | 1051 | let Some(session) = &mut self.session else { |
| 1033 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); | 1052 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); |
| 1034 | cx.notify(); | 1053 | cx.notify(); |
| @@ -1190,6 +1209,18 @@ impl Render for Player { | |||
| 1190 | if this.export_open { | 1209 | if this.export_open { |
| 1191 | if key == ESCAPE { | 1210 | if key == ESCAPE { |
| 1192 | this.export_open = false; | 1211 | this.export_open = false; |
| 1212 | + } else if key == "enter" { | ||
| 1213 | + // The card's own button, by keyboard: the one thing in | ||
| 1214 | + // it that writes a file must not be pointer-only either. | ||
| 1215 | + this.start_export(cx); | ||
| 1216 | + } else if let Some(format) = format_key(key) { | ||
| 1217 | + // The format rows by their initial, so the card can be | ||
| 1218 | + // driven without a mouse -- the same card-local input | ||
| 1219 | + // the typed bitrate is, and for the same reason: a | ||
| 1220 | + // choice reachable only by pointer is not reachable by | ||
| 1221 | + // everyone. Not a keymap binding: it means nothing | ||
| 1222 | + // outside this card, exactly like the digits. | ||
| 1223 | + this.set_format(format); | ||
| 1193 | } else if let Ok(digit) = key.parse::<u32>() { | 1224 | } else if let Ok(digit) = key.parse::<u32>() { |
| 1194 | this.custom_mbps = push_digit(this.custom_mbps, digit); | 1225 | this.custom_mbps = push_digit(this.custom_mbps, digit); |
| 1195 | this.quality = Quality::Custom; | 1226 | this.quality = Quality::Custom; |
| @@ -1987,19 +2018,52 @@ impl Player { | |||
| 1987 | .gap(px(12.)) | 2018 | .gap(px(12.)) |
| 1988 | .px(px(6.)) | 2019 | .px(px(6.)) |
| 1989 | .rounded(px(3.)) | 2020 | .rounded(px(3.)) |
| 1990 | - .cursor_pointer() | ||
| 1991 | - .hover(|s| s.bg(rgb(HOVER))) | ||
| 1992 | }; | 2021 | }; |
| 2022 | + // A row that cannot be picked is dimmed and takes no click, exactly as | ||
| 2023 | + // an inapplicable item in the clip menu is: it still says its piece. | ||
| 2024 | + let live = |d: Stateful<Div>, enabled: bool| { | ||
| 2025 | + d.when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) | ||
| 2026 | + .when(enabled, |d| { | ||
| 2027 | + d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))) | ||
| 2028 | + }) | ||
| 2029 | + }; | ||
| 2030 | + // The formats first: the quality rows below are *video* bitrate, so | ||
| 2031 | + // which file is being written decides whether they mean anything. | ||
| 2032 | + let formats: Vec<_> = FORMATS | ||
| 2033 | + .into_iter() | ||
| 2034 | + .enumerate() | ||
| 2035 | + .map(|(i, (format, label, detail))| { | ||
| 2036 | + let picked = format == Some(self.format); | ||
| 2037 | + live(row(("format", i)), format.is_some()) | ||
| 2038 | + .when(picked, |d| d.bg(rgb(SELECTED))) | ||
| 2039 | + .when_some(format, |d, format| { | ||
| 2040 | + d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 2041 | + this.set_format(format); | ||
| 2042 | + cx.notify(); | ||
| 2043 | + })) | ||
| 2044 | + }) | ||
| 2045 | + .child(label) | ||
| 2046 | + .child( | ||
| 2047 | + div() | ||
| 2048 | + .text_size(px(11.)) | ||
| 2049 | + .text_color(rgb(INK_DIM)) | ||
| 2050 | + .child(detail), | ||
| 2051 | + ) | ||
| 2052 | + }) | ||
| 2053 | + .collect(); | ||
| 2054 | + let video = self.format.has_video(); | ||
| 1993 | let rows: Vec<_> = Quality::ALL | 2055 | let rows: Vec<_> = Quality::ALL |
| 1994 | .into_iter() | 2056 | .into_iter() |
| 1995 | .enumerate() | 2057 | .enumerate() |
| 1996 | .map(|(i, quality)| { | 2058 | .map(|(i, quality)| { |
| 1997 | - row(("quality", i)) | 2059 | + live(row(("quality", i)), video) |
| 1998 | - .when(self.quality == quality, |d| d.bg(rgb(SELECTED))) | 2060 | + .when(video && self.quality == quality, |d| d.bg(rgb(SELECTED))) |
| 1999 | - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 2061 | + .when(video, |d| { |
| 2000 | - this.quality = quality; | 2062 | + d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { |
| 2001 | - cx.notify(); | 2063 | + this.quality = quality; |
| 2002 | - })) | 2064 | + cx.notify(); |
| 2065 | + })) | ||
| 2066 | + }) | ||
| 2003 | .child(quality.label()) | 2067 | .child(quality.label()) |
| 2004 | .child( | 2068 | .child( |
| 2005 | div() | 2069 | div() |
| @@ -2040,34 +2104,47 @@ impl Player { | |||
| 2040 | .text_size(px(11.)) | 2104 | .text_size(px(11.)) |
| 2041 | .text_color(rgb(INK_DIM)) | 2105 | .text_color(rgb(INK_DIM)) |
| 2042 | .child(self.notice.clone().unwrap_or_else(|| { | 2106 | .child(self.notice.clone().unwrap_or_else(|| { |
| 2043 | - "pick a quality, then Export — esc closes".into() | 2107 | + "pick a format (m/w/f), then Export — esc closes".into() |
| 2044 | })), | 2108 | })), |
| 2045 | ) | 2109 | ) |
| 2110 | + // Capped and scrolling like the keybindings list: the | ||
| 2111 | + // destination, six formats and five qualities are more | ||
| 2112 | + // rows than a 360 px window has room for, and it is the | ||
| 2113 | + // list that scrolls, never the card that grows. | ||
| 2046 | .child( | 2114 | .child( |
| 2047 | - row(("destination", 0)) | 2115 | + div() |
| 2048 | - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | 2116 | + .id("export-rows") |
| 2049 | - this.pick_destination(cx) | 2117 | + .flex() |
| 2050 | - })) | 2118 | + .flex_col() |
| 2051 | - .child("Destination") | 2119 | + .gap(px(2.)) |
| 2120 | + .max_h(px(EXPORT_ROWS_H)) | ||
| 2121 | + .overflow_y_scroll() | ||
| 2052 | .child( | 2122 | .child( |
| 2053 | - div() | 2123 | + live(row(("destination", 0)), true) |
| 2054 | - .text_size(px(11.)) | 2124 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { |
| 2055 | - .text_color(rgb(INK_DIM)) | 2125 | + this.pick_destination(cx) |
| 2056 | - .child(file_name(&self.export_path)), | 2126 | + })) |
| 2057 | - ), | 2127 | + .child("Destination") |
| 2128 | + .child( | ||
| 2129 | + div() | ||
| 2130 | + .text_size(px(11.)) | ||
| 2131 | + .text_color(rgb(INK_DIM)) | ||
| 2132 | + .child(file_name(&self.export_path)), | ||
| 2133 | + ), | ||
| 2134 | + ) | ||
| 2135 | + .children(formats) | ||
| 2136 | + .children(rows), | ||
| 2058 | ) | 2137 | ) |
| 2059 | - .children(rows) | 2138 | + // What the picked row really writes. `moov` last is the |
| 2060 | - // Not offered, so said: these are what this program can | 2139 | + // muxer's own shape -- an mp4 is playable only once it |
| 2061 | - // write, and a menu of one is a lie about the other | 2140 | + // is finished. |
| 2062 | - // entries. `moov` last is the muxer's own shape -- the | ||
| 2063 | - // file is playable only once it is finished. | ||
| 2064 | .child( | 2141 | .child( |
| 2065 | div() | 2142 | div() |
| 2066 | .flex_none() | 2143 | .flex_none() |
| 2067 | .px(px(6.)) | 2144 | .px(px(6.)) |
| 2068 | .text_size(px(11.)) | 2145 | .text_size(px(11.)) |
| 2069 | .text_color(rgb(INK_DIM)) | 2146 | .text_color(rgb(INK_DIM)) |
| 2070 | - .child("H.264 · MP4 · moov at end"), | 2147 | + .child(format_line(self.format)), |
| 2071 | ) | 2148 | ) |
| 2072 | .child( | 2149 | .child( |
| 2073 | div() | 2150 | div() |
| @@ -2932,19 +3009,74 @@ impl Quality { | |||
| 2932 | Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"), | 3009 | Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"), |
| 2933 | other => format!( | 3010 | other => format!( |
| 2934 | "{} Mbps", | 3011 | "{} Mbps", |
| 2935 | - export_settings(other, 0).bitrate.unwrap_or_default() / 1_000_000 | 3012 | + export_settings(other, 0, Format::Mp4) |
| 3013 | + .bitrate | ||
| 3014 | + .unwrap_or_default() | ||
| 3015 | + / 1_000_000 | ||
| 2936 | ), | 3016 | ), |
| 2937 | } | 3017 | } |
| 2938 | } | 3018 | } |
| 2939 | } | 3019 | } |
| 2940 | 3020 | ||
| 3021 | +/// The export card's format rows: what this program can write, and what it | ||
| 3022 | +/// cannot with the reason it cannot. A format with no entry at all would read | ||
| 3023 | +/// as an oversight, and a menu of three as a claim that nothing else exists -- | ||
| 3024 | +/// so the refusals are rows too, dimmed and unclickable. | ||
| 3025 | +/// | ||
| 3026 | +/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a | ||
| 3027 | +/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a | ||
| 3028 | +/// decision about this project rather than about the code, and the row says so | ||
| 3029 | +/// instead of pretending the encoder does not exist. | ||
| 3030 | +const FORMATS: [(Option<Format>, &str, &str); 6] = [ | ||
| 3031 | + (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), | ||
| 3032 | + (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), | ||
| 3033 | + (Some(Format::Flac), "FLAC", "lossless — audio only"), | ||
| 3034 | + (None, "MP3", "encoder is LGPL — licence decision pending"), | ||
| 3035 | + (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), | ||
| 3036 | + (None, "AAC", "no pure-Rust AAC encoder"), | ||
| 3037 | +]; | ||
| 3038 | + | ||
| 3039 | +/// The format a key picks while the export card is up: the row's own initial, | ||
| 3040 | +/// which is unambiguous across the three that can be picked. `None` for | ||
| 3041 | +/// everything else, digits included -- those are the bitrate's. | ||
| 3042 | +fn format_key(key: &str) -> Option<Format> { | ||
| 3043 | + FORMATS | ||
| 3044 | + .into_iter() | ||
| 3045 | + .filter_map(|(format, label, _)| format.zip(label.get(..1))) | ||
| 3046 | + .find(|(_, initial)| initial.eq_ignore_ascii_case(key)) | ||
| 3047 | + .map(|(format, _)| format) | ||
| 3048 | +} | ||
| 3049 | + | ||
| 3050 | +/// The line under the rows: what the picked format really writes, in the terms | ||
| 3051 | +/// a file is judged by afterwards. | ||
| 3052 | +fn format_line(format: Format) -> &'static str { | ||
| 3053 | + match format { | ||
| 3054 | + Format::Mp4 => "H.264 · MP4 · moov at end", | ||
| 3055 | + Format::Wav => "16-bit PCM · WAV · timeline audio only", | ||
| 3056 | + Format::Flac => "FLAC · lossless · timeline audio only", | ||
| 3057 | + } | ||
| 3058 | +} | ||
| 3059 | + | ||
| 3060 | +/// The destination under a format: `take.export.mp4` becomes `take.export.wav`. | ||
| 3061 | +/// The stem is untouched, so a name typed into the save dialog survives a | ||
| 3062 | +/// change of mind about the format -- only the extension is the format's to say. | ||
| 3063 | +fn retarget(path: &std::path::Path, format: Format) -> PathBuf { | ||
| 3064 | + let mut path = path.to_path_buf(); | ||
| 3065 | + path.set_extension(format.ext()); | ||
| 3066 | + path | ||
| 3067 | +} | ||
| 3068 | + | ||
| 2941 | /// The card's rows as the engine takes them. `Auto` leaves the bitrate to the | 3069 | /// The card's rows as the engine takes them. `Auto` leaves the bitrate to the |
| 2942 | /// exporter, which derives it from the picture; the fixed rows are figures that | 3070 | /// exporter, which derives it from the picture; the fixed rows are figures that |
| 2943 | /// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the | 3071 | /// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the |
| 2944 | /// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this | 3072 | /// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this |
| 2945 | /// must not clamp it a second time and disagree about where the edge is. | 3073 | /// must not clamp it a second time and disagree about where the edge is. |
| 2946 | -fn export_settings(quality: Quality, custom_mbps: u32) -> ExportSettings { | 3074 | +/// |
| 3075 | +/// The bitrate travels even for an audio format, where the engine ignores it: | ||
| 3076 | +/// one settings value, and a row the card has dimmed cannot have been changed. | ||
| 3077 | +fn export_settings(quality: Quality, custom_mbps: u32, format: Format) -> ExportSettings { | ||
| 2947 | ExportSettings { | 3078 | ExportSettings { |
| 3079 | + format, | ||
| 2948 | bitrate: match quality { | 3080 | bitrate: match quality { |
| 2949 | Quality::Auto => None, | 3081 | Quality::Auto => None, |
| 2950 | Quality::Low => Some(2_000_000), | 3082 | Quality::Low => Some(2_000_000), |
| @@ -3297,14 +3429,15 @@ fn timecode(t: f64, fps: f64) -> String { | |||
| 3297 | #[cfg(test)] | 3429 | #[cfg(test)] |
| 3298 | mod tests { | 3430 | mod tests { |
| 3299 | use super::{ | 3431 | use super::{ |
| 3300 | - ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, | 3432 | + ACCENT, CONTROL_H, Clip, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, |
| 3301 | - KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, | 3433 | + INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, |
| 3302 | - Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, | 3434 | + LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, |
| 3303 | - SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, | 3435 | + RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, |
| 3304 | - applicable, can_add, cancels_export, envelope, export_path, export_settings, frac_along, | 3436 | + WAVE_BPS, WAVE_COL, Wave, applicable, can_add, cancels_export, envelope, export_path, |
| 3305 | - frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise, | 3437 | + export_settings, format_line, frac_along, frame_at, is_bare_modifier, is_project, keymap, |
| 3306 | - project_path, push_digit, scrub_due, show_label, source_frames, source_tint, start_frac, | 3438 | + lane_clips, marked, menu_at, normalise, project_path, push_digit, retarget, scrub_due, |
| 3307 | - timecode, unseen_paths, unseen_sources, width_frac, window_title, | 3439 | + show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, |
| 3440 | + width_frac, window_title, | ||
| 3308 | }; | 3441 | }; |
| 3309 | use super::{file_name, library_rows}; | 3442 | use super::{file_name, library_rows}; |
| 3310 | use engine::PlaybackSession; | 3443 | use engine::PlaybackSession; |
| @@ -4012,17 +4145,32 @@ mod tests { | |||
| 4012 | fn a_quality_row_is_the_bitrate_it_promises() { | 4145 | fn a_quality_row_is_the_bitrate_it_promises() { |
| 4013 | // Auto is the one row that says nothing: the exporter derives it, and | 4146 | // Auto is the one row that says nothing: the exporter derives it, and |
| 4014 | // a number typed against the custom row must not leak into it. | 4147 | // a number typed against the custom row must not leak into it. |
| 4015 | - assert_eq!(export_settings(Quality::Auto, 7).bitrate, None); | 4148 | + let mp4 = Format::Mp4; |
| 4016 | - assert_eq!(export_settings(Quality::Low, 0).bitrate, Some(2_000_000)); | 4149 | + assert_eq!(export_settings(Quality::Auto, 7, mp4).bitrate, None); |
| 4017 | - assert_eq!(export_settings(Quality::Medium, 0).bitrate, Some(6_000_000)); | 4150 | + assert_eq!(export_settings(Quality::Low, 0, mp4).bitrate, Some(2_000_000)); |
| 4018 | - assert_eq!(export_settings(Quality::High, 0).bitrate, Some(12_000_000)); | 4151 | + assert_eq!( |
| 4152 | + export_settings(Quality::Medium, 0, mp4).bitrate, | ||
| 4153 | + Some(6_000_000) | ||
| 4154 | + ); | ||
| 4155 | + assert_eq!( | ||
| 4156 | + export_settings(Quality::High, 0, mp4).bitrate, | ||
| 4157 | + Some(12_000_000) | ||
| 4158 | + ); | ||
| 4019 | // Megabits as typed, and as the row says it back. | 4159 | // Megabits as typed, and as the row says it back. |
| 4020 | - assert_eq!(export_settings(Quality::Custom, 7).bitrate, Some(7_000_000)); | 4160 | + assert_eq!( |
| 4161 | + export_settings(Quality::Custom, 7, mp4).bitrate, | ||
| 4162 | + Some(7_000_000) | ||
| 4163 | + ); | ||
| 4021 | assert_eq!(Quality::Low.detail(0), "2 Mbps"); | 4164 | assert_eq!(Quality::Low.detail(0), "2 Mbps"); |
| 4165 | + // The picked format travels, or the card's rows would be a picture of a | ||
| 4166 | + // choice the engine never hears about. | ||
| 4167 | + for format in [Format::Mp4, Format::Wav, Format::Flac] { | ||
| 4168 | + assert_eq!(export_settings(Quality::Auto, 0, format).format, format); | ||
| 4169 | + } | ||
| 4022 | // Every fixed row sits inside the engine's clamp (export.rs:290), so no | 4170 | // Every fixed row sits inside the engine's clamp (export.rs:290), so no |
| 4023 | // row can promise a bitrate the exporter silently changes. | 4171 | // row can promise a bitrate the exporter silently changes. |
| 4024 | for quality in Quality::ALL { | 4172 | for quality in Quality::ALL { |
| 4025 | - let settings = export_settings(quality, 7); | 4173 | + let settings = export_settings(quality, 7, mp4); |
| 4026 | if let Some(bitrate) = settings.bitrate { | 4174 | if let Some(bitrate) = settings.bitrate { |
| 4027 | assert!( | 4175 | assert!( |
| 4028 | (1_000_000..=20_000_000).contains(&bitrate), | 4176 | (1_000_000..=20_000_000).contains(&bitrate), |
| @@ -4049,24 +4197,61 @@ mod tests { | |||
| 4049 | 4197 | ||
| 4050 | #[test] | 4198 | #[test] |
| 4051 | fn the_export_card_fits_the_smallest_window() { | 4199 | fn the_export_card_fits_the_smallest_window() { |
| 4052 | - // Same 640x360 floor the keybindings card is measured against: a | 4200 | + // Same 640x360 floor the keybindings card is measured against: the |
| 4053 | - // destination row, one row per quality, the fixed-format line and the | 4201 | + // capped row list, the fixed-format line and the confirm button, under |
| 4054 | - // confirm button, under a title and a status line. | 4202 | + // a title and a status line. |
| 4055 | - let rows = Quality::ALL.len() as f32 + 1.; | ||
| 4056 | let title = 17.; | 4203 | let title = 17.; |
| 4057 | let status = 28.; | 4204 | let status = 28.; |
| 4058 | let fixed = 17.; | 4205 | let fixed = 17.; |
| 4059 | - let gaps = (rows + 3.) * 2.; | 4206 | + let gaps = 4. * 2.; |
| 4060 | let padding = 24.; | 4207 | let padding = 24.; |
| 4061 | assert!( | 4208 | assert!( |
| 4062 | - title + status + rows * KEYS_ROW_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., | 4209 | + title + status + EXPORT_ROWS_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., |
| 4063 | "card too tall" | 4210 | "card too tall" |
| 4064 | ); | 4211 | ); |
| 4212 | + // The cap is only honest if enough of the list is on screen to read as | ||
| 4213 | + // one -- the destination and the first formats, not a slot. | ||
| 4214 | + assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 6.); | ||
| 4065 | // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's. | 4215 | // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's. |
| 4066 | assert!(KEYS_ROW_H >= HIT_MIN); | 4216 | assert!(KEYS_ROW_H >= HIT_MIN); |
| 4067 | assert!(CONTROL_H >= HIT_MIN); | 4217 | assert!(CONTROL_H >= HIT_MIN); |
| 4068 | } | 4218 | } |
| 4069 | 4219 | ||
| 4220 | + #[test] | ||
| 4221 | + fn every_format_row_is_offered_or_says_why_not() { | ||
| 4222 | + // The three this program can write are rows that pick, each named after | ||
| 4223 | + // its own extension so a destination can never disagree with its bytes. | ||
| 4224 | + let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); | ||
| 4225 | + assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]); | ||
| 4226 | + for (format, label, _) in FORMATS { | ||
| 4227 | + match format { | ||
| 4228 | + Some(format) => assert_eq!(format.ext(), label.to_lowercase()), | ||
| 4229 | + // A refused format is a row with a reason, never a hidden one: | ||
| 4230 | + // an empty detail column would read as an oversight. | ||
| 4231 | + None => assert!(!label.is_empty()), | ||
| 4232 | + } | ||
| 4233 | + } | ||
| 4234 | + for (format, label, detail) in FORMATS { | ||
| 4235 | + assert!(!detail.is_empty(), "{label} says nothing"); | ||
| 4236 | + // Only mp4 carries the picture, so only mp4 leaves the bitrate rows | ||
| 4237 | + // live -- the card dims them off exactly this. | ||
| 4238 | + assert_eq!( | ||
| 4239 | + format.is_some_and(Format::has_video), | ||
| 4240 | + format == Some(Format::Mp4) | ||
| 4241 | + ); | ||
| 4242 | + } | ||
| 4243 | + // The destination follows the format and keeps the stem, mp4 included. | ||
| 4244 | + assert_eq!( | ||
| 4245 | + retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), | ||
| 4246 | + std::path::Path::new("/a/take.export.wav") | ||
| 4247 | + ); | ||
| 4248 | + assert_eq!( | ||
| 4249 | + retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4), | ||
| 4250 | + std::path::Path::new("/a/take.export.mp4") | ||
| 4251 | + ); | ||
| 4252 | + assert!(format_line(Format::Flac).contains("audio only")); | ||
| 4253 | + } | ||
| 4254 | + | ||
| 4070 | #[test] | 4255 | #[test] |
| 4071 | fn nothing_clickable_is_smaller_than_the_wcag_minimum() { | 4256 | fn nothing_clickable_is_smaller_than_the_wcag_minimum() { |
| 4072 | // Every hit target in the panel, including the scrub strip -- whose bar | 4257 | // Every hit target in the panel, including the scrub strip -- whose bar |
| @@ -4411,6 +4596,9 @@ fn main() { | |||
| 4411 | // bitrate the picture asks for. | 4596 | // bitrate the picture asks for. |
| 4412 | quality: Quality::Auto, | 4597 | quality: Quality::Auto, |
| 4413 | custom_mbps: 0, | 4598 | custom_mbps: 0, |
| 4599 | + // Picture and sound, which is what an export was before | ||
| 4600 | + // there was anything to pick. | ||
| 4601 | + format: Format::default(), | ||
| 4414 | rebinding: None, | 4602 | rebinding: None, |
| 4415 | notice: notice.clone().map(SharedString::from), | 4603 | notice: notice.clone().map(SharedString::from), |
| 4416 | // Nothing pushed yet, and never a real title: the first | 4604 | // Nothing pushed yet, and never a real title: the first |
crates/engine/Cargo.tomlmodified+6 -0
| @@ -5,6 +5,12 @@ edition.workspace = true | |||
| 5 | 5 | ||
| 6 | # No UI dependency here, ever: the engine must stay reusable across front-ends. | 6 | # No UI dependency here, ever: the engine must stay reusable across front-ends. |
| 7 | [dependencies] | 7 | [dependencies] |
| 8 | +# The two audio-only export formats. Pure Rust, both of them, which is the whole | ||
| 9 | +# reason they are the two: `hound` writes the RIFF header and the PCM, `flacenc` | ||
| 10 | +# encodes FLAC. No default features on flacenc -- its `par` (rayon), `log` and | ||
| 11 | +# `serde` are for its own command-line front-end, and this needs none of them. | ||
| 12 | +hound = "3.5.1" | ||
| 13 | +flacenc = { version = "0.5.1", default-features = false } | ||
| 8 | libloading = "0.8" | 14 | libloading = "0.8" |
| 9 | mp4 = "0.14" | 15 | mp4 = "0.14" |
| 10 | rusty_h264 = { version = "0.8", default-features = false } | 16 | rusty_h264 = { version = "0.8", default-features = false } |
crates/engine/src/export.rsmodified+179 -11
| @@ -1,9 +1,13 @@ | |||
| 1 | -//! Export: the edit list rendered back out as one mp4. | 1 | +//! Export: the edit list rendered back out as one mp4 — or, picture left |
| 2 | +//! behind, as one WAV or FLAC of the timeline's audio alone. | ||
| 2 | //! | 3 | //! |
| 3 | //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it | 4 | //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it |
| 4 | //! is impossible — while audio is copied packet for packet, because there is no | 5 | //! is impossible — while audio is copied packet for packet, because there is no |
| 5 | -//! pure-Rust AAC encoder to re-encode with. The worker owns everything: the | 6 | +//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such |
| 6 | -//! caller gets an [`ExportHandle`] and polls it from its render loop. | 7 | +//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so |
| 8 | +//! those are *decoded* out of the timeline instead of copied. The worker owns | ||
| 9 | +//! everything: the caller gets an [`ExportHandle`] and polls it from its render | ||
| 10 | +//! loop. | ||
| 7 | //! | 11 | //! |
| 8 | //! Nothing partial survives a failure: the worker writes to `<out>.part` and | 12 | //! Nothing partial survives a failure: the worker writes to `<out>.part` and |
| 9 | //! renames it onto `out` only once the file is closed and complete, so the | 13 | //! renames it onto `out` only once the file is closed and complete, so the |
| @@ -20,7 +24,10 @@ use std::thread; | |||
| 20 | 24 | ||
| 21 | use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; | 25 | use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; |
| 22 | 26 | ||
| 23 | -use crate::audio::AudioSession; | 27 | +use flacenc::component::BitRepr; |
| 28 | +use flacenc::error::Verify; | ||
| 29 | + | ||
| 30 | +use crate::audio::{AudioMeta, AudioSession}; | ||
| 24 | use crate::demux::{Demuxer, VideoMeta}; | 31 | use crate::demux::{Demuxer, VideoMeta}; |
| 25 | use crate::hw::{HwEncoder, HwSession}; | 32 | use crate::hw::{HwEncoder, HwSession}; |
| 26 | use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; | 33 | use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; |
| @@ -36,18 +43,55 @@ const BITS_PER_PIXEL: f64 = 0.1; | |||
| 36 | const MIN_BITRATE: u64 = 1_000_000; | 43 | const MIN_BITRATE: u64 = 1_000_000; |
| 37 | const MAX_BITRATE: u64 = 20_000_000; | 44 | const MAX_BITRATE: u64 = 20_000_000; |
| 38 | 45 | ||
| 39 | -/// What the caller gets to decide about the output. The codec and container are | 46 | +/// What an export writes. Three, not more: H.264-in-mp4 is the only *video* |
| 40 | -/// not among it: H.264 in mp4 is the only pair with both an encoder and a | 47 | +/// pair with both an encoder and a decoder under this project's no-install |
| 41 | -/// decoder under this project's no-install rule, so offering a choice would be | 48 | +/// rule, and WAV and FLAC are the only audio formats with a pure-Rust encoder |
| 42 | -/// offering files we cannot read back. | 49 | +/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing |
| 50 | +/// decision this project has not taken; Vorbis, Opus and AAC have none. A | ||
| 51 | +/// front-end says so rather than hiding the rows. | ||
| 52 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | ||
| 53 | +pub enum Format { | ||
| 54 | + /// Picture and sound: video re-encoded, AAC copied. | ||
| 55 | + #[default] | ||
| 56 | + Mp4, | ||
| 57 | + /// The audio lane alone, 16-bit PCM. | ||
| 58 | + Wav, | ||
| 59 | + /// The audio lane alone, losslessly compressed. | ||
| 60 | + Flac, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl Format { | ||
| 64 | + /// The extension a file of this format is named with -- a front-end builds | ||
| 65 | + /// the destination path from it, so the name never disagrees with the bytes. | ||
| 66 | + pub fn ext(self) -> &'static str { | ||
| 67 | + match self { | ||
| 68 | + Self::Mp4 => "mp4", | ||
| 69 | + Self::Wav => "wav", | ||
| 70 | + Self::Flac => "flac", | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + /// Whether this format carries the picture. The bitrate settings are video | ||
| 75 | + /// settings and mean nothing to the other two. | ||
| 76 | + pub fn has_video(self) -> bool { | ||
| 77 | + matches!(self, Self::Mp4) | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// What the caller gets to decide about the output. The codec is not among it: | ||
| 82 | +/// [`Format`] names a container *and* what goes in it, because every pair we | ||
| 83 | +/// can write is a pair we can also read back. | ||
| 43 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | 84 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 44 | pub struct ExportSettings { | 85 | pub struct ExportSettings { |
| 45 | /// Bits per second, clamped to the same sane range the automatic value uses. | 86 | /// Bits per second, clamped to the same sane range the automatic value uses. |
| 46 | - /// `None` picks it from the picture size and frame rate. | 87 | + /// `None` picks it from the picture size and frame rate. Video only. |
| 47 | pub bitrate: Option<u64>, | 88 | pub bitrate: Option<u64>, |
| 48 | /// Skip the hardware encoder even where it is available -- an escape hatch | 89 | /// Skip the hardware encoder even where it is available -- an escape hatch |
| 49 | /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin. | 90 | /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin. |
| 50 | pub force_sw: bool, | 91 | pub force_sw: bool, |
| 92 | + /// The file to write. Defaults to [`Format::Mp4`], which is what every | ||
| 93 | + /// caller wrote before there was a choice. | ||
| 94 | + pub format: Format, | ||
| 51 | } | 95 | } |
| 52 | 96 | ||
| 53 | struct Shared { | 97 | struct Shared { |
| @@ -118,8 +162,11 @@ pub fn start( | |||
| 118 | // The rename is the last step and the only one that publishes a file | 162 | // The rename is the last step and the only one that publishes a file |
| 119 | // under the name the caller asked for; it stays on the same directory, | 163 | // under the name the caller asked for; it stays on the same directory, |
| 120 | // so it is atomic. | 164 | // so it is atomic. |
| 121 | - let result = run(&project, &meta, &part, &worker, &settings) | 165 | + let written = match settings.format { |
| 122 | - .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); | 166 | + Format::Mp4 => run(&project, &meta, &part, &worker, &settings), |
| 167 | + format => run_audio(&project, &meta, &part, &worker, format), | ||
| 168 | + }; | ||
| 169 | + let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); | ||
| 123 | if result.is_err() { | 170 | if result.is_err() { |
| 124 | // The muxer -- and with it the file handle -- died with `run`. | 171 | // The muxer -- and with it the file handle -- died with `run`. |
| 125 | let _ = std::fs::remove_file(&part); | 172 | let _ = std::fs::remove_file(&part); |
| @@ -232,6 +279,127 @@ fn run( | |||
| 232 | Ok(()) | 279 | Ok(()) |
| 233 | } | 280 | } |
| 234 | 281 | ||
| 282 | +/// The audio lane alone, as a WAV or a FLAC. | ||
| 283 | +/// | ||
| 284 | +/// Nothing here re-derives the edit: the play list is | ||
| 285 | +/// [`Project::segments_from`] and it is handed to the very | ||
| 286 | +/// [`AudioSession::open_multi_streams`] playback feeds from, so what is written | ||
| 287 | +/// is what was heard -- gaps included, which arrive as real silence from that | ||
| 288 | +/// choke point rather than as a hole this would have to invent. | ||
| 289 | +/// | ||
| 290 | +/// The length is the *timeline's*: each segment resolves its window to whole | ||
| 291 | +/// samples on its own, so the sum can miss the timeline by a sample or two, and | ||
| 292 | +/// a source that runs out early would leave the file short. Both are settled by | ||
| 293 | +/// one `resize` at the end -- padding with silence, trimming what overshot -- | ||
| 294 | +/// so an exported file is exactly as long as what was edited. | ||
| 295 | +fn run_audio( | ||
| 296 | + project: &Project, | ||
| 297 | + meta: &VideoMeta, | ||
| 298 | + out: &Path, | ||
| 299 | + shared: &Shared, | ||
| 300 | + format: Format, | ||
| 301 | +) -> crate::Result<()> { | ||
| 302 | + let sources = project.audio_sources(); | ||
| 303 | + let segs = project.segments_from(0, meta.frame_rate); | ||
| 304 | + let Some((audio, chunks)) = AudioSession::open_multi_streams(&sources, &segs)? else { | ||
| 305 | + return Err("this timeline has no audio to export".into()); | ||
| 306 | + }; | ||
| 307 | + let channels = usize::from(audio.channels); | ||
| 308 | + let frames = (f64::from(project.timeline_frames()) / meta.frame_rate | ||
| 309 | + * f64::from(audio.sample_rate)) | ||
| 310 | + .round() as u64; | ||
| 311 | + let total = frames as usize * channels; | ||
| 312 | + // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB | ||
| 313 | + // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and | ||
| 314 | + // the mp4 path already collects its copied AAC track the same. Upgrade path | ||
| 315 | + // is hound's incremental writer plus flacenc's `Source` trait. | ||
| 316 | + let mut samples: Vec<i32> = Vec::with_capacity(total); | ||
| 317 | + for chunk in chunks { | ||
| 318 | + cancelled(shared)?; | ||
| 319 | + // ponytail: the per-segment EQ goes here -- `EqState::process` on this | ||
| 320 | + // same interleaved f32 buffer, before the quantisation below, which is | ||
| 321 | + // the point playback's feeder will call it from too. Not wired: the EQ | ||
| 322 | + // slice owns that, this is only the seat kept for it. | ||
| 323 | + samples.extend( | ||
| 324 | + chunk | ||
| 325 | + .samples | ||
| 326 | + .iter() | ||
| 327 | + .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32), | ||
| 328 | + ); | ||
| 329 | + let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1); | ||
| 330 | + shared.progress.store(done as u32, Ordering::Relaxed); | ||
| 331 | + } | ||
| 332 | + samples.resize(total, 0); | ||
| 333 | + // Written in one go and still cancellable up to here, exactly as the mp4 | ||
| 334 | + // path is up to its `finish`: the `.part` is what either gets renamed or | ||
| 335 | + // deleted. | ||
| 336 | + cancelled(shared)?; | ||
| 337 | + match format { | ||
| 338 | + Format::Wav => write_wav(out, &samples, &audio)?, | ||
| 339 | + Format::Flac => write_flac(out, &samples, &audio)?, | ||
| 340 | + Format::Mp4 => unreachable!("the mp4 path is `run`"), | ||
| 341 | + } | ||
| 342 | + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); | ||
| 343 | + Ok(()) | ||
| 344 | +} | ||
| 345 | + | ||
| 346 | +/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in | ||
| 347 | +/// this engine, so what the decoder handed over is what the header says. | ||
| 348 | +fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { | ||
| 349 | + let mut writer = hound::WavWriter::create( | ||
| 350 | + out, | ||
| 351 | + hound::WavSpec { | ||
| 352 | + channels: audio.channels, | ||
| 353 | + sample_rate: audio.sample_rate, | ||
| 354 | + bits_per_sample: 16, | ||
| 355 | + sample_format: hound::SampleFormat::Int, | ||
| 356 | + }, | ||
| 357 | + )?; | ||
| 358 | + for &sample in samples { | ||
| 359 | + writer.write_sample(sample as i16)?; | ||
| 360 | + } | ||
| 361 | + // Not `drop`: this is what rewrites the RIFF sizes in the header, and its | ||
| 362 | + // failure is the difference between a finished file and a truncated one. | ||
| 363 | + writer.finalize()?; | ||
| 364 | + Ok(()) | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to | ||
| 368 | +/// text: they are not `Send + Sync`, and every one of them fails the export the | ||
| 369 | +/// same way. | ||
| 370 | +fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { | ||
| 371 | + let config = flacenc::config::Encoder::default() | ||
| 372 | + .into_verified() | ||
| 373 | + .map_err(|(_, e)| format!("flac encoder config: {e}"))?; | ||
| 374 | + let source = flacenc::source::MemSource::from_samples( | ||
| 375 | + samples, | ||
| 376 | + usize::from(audio.channels), | ||
| 377 | + 16, | ||
| 378 | + audio.sample_rate as usize, | ||
| 379 | + ); | ||
| 380 | + let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size) | ||
| 381 | + .map_err(|e| format!("flac encode: {e}"))?; | ||
| 382 | + // The block sizes are stated fixed, which is what the frames themselves say | ||
| 383 | + // (they are numbered, not sample-addressed). flacenc's single-threaded path | ||
| 384 | + // instead writes the *last* frame's length as the minimum, and a short final | ||
| 385 | + // frame is the normal case -- a stream whose `streaminfo` then disagrees | ||
| 386 | + // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia, | ||
| 387 | + // which is this engine's own reader, rejects every frame header and reads | ||
| 388 | + // to EOF looking for a good one. Written this way the file reopens here, | ||
| 389 | + // which is the only test of an export that counts. (Same value flacenc's | ||
| 390 | + // own `par` path writes; the reference encoder does it too.) | ||
| 391 | + stream | ||
| 392 | + .stream_info_mut() | ||
| 393 | + .set_block_sizes(config.block_size, config.block_size) | ||
| 394 | + .map_err(|e| format!("flac block size: {e}"))?; | ||
| 395 | + let mut sink = flacenc::bitsink::ByteSink::new(); | ||
| 396 | + stream | ||
| 397 | + .write(&mut sink) | ||
| 398 | + .map_err(|e| format!("flac write: {e}"))?; | ||
| 399 | + std::fs::write(out, sink.as_slice())?; | ||
| 400 | + Ok(()) | ||
| 401 | +} | ||
| 402 | + | ||
| 235 | /// The I420 planes of one black picture, allocated once for a whole export: a | 403 | /// The I420 planes of one black picture, allocated once for a whole export: a |
| 236 | /// gap in the video lane is encoded, not skipped, or every frame after it would | 404 | /// gap in the video lane is encoded, not skipped, or every frame after it would |
| 237 | /// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention | 405 | /// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention |
crates/engine/tests/audio_export.rsadded+274 -0
| @@ -0,0 +1,274 @@ | |||
| 1 | +//! The timeline's audio written out on its own, as a WAV or a FLAC, and read | ||
| 2 | +//! straight back in through the engine's own reader — which is the check that | ||
| 3 | +//! matters: a file this program cannot reopen is a file it had no business | ||
| 4 | +//! writing. | ||
| 5 | +//! | ||
| 6 | +//! The fixtures carry a 1 Hz volume pulse (`gen_fixtures.sh`), so a second of | ||
| 7 | +//! exported audio has a measurable shape and not just a level: the pattern is | ||
| 8 | +//! asserted as a peak/dip *ratio*, never an absolute level, because ffmpeg's | ||
| 9 | +//! sine fixtures peak around 0.12. | ||
| 10 | +//! | ||
| 11 | +//! No picture is decoded anywhere here, so nothing needs the plugin and the | ||
| 12 | +//! whole file runs on any machine. | ||
| 13 | + | ||
| 14 | +use std::path::{Path, PathBuf}; | ||
| 15 | +use std::time::{Duration, Instant}; | ||
| 16 | + | ||
| 17 | +use engine::export::{ExportSettings, Format}; | ||
| 18 | +use engine::project::Source; | ||
| 19 | +use engine::{AudioSession, Clip, ExportHandle, Project}; | ||
| 20 | + | ||
| 21 | +const RATE: u32 = 44_100; | ||
| 22 | + | ||
| 23 | +fn asset(name: &str) -> PathBuf { | ||
| 24 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 25 | + .join("../../assets") | ||
| 26 | + .join(name) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Per-run unique, like the mp4 suite's: two suites at once must not delete | ||
| 30 | +/// each other's output. | ||
| 31 | +fn out_path(name: &str, ext: &str) -> PathBuf { | ||
| 32 | + let path = | ||
| 33 | + std::env::temp_dir().join(format!("ve_audio_{name}_{}.{ext}", std::process::id())); | ||
| 34 | + let _ = std::fs::remove_file(&path); | ||
| 35 | + let _ = std::fs::remove_file(part_path(&path)); | ||
| 36 | + path | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +fn part_path(out: &Path) -> PathBuf { | ||
| 40 | + PathBuf::from(format!("{}.part", out.display())) | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | ||
| 44 | + let started = Instant::now(); | ||
| 45 | + while !handle.is_finished() { | ||
| 46 | + assert!(started.elapsed() < limit, "export did not finish in {limit:?}"); | ||
| 47 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 48 | + } | ||
| 49 | + handle.result().expect("a finished export has an outcome") | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// One second of `test_av`, one second of hole, one second of `test_tone.mp3`. | ||
| 53 | +/// | ||
| 54 | +/// Three things at once: a cut, a gap (which must arrive as silence), and a | ||
| 55 | +/// source the mp4 export flatly refuses — there is no AAC encoder here, so an | ||
| 56 | +/// mp3 on the timeline can *only* leave through this door. | ||
| 57 | +fn mixed_project() -> Project { | ||
| 58 | + let clip = |start, source| Clip { | ||
| 59 | + start, | ||
| 60 | + in_frame: 0, | ||
| 61 | + out_frame: 30, | ||
| 62 | + source, | ||
| 63 | + link: None, | ||
| 64 | + }; | ||
| 65 | + Project::from_parts( | ||
| 66 | + vec![ | ||
| 67 | + Source::new(asset("test_av.mp4"), 0), | ||
| 68 | + Source::new(asset("test_tone.mp3"), 0), | ||
| 69 | + ], | ||
| 70 | + // The picture is beside the point here, but a project has two lanes and | ||
| 71 | + // the timeline's length is the longer of them: three seconds of video | ||
| 72 | + // is what makes the third second of audio part of the timeline. | ||
| 73 | + vec![Clip { | ||
| 74 | + start: 0, | ||
| 75 | + in_frame: 0, | ||
| 76 | + out_frame: 90, | ||
| 77 | + source: 0, | ||
| 78 | + link: None, | ||
| 79 | + }], | ||
| 80 | + vec![clip(0, 0), clip(60, 1)], | ||
| 81 | + ) | ||
| 82 | + .expect("a two-source project with a hole in the audio lane") | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +fn meta() -> engine::VideoMeta { | ||
| 86 | + engine::demux::Demuxer::open(&asset("test_av.mp4")) | ||
| 87 | + .expect("open test_av") | ||
| 88 | + .0 | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Interleaved samples of a written file, through the engine's own reader -- | ||
| 92 | +/// the same door an import comes in through, so a pass here means the export | ||
| 93 | +/// can be brought back into a timeline. | ||
| 94 | +fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) { | ||
| 95 | + let (meta, chunks) = AudioSession::open(path) | ||
| 96 | + .expect("reopen the export") | ||
| 97 | + .expect("the export has audio"); | ||
| 98 | + let mut samples = Vec::new(); | ||
| 99 | + for chunk in chunks { | ||
| 100 | + samples.extend(chunk.samples); | ||
| 101 | + } | ||
| 102 | + (meta, samples) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// Root mean square of `[from, to)` seconds of an interleaved stereo buffer. | ||
| 106 | +fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 { | ||
| 107 | + let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels; | ||
| 108 | + let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())]; | ||
| 109 | + assert!(!window.is_empty(), "no samples in [{from}, {to})"); | ||
| 110 | + (window.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / window.len() as f64).sqrt() | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// What every audio export must be, whatever encoded it: exactly as long as the | ||
| 114 | +/// timeline, silent where the timeline is empty, and audible where it is not -- | ||
| 115 | +/// with the fixtures' 1 Hz pulse still in it, which is what says the samples are | ||
| 116 | +/// the *edit's* and not just noise of the right length. | ||
| 117 | +fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) { | ||
| 118 | + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded"); | ||
| 119 | + let channels = usize::from(meta.channels); | ||
| 120 | + // Three seconds of timeline, to the sample: the segments round their own | ||
| 121 | + // windows and the mp3 need not end where the second does, so this is the | ||
| 122 | + // export's own trim/pad and not an accident of the sources. | ||
| 123 | + let frames = (3.0 * f64::from(RATE)) as usize; | ||
| 124 | + assert_eq!(samples.len(), frames * channels, "timeline length in samples"); | ||
| 125 | + | ||
| 126 | + // Second 0 is test_av, second 2 is the mp3; both carry the tone. | ||
| 127 | + let av = rms(samples, channels, 0.05, 0.95); | ||
| 128 | + let tone = rms(samples, channels, 2.05, 2.95); | ||
| 129 | + // Second 1 is the hole. Silence, not a stall and not a skip: it occupies | ||
| 130 | + // its full second, which is what the sample count above already proved. | ||
| 131 | + let gap = rms(samples, channels, 1.0, 2.0); | ||
| 132 | + println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}"); | ||
| 133 | + assert!(av > 0.01, "the first second is audible"); | ||
| 134 | + assert!(tone > 0.01, "the mp3 second is audible"); | ||
| 135 | + assert_eq!(gap, 0.0, "the gap is exact silence"); | ||
| 136 | + | ||
| 137 | + // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at | ||
| 138 | + // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level. | ||
| 139 | + let peak = rms(samples, channels, 0.2, 0.3); | ||
| 140 | + let dip = rms(samples, channels, 0.7, 0.8); | ||
| 141 | + println!("pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}", peak / dip); | ||
| 142 | + assert!( | ||
| 143 | + peak > dip * 4.0, | ||
| 144 | + "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}" | ||
| 145 | + ); | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// The RIFF header itself, byte for byte: hound writes it, but what a player | ||
| 149 | +/// reads is the bytes, and a wrong rate or a wrong `data` size is a file that | ||
| 150 | +/// decodes at the wrong speed rather than one that fails to open. | ||
| 151 | +fn assert_wav_header(path: &Path, frames: usize) { | ||
| 152 | + let bytes = std::fs::read(path).expect("read the wav back"); | ||
| 153 | + let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]); | ||
| 154 | + let u32_at = |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); | ||
| 155 | + assert_eq!(&bytes[0..4], b"RIFF"); | ||
| 156 | + assert_eq!(&bytes[8..12], b"WAVE"); | ||
| 157 | + assert_eq!(&bytes[12..16], b"fmt "); | ||
| 158 | + assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size"); | ||
| 159 | + assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag"); | ||
| 160 | + assert_eq!(u16_at(22), 2, "stereo"); | ||
| 161 | + assert_eq!(u32_at(24), RATE, "sample rate"); | ||
| 162 | + assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2"); | ||
| 163 | + assert_eq!(u16_at(32), 4, "block align"); | ||
| 164 | + assert_eq!(u16_at(34), 16, "bits per sample"); | ||
| 165 | + // The `data` chunk carries every sample and nothing else. hound may write a | ||
| 166 | + // `fact` chunk first, so it is found rather than assumed to be at 36. | ||
| 167 | + let data = bytes | ||
| 168 | + .windows(4) | ||
| 169 | + .position(|w| w == b"data") | ||
| 170 | + .expect("a data chunk"); | ||
| 171 | + assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size"); | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +#[test] | ||
| 175 | +fn exports_the_timeline_as_a_wav() { | ||
| 176 | + let out = out_path("wav", "wav"); | ||
| 177 | + let handle = engine::export::start( | ||
| 178 | + mixed_project(), | ||
| 179 | + meta(), | ||
| 180 | + &out, | ||
| 181 | + &ExportSettings { | ||
| 182 | + format: Format::Wav, | ||
| 183 | + ..Default::default() | ||
| 184 | + }, | ||
| 185 | + ); | ||
| 186 | + wait(&handle, Duration::from_secs(60)).expect("wav export"); | ||
| 187 | + assert_eq!(handle.progress(), 1.0, "finished at full progress"); | ||
| 188 | + assert!(!part_path(&out).exists(), "the .part was renamed away"); | ||
| 189 | + | ||
| 190 | + let (meta, samples) = decode(&out); | ||
| 191 | + assert_timeline_shape(&meta, &samples); | ||
| 192 | + assert_wav_header(&out, samples.len() / usize::from(meta.channels)); | ||
| 193 | + std::fs::remove_file(&out).unwrap(); | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +#[test] | ||
| 197 | +fn exports_the_timeline_as_a_flac() { | ||
| 198 | + let out = out_path("flac", "flac"); | ||
| 199 | + let handle = engine::export::start( | ||
| 200 | + mixed_project(), | ||
| 201 | + meta(), | ||
| 202 | + &out, | ||
| 203 | + &ExportSettings { | ||
| 204 | + format: Format::Flac, | ||
| 205 | + ..Default::default() | ||
| 206 | + }, | ||
| 207 | + ); | ||
| 208 | + wait(&handle, Duration::from_secs(60)).expect("flac export"); | ||
| 209 | + assert_eq!(handle.progress(), 1.0, "finished at full progress"); | ||
| 210 | + | ||
| 211 | + let bytes = std::fs::read(&out).expect("read the flac back"); | ||
| 212 | + assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic"); | ||
| 213 | + // Lossless is a claim about the samples, so it is checked on the samples: | ||
| 214 | + // the same shape the WAV of the same timeline has. | ||
| 215 | + let (meta, samples) = decode(&out); | ||
| 216 | + assert_timeline_shape(&meta, &samples); | ||
| 217 | + // Smaller than the PCM it encodes, or the whole point of the row is gone. | ||
| 218 | + let pcm = samples.len() * 2; | ||
| 219 | + println!("flac {} bytes for {pcm} bytes of PCM", bytes.len()); | ||
| 220 | + assert!(bytes.len() < pcm, "compressed"); | ||
| 221 | + std::fs::remove_file(&out).unwrap(); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// Cancel leaves nothing behind -- not the output, not the `.part`. The | ||
| 225 | +/// timeline is long enough (a minute of audio) that the escape lands mid-decode | ||
| 226 | +/// rather than after the file is already closed. | ||
| 227 | +#[test] | ||
| 228 | +fn a_cancelled_audio_export_leaves_no_file() { | ||
| 229 | + let source = asset("test_av.mp4"); | ||
| 230 | + let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av"); | ||
| 231 | + let mut project = Project::single(&source, meta.frame_count); | ||
| 232 | + for _ in 0..11 { | ||
| 233 | + assert!(project.append_clip(0, meta.frame_count), "a minute of it"); | ||
| 234 | + } | ||
| 235 | + let out = out_path("cancel", "wav"); | ||
| 236 | + let handle = engine::export::start( | ||
| 237 | + project, | ||
| 238 | + meta, | ||
| 239 | + &out, | ||
| 240 | + &ExportSettings { | ||
| 241 | + format: Format::Wav, | ||
| 242 | + ..Default::default() | ||
| 243 | + }, | ||
| 244 | + ); | ||
| 245 | + handle.cancel(); | ||
| 246 | + let outcome = wait(&handle, Duration::from_secs(120)); | ||
| 247 | + let text = outcome.expect_err("a cancelled export fails").to_string(); | ||
| 248 | + assert!(text.contains("cancelled"), "{text}"); | ||
| 249 | + assert!(!out.exists(), "no output file"); | ||
| 250 | + assert!(!part_path(&out).exists(), "no half-written .part either"); | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// A silent timeline cannot become an audio file, and says so rather than | ||
| 254 | +/// writing zero samples that a user would take for a broken microphone. | ||
| 255 | +#[test] | ||
| 256 | +fn a_silent_timeline_refuses_an_audio_export() { | ||
| 257 | + let source = asset("test_mismatch.mp4"); // video only, no audio track | ||
| 258 | + let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); | ||
| 259 | + let out = out_path("silent", "wav"); | ||
| 260 | + let handle = engine::export::start( | ||
| 261 | + Project::single(&source, meta.frame_count), | ||
| 262 | + meta, | ||
| 263 | + &out, | ||
| 264 | + &ExportSettings { | ||
| 265 | + format: Format::Wav, | ||
| 266 | + ..Default::default() | ||
| 267 | + }, | ||
| 268 | + ); | ||
| 269 | + let text = wait(&handle, Duration::from_secs(60)) | ||
| 270 | + .expect_err("no audio to export") | ||
| 271 | + .to_string(); | ||
| 272 | + assert!(text.contains("no audio"), "{text}"); | ||
| 273 | + assert!(!out.exists() && !part_path(&out).exists(), "nothing written"); | ||
| 274 | +} | ||
crates/engine/tests/export.rsmodified+1 -0
| @@ -374,6 +374,7 @@ fn a_higher_bitrate_writes_a_bigger_file() { | |||
| 374 | let settings = ExportSettings { | 374 | let settings = ExportSettings { |
| 375 | bitrate: Some(bitrate), | 375 | bitrate: Some(bitrate), |
| 376 | force_sw: true, | 376 | force_sw: true, |
| 377 | + ..Default::default() | ||
| 377 | }; | 378 | }; |
| 378 | let handle = session.export_to_with(&out, &settings); | 379 | let handle = session.export_to_with(&out, &settings); |
| 379 | wait(&handle, Duration::from_secs(180)).expect("export"); | 380 | wait(&handle, Duration::from_secs(180)).expect("export"); |