🔀 merge: origin/main into E1, and the Sound row becomes a choice list
Browse files at this commit30 changed files +5740 -1062
- Cargo.lock +89 -0
- Cargo.toml +4 -1
- crates/app/src/keymap.rs +41 -5
- crates/app/src/main.rs +2965 -738
- crates/engine-hw/src/lib.rs +4 -3
- crates/engine/Cargo.toml +10 -0
- crates/engine/src/audio.rs +381 -90
- crates/engine/src/demux.rs +464 -50
- crates/engine/src/edith.rs +167 -24
- crates/engine/src/lib.rs +1 -0
- crates/engine/src/playback.rs +118 -28
- crates/engine/src/project.rs +38 -0
- crates/engine/src/subtitle.rs +344 -0
- crates/engine/src/waveform.rs +39 -4
- crates/engine/tests/audio_decode.rs +134 -0
- crates/engine/tests/audio_export.rs +61 -0
- crates/engine/tests/audio_multi.rs +67 -7
- crates/engine/tests/av1.rs +64 -6
- crates/engine/tests/data/test_subs.ass +14 -0
- crates/engine/tests/data/test_subs.srt +12 -0
- crates/engine/tests/h264_mkv.rs +149 -0
- crates/engine/tests/hevc.rs +83 -6
- crates/engine/tests/lanes.rs +9 -4
- crates/engine/tests/playback.rs +60 -25
- crates/engine/tests/saveload.rs +14 -11
- crates/engine/tests/silence.rs +2 -1
- crates/engine/tests/subtitles.rs +237 -0
- crates/engine/tests/vp9.rs +22 -6
- scripts/gen_fixtures.sh +60 -4
- vendor/rusty_aac/src/dsp.rs +87 -49
Cargo.lockmodified+89 -0
| @@ -1003,6 +1003,12 @@ dependencies = [ | |||
| 1003 | "thiserror 2.0.20", | 1003 | "thiserror 2.0.20", |
| 1004 | ] | 1004 | ] |
| 1005 | 1005 | ||
| 1006 | +[[package]] | ||
| 1007 | +name = "compcol" | ||
| 1008 | +version = "0.6.8" | ||
| 1009 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1010 | +checksum = "28b37ce533aa0fddc1e6820e331968ba72aa48b5c8bbb2bebdc03d48b6ed0f16" | ||
| 1011 | + | ||
| 1006 | [[package]] | 1012 | [[package]] |
| 1007 | name = "compression-codecs" | 1013 | name = "compression-codecs" |
| 1008 | version = "0.4.38" | 1014 | version = "0.4.38" |
| @@ -1636,8 +1642,10 @@ dependencies = [ | |||
| 1636 | "libloading", | 1642 | "libloading", |
| 1637 | "mp4", | 1643 | "mp4", |
| 1638 | "oxideav-ac3", | 1644 | "oxideav-ac3", |
| 1645 | + "oxideav-ass", | ||
| 1639 | "oxideav-core", | 1646 | "oxideav-core", |
| 1640 | "oxideav-h265", | 1647 | "oxideav-h265", |
| 1648 | + "oxideav-subtitle", | ||
| 1641 | "rav1e", | 1649 | "rav1e", |
| 1642 | "rusty_aac", | 1650 | "rusty_aac", |
| 1643 | "rusty_h264", | 1651 | "rusty_h264", |
| @@ -3940,6 +3948,16 @@ dependencies = [ | |||
| 3940 | "oxideav-core", | 3948 | "oxideav-core", |
| 3941 | ] | 3949 | ] |
| 3942 | 3950 | ||
| 3951 | +[[package]] | ||
| 3952 | +name = "oxideav-ass" | ||
| 3953 | +version = "0.0.9" | ||
| 3954 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3955 | +checksum = "b9d5a10750f54eb6913bf3ca295d17899006c9a9c6c94970741a5a7c0c49e3fa" | ||
| 3956 | +dependencies = [ | ||
| 3957 | + "oxideav-core", | ||
| 3958 | + "oxideav-subtitle", | ||
| 3959 | +] | ||
| 3960 | + | ||
| 3943 | [[package]] | 3961 | [[package]] |
| 3944 | name = "oxideav-core" | 3962 | name = "oxideav-core" |
| 3945 | version = "0.1.34" | 3963 | version = "0.1.34" |
| @@ -3958,6 +3976,77 @@ dependencies = [ | |||
| 3958 | "oxideav-core", | 3976 | "oxideav-core", |
| 3959 | ] | 3977 | ] |
| 3960 | 3978 | ||
| 3979 | +[[package]] | ||
| 3980 | +name = "oxideav-otf" | ||
| 3981 | +version = "0.1.3" | ||
| 3982 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3983 | +checksum = "571c56414ce3138d3a4e7c833b402b3c69a96db707f54abd0f1ad85f3d5d1a0b" | ||
| 3984 | +dependencies = [ | ||
| 3985 | + "oxideav-core", | ||
| 3986 | +] | ||
| 3987 | + | ||
| 3988 | +[[package]] | ||
| 3989 | +name = "oxideav-pixfmt" | ||
| 3990 | +version = "0.1.7" | ||
| 3991 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3992 | +checksum = "868d5cd1d9cf3f4d527241b6ed85fcd628c65e303fe4efb2998e4d6104c7ce4b" | ||
| 3993 | +dependencies = [ | ||
| 3994 | + "oxideav-core", | ||
| 3995 | +] | ||
| 3996 | + | ||
| 3997 | +[[package]] | ||
| 3998 | +name = "oxideav-png" | ||
| 3999 | +version = "0.1.8" | ||
| 4000 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4001 | +checksum = "c78483db4263204f6f9e2e63354b45f0fe2f83e0e08282f68c8a9647d537fa1f" | ||
| 4002 | +dependencies = [ | ||
| 4003 | + "compcol", | ||
| 4004 | + "oxideav-core", | ||
| 4005 | +] | ||
| 4006 | + | ||
| 4007 | +[[package]] | ||
| 4008 | +name = "oxideav-raster" | ||
| 4009 | +version = "0.1.2" | ||
| 4010 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4011 | +checksum = "41beead01c28b23e6e997e8b2d3a38bb1b53cd37b6e8a72a10befa2fb57a6e06" | ||
| 4012 | +dependencies = [ | ||
| 4013 | + "oxideav-core", | ||
| 4014 | + "oxideav-pixfmt", | ||
| 4015 | +] | ||
| 4016 | + | ||
| 4017 | +[[package]] | ||
| 4018 | +name = "oxideav-scribe" | ||
| 4019 | +version = "0.1.9" | ||
| 4020 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4021 | +checksum = "a9aec36b356861de9e0e660a7990f14b428476638f7b2ba902c0cd7e1ffdac39" | ||
| 4022 | +dependencies = [ | ||
| 4023 | + "oxideav-core", | ||
| 4024 | + "oxideav-otf", | ||
| 4025 | + "oxideav-png", | ||
| 4026 | + "oxideav-ttf", | ||
| 4027 | +] | ||
| 4028 | + | ||
| 4029 | +[[package]] | ||
| 4030 | +name = "oxideav-subtitle" | ||
| 4031 | +version = "0.1.2" | ||
| 4032 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4033 | +checksum = "88e41289024a95ea82051cd18af77885afd7be3c23a38255cb1edbe49872273a" | ||
| 4034 | +dependencies = [ | ||
| 4035 | + "oxideav-core", | ||
| 4036 | + "oxideav-pixfmt", | ||
| 4037 | + "oxideav-raster", | ||
| 4038 | + "oxideav-scribe", | ||
| 4039 | +] | ||
| 4040 | + | ||
| 4041 | +[[package]] | ||
| 4042 | +name = "oxideav-ttf" | ||
| 4043 | +version = "0.1.7" | ||
| 4044 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4045 | +checksum = "c44d45518f6f4d749d2bf2c7cb3622fdb7ccc6147457545ed36aa8d241adea8e" | ||
| 4046 | +dependencies = [ | ||
| 4047 | + "oxideav-core", | ||
| 4048 | +] | ||
| 4049 | + | ||
| 3961 | [[package]] | 4050 | [[package]] |
| 3962 | name = "parking" | 4051 | name = "parking" |
| 3963 | version = "2.2.1" | 4052 | version = "2.2.1" |
Cargo.tomlmodified+4 -1
| @@ -23,7 +23,10 @@ edition = "2024" | |||
| 23 | # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per | 23 | # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per |
| 24 | # term (the fast path in the same file serves the encoder only), | 24 | # term (the fast path in the same file serves the encoder only), |
| 25 | # which is 4x slower than real time for 5.1 and therefore not | 25 | # which is 4x slower than real time for 5.1 and therefore not |
| 26 | -# playable at all; the patch caches the cosine matrix | 26 | +# playable at all; the patch routes the IMDCT through the same |
| 27 | +# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`), | ||
| 28 | +# 40x the matrix version it started as -- 2 hours of 5.1 for a | ||
| 29 | +# waveform in 2.4 minutes rather than an hour | ||
| 27 | # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and | 30 | # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and |
| 28 | # refuses any dimension that is not a multiple of the 16-sample | 31 | # refuses any dimension that is not a multiple of the 16-sample |
| 29 | # CTB, so 1920x1080 could not be written at all; the patch adds | 32 | # CTB, so 1920x1080 could not be written at all; the patch adds |
crates/app/src/keymap.rsmodified+41 -5
| @@ -78,13 +78,14 @@ pub enum ActionId { | |||
| 78 | Speed, | 78 | Speed, |
| 79 | Silence, | 79 | Silence, |
| 80 | Mix, | 80 | Mix, |
| 81 | + ToggleSnap, | ||
| 81 | CancelExport, | 82 | CancelExport, |
| 82 | } | 83 | } |
| 83 | 84 | ||
| 84 | impl ActionId { | 85 | impl ActionId { |
| 85 | /// Display order everywhere -- the editor lists them in it and | 86 | /// Display order everywhere -- the editor lists them in it and |
| 86 | /// [`Keymap::defaults`] binds them in it. | 87 | /// [`Keymap::defaults`] binds them in it. |
| 87 | - pub const ALL: [ActionId; 39] = [ | 88 | + pub const ALL: [ActionId; 40] = [ |
| 88 | ActionId::Play, | 89 | ActionId::Play, |
| 89 | ActionId::StepBack, | 90 | ActionId::StepBack, |
| 90 | ActionId::StepForward, | 91 | ActionId::StepForward, |
| @@ -123,6 +124,7 @@ impl ActionId { | |||
| 123 | ActionId::Speed, | 124 | ActionId::Speed, |
| 124 | ActionId::Silence, | 125 | ActionId::Silence, |
| 125 | ActionId::Mix, | 126 | ActionId::Mix, |
| 127 | + ActionId::ToggleSnap, | ||
| 126 | ActionId::CancelExport, | 128 | ActionId::CancelExport, |
| 127 | ]; | 129 | ]; |
| 128 | 130 | ||
| @@ -167,6 +169,7 @@ impl ActionId { | |||
| 167 | ActionId::Speed => "Speed (tape)…", | 169 | ActionId::Speed => "Speed (tape)…", |
| 168 | ActionId::Silence => "Silences: cut or speed up…", | 170 | ActionId::Silence => "Silences: cut or speed up…", |
| 169 | ActionId::Mix => "Mix: track volumes and the limiter…", | 171 | ActionId::Mix => "Mix: track volumes and the limiter…", |
| 172 | + ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)", | ||
| 170 | ActionId::CancelExport => "Cancel export", | 173 | ActionId::CancelExport => "Cancel export", |
| 171 | } | 174 | } |
| 172 | } | 175 | } |
| @@ -213,6 +216,7 @@ impl ActionId { | |||
| 213 | ActionId::Speed => "speed", | 216 | ActionId::Speed => "speed", |
| 214 | ActionId::Silence => "silence", | 217 | ActionId::Silence => "silence", |
| 215 | ActionId::Mix => "mix", | 218 | ActionId::Mix => "mix", |
| 219 | + ActionId::ToggleSnap => "toggle-snap", | ||
| 216 | ActionId::CancelExport => "cancel-export", | 220 | ActionId::CancelExport => "cancel-export", |
| 217 | } | 221 | } |
| 218 | } | 222 | } |
| @@ -265,6 +269,9 @@ impl ActionId { | |||
| 265 | | ActionId::AddVideoLane | 269 | | ActionId::AddVideoLane |
| 266 | | ActionId::AddAudioLane | 270 | | ActionId::AddAudioLane |
| 267 | | ActionId::RemoveVideoLane | 271 | | ActionId::RemoveVideoLane |
| 272 | + // Not a view setting despite being a pointer aid: it decides where | ||
| 273 | + // a drag actually lands, which is an edit and not a magnification. | ||
| 274 | + | ActionId::ToggleSnap | ||
| 268 | | ActionId::RemoveAudioLane => Category::Editing, | 275 | | ActionId::RemoveAudioLane => Category::Editing, |
| 269 | ActionId::ToggleMute | 276 | ActionId::ToggleMute |
| 270 | | ActionId::VolumeUp | 277 | | ActionId::VolumeUp |
| @@ -326,7 +333,7 @@ pub struct Fixed { | |||
| 326 | pub category: Category, | 333 | pub category: Category, |
| 327 | } | 334 | } |
| 328 | 335 | ||
| 329 | -pub const FIXED: [Fixed; 22] = [ | 336 | +pub const FIXED: [Fixed; 27] = [ |
| 330 | // Not a chord at all but a way of pressing one, and the only place the | 337 | // Not a chord at all but a way of pressing one, and the only place the |
| 331 | // editor can say so: holding a key that moves a *value* runs it, and | 338 | // editor can say so: holding a key that moves a *value* runs it, and |
| 332 | // holding anything else still does what one press did. | 339 | // holding anything else still does what one press did. |
| @@ -399,7 +406,7 @@ pub const FIXED: [Fixed; 22] = [ | |||
| 399 | // its own: a band nothing but a drag can reach is a band half the users of | 406 | // its own: a band nothing but a drag can reach is a band half the users of |
| 400 | // this editor cannot move at all. Card-local, so none of them is bindable. | 407 | // this editor cannot move at all. Card-local, so none of them is bindable. |
| 401 | Fixed { | 408 | Fixed { |
| 402 | - chord: "1–5", | 409 | + chord: "1–9, 0", |
| 403 | label: "Pick an equalizer band", | 410 | label: "Pick an equalizer band", |
| 404 | category: Category::Audio, | 411 | category: Category::Audio, |
| 405 | }, | 412 | }, |
| @@ -413,6 +420,31 @@ pub const FIXED: [Fixed; 22] = [ | |||
| 413 | label: "Lower the picked band 1 dB", | 420 | label: "Lower the picked band 1 dB", |
| 414 | category: Category::Audio, | 421 | category: Category::Audio, |
| 415 | }, | 422 | }, |
| 423 | + Fixed { | ||
| 424 | + chord: "← / →", | ||
| 425 | + label: "Move the picked band down or up in frequency", | ||
| 426 | + category: Category::Audio, | ||
| 427 | + }, | ||
| 428 | + Fixed { | ||
| 429 | + chord: "shift ← / →", | ||
| 430 | + label: "Widen or narrow the picked band (its Q)", | ||
| 431 | + category: Category::Audio, | ||
| 432 | + }, | ||
| 433 | + Fixed { | ||
| 434 | + chord: "a", | ||
| 435 | + label: "Add an equalizer band beside the picked one", | ||
| 436 | + category: Category::Audio, | ||
| 437 | + }, | ||
| 438 | + Fixed { | ||
| 439 | + chord: "x", | ||
| 440 | + label: "Remove the picked equalizer band", | ||
| 441 | + category: Category::Audio, | ||
| 442 | + }, | ||
| 443 | + Fixed { | ||
| 444 | + chord: "f", | ||
| 445 | + label: "Flatten the picked band (double-click does the same)", | ||
| 446 | + category: Category::Audio, | ||
| 447 | + }, | ||
| 416 | Fixed { | 448 | Fixed { |
| 417 | chord: "r", | 449 | chord: "r", |
| 418 | label: "Flatten every band", | 450 | label: "Flatten every band", |
| @@ -650,6 +682,9 @@ impl Keymap { | |||
| 650 | // machine's volume and not the project's -- two things one key | 682 | // machine's volume and not the project's -- two things one key |
| 651 | // must not mean. | 683 | // must not mean. |
| 652 | b(ActionId::Mix, "f", false), | 684 | b(ActionId::Mix, "f", false), |
| 685 | + // The snap takes "n", which is what every other editor toggles | ||
| 686 | + // it with: free here, and nowhere near the two keys that delete. | ||
| 687 | + b(ActionId::ToggleSnap, "n", false), | ||
| 653 | b(ActionId::CancelExport, "escape", false), | 688 | b(ActionId::CancelExport, "escape", false), |
| 654 | ], | 689 | ], |
| 655 | } | 690 | } |
| @@ -912,7 +947,7 @@ mod tests { | |||
| 912 | #[test] | 947 | #[test] |
| 913 | fn every_default_stroke_reaches_its_action() { | 948 | fn every_default_stroke_reaches_its_action() { |
| 914 | let k = Keymap::defaults(); | 949 | let k = Keymap::defaults(); |
| 915 | - assert_eq!(k.entries().len(), 41); | 950 | + assert_eq!(k.entries().len(), 42); |
| 916 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); | 951 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); |
| 917 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two | 952 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two |
| 918 | // ends of the timeline. | 953 | // ends of the timeline. |
| @@ -1146,7 +1181,8 @@ mod tests { | |||
| 1146 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); | 1181 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); |
| 1147 | // The label is the editor's column, and never the file's word for it. | 1182 | // The label is the editor's column, and never the file's word for it. |
| 1148 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); | 1183 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); |
| 1149 | - assert_eq!(ActionId::ALL.len(), 39); | 1184 | + assert_eq!(ActionId::ALL.len(), 40); |
| 1185 | + assert_eq!(k.display(ActionId::ToggleSnap), "n"); | ||
| 1150 | assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); | 1186 | assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); |
| 1151 | } | 1187 | } |
| 1152 | 1188 | ||
crates/app/src/main.rsmodified+2965 -738
Diff too large; view file
| @@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed}; | |||
| 19 | use engine::scale::FitPolicy; | 19 | use engine::scale::FitPolicy; |
| 20 | use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; | 20 | use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; |
| 21 | use gpui::{ | 21 | use gpui::{ |
| 22 | - AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, | 22 | + AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent, |
| 23 | - KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, | 23 | + FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, |
| 24 | - Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, | 24 | + PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, |
| 25 | - TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, | 25 | + Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, |
| 26 | - relative, rgb, rgba, size, | 26 | + point, prelude::*, px, relative, rgb, rgba, size, |
| 27 | }; | 27 | }; |
| 28 | 28 | ||
| 29 | /// Editor chrome: three grays and one accent, all darker than the picture so the | 29 | /// Editor chrome: three grays and one accent, all darker than the picture so the |
| @@ -85,6 +85,13 @@ const WAVE_BPS: u32 = 40; | |||
| 85 | /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, | 85 | /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, |
| 86 | /// and a path with a point per pixel is a path per repaint. | 86 | /// and a path with a point per pixel is a path per repaint. |
| 87 | const WAVE_COL: f32 = 2.; | 87 | const WAVE_COL: f32 = 2.; |
| 88 | +/// The most columns one envelope is ever built from. A waveform is drawn into | ||
| 89 | +/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a | ||
| 90 | +/// screen wide, so nothing on screen ever reaches this -- it is the backstop for | ||
| 91 | +/// a box laid out wider than any screen, whose path would otherwise cost a point | ||
| 92 | +/// per two pixels of a width nobody can see and stall the repaint that was | ||
| 93 | +/// meant to draw the wave. | ||
| 94 | +const WAVE_COLS_MAX: usize = 4096; | ||
| 88 | /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px | 95 | /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px |
| 89 | /// to look at -- `RULER_HIT_H` is the strip that has to be hit. | 96 | /// to look at -- `RULER_HIT_H` is the strip that has to be hit. |
| 90 | const HIT_MIN: f32 = 24.; | 97 | const HIT_MIN: f32 = 24.; |
| @@ -260,6 +267,10 @@ enum Wave { | |||
| 260 | Loading, | 267 | Loading, |
| 261 | /// The file has no audio track. An answer, not a miss. | 268 | /// The file has no audio track. An answer, not a miss. |
| 262 | Silent, | 269 | Silent, |
| 270 | + /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: | ||
| 271 | + /// "this file's sound could not be read" and "this file has no sound" look | ||
| 272 | + /// the same on a lane, and the first is a bug report waiting to happen. | ||
| 273 | + Failed, | ||
| 263 | Peaks(Arc<Vec<(f32, f32)>>), | 274 | Peaks(Arc<Vec<(f32, f32)>>), |
| 264 | } | 275 | } |
| 265 | 276 | ||
| @@ -277,6 +288,13 @@ struct AssetDrag(PathBuf, usize); | |||
| 277 | struct ClipDrag { | 288 | struct ClipDrag { |
| 278 | lane: Lane, | 289 | lane: Lane, |
| 279 | idx: usize, | 290 | idx: usize, |
| 291 | + /// The clip that was picked up, so the drop can find it again: gpui freezes | ||
| 292 | + /// the payload for the whole gesture, and an edit made *during* one -- a | ||
| 293 | + /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples | ||
| 294 | + /// the indices under it. The index alone would then name a different take at | ||
| 295 | + /// the release, and the drag would move a clip nobody touched (see | ||
| 296 | + /// [`live_idx`]). | ||
| 297 | + clip: Clip, | ||
| 280 | } | 298 | } |
| 281 | 299 | ||
| 282 | /// A clip edge being dragged: which end of which clip, and the timeline frame | 300 | /// A clip edge being dragged: which end of which clip, and the timeline frame |
| @@ -335,6 +353,42 @@ struct LibraryMenu { | |||
| 335 | details: bool, | 353 | details: bool, |
| 336 | } | 354 | } |
| 337 | 355 | ||
| 356 | +/// An open choice list: which setting it offers and where it hangs. What a | ||
| 357 | +/// button that stepped one value on per click used to be -- a setting with more | ||
| 358 | +/// than two values is a list to look at, not a thing to click round. Placed by | ||
| 359 | +/// [`menu_at`] and closed by a stroke, exactly like the two menus above it. | ||
| 360 | +#[derive(Clone, Copy, PartialEq)] | ||
| 361 | +struct Picker { | ||
| 362 | + of: Pick, | ||
| 363 | + at: Point<Pixels>, | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +/// Which setting an open list is offering. The fit policy names the clip it is | ||
| 367 | +/// about, like the clip menu it opens from -- indices move under every edit, so | ||
| 368 | +/// the list closes on the first stroke as that menu does. | ||
| 369 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 370 | +enum Pick { | ||
| 371 | + Resolution, | ||
| 372 | + Fit(Lane, usize), | ||
| 373 | + /// What the export's *sound* is coded at. Opened from the card's Sound row, | ||
| 374 | + /// which is the only place it means anything. | ||
| 375 | + AudioRate, | ||
| 376 | +} | ||
| 377 | + | ||
| 378 | +/// One value a list offers, carrying everything picking it needs -- so a click | ||
| 379 | +/// goes straight to the value rather than to a position in a list that was | ||
| 380 | +/// built somewhere else. | ||
| 381 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 382 | +enum Choice { | ||
| 383 | + Size(u32, u32), | ||
| 384 | + Fit(Lane, usize, FitPolicy), | ||
| 385 | + AudioRate(u32), | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +/// One row of an open list: the value, its name, the small print beside it, and | ||
| 389 | +/// whether it is the one in force. | ||
| 390 | +type ChoiceRow = (Choice, SharedString, SharedString, bool); | ||
| 391 | + | ||
| 338 | /// What a library row's menu offers, in the order it lists them. Unlike the clip | 392 | /// What a library row's menu offers, in the order it lists them. Unlike the clip |
| 339 | /// menu's items none of these is a stroke -- there is no keyboard way to a row -- | 393 | /// menu's items none of these is a stroke -- there is no keyboard way to a row -- |
| 340 | /// so the label and the hint are written here rather than read off the keymap. | 394 | /// so the label and the hint are written here rather than read off the keymap. |
| @@ -402,6 +456,47 @@ const MENU_ITEMS: [ActionId; 14] = [ | |||
| 402 | ActionId::ToggleMute, | 456 | ActionId::ToggleMute, |
| 403 | ]; | 457 | ]; |
| 404 | 458 | ||
| 459 | +/// One row of the actions card, in the order it lists them: a heading, then | ||
| 460 | +/// every action the registry files under it, then the strokes the modal cards | ||
| 461 | +/// answer themselves. | ||
| 462 | +/// | ||
| 463 | +/// A list rather than a loop inside the render, so the card and | ||
| 464 | +/// `every_action_is_on_the_actions_card` read the *same* order: an action that | ||
| 465 | +/// reaches no row fails a test instead of quietly becoming pointer-unreachable. | ||
| 466 | +enum KeyRow { | ||
| 467 | + Head(keymap::Category), | ||
| 468 | + /// Click its label to do it, click its stroke to change that stroke. | ||
| 469 | + Act(ActionId), | ||
| 470 | + /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may | ||
| 471 | + /// unbind the way out of a card. | ||
| 472 | + Fixed(usize), | ||
| 473 | +} | ||
| 474 | + | ||
| 475 | +/// Every action, under its heading, and the card-local strokes beside them. | ||
| 476 | +/// Generated from the registry -- [`ActionId::ALL`] in its own order, under | ||
| 477 | +/// [`keymap::Category::ALL`] -- so an action added there is on the card the | ||
| 478 | +/// moment it exists and there is no second list here to forget. | ||
| 479 | +fn keys_rows() -> Vec<KeyRow> { | ||
| 480 | + let mut rows = Vec::new(); | ||
| 481 | + for category in keymap::Category::ALL { | ||
| 482 | + rows.push(KeyRow::Head(category)); | ||
| 483 | + rows.extend( | ||
| 484 | + ActionId::ALL | ||
| 485 | + .into_iter() | ||
| 486 | + .filter(|a| a.category() == category) | ||
| 487 | + .map(KeyRow::Act), | ||
| 488 | + ); | ||
| 489 | + rows.extend( | ||
| 490 | + keymap::FIXED | ||
| 491 | + .iter() | ||
| 492 | + .enumerate() | ||
| 493 | + .filter(|(_, f)| f.category == category) | ||
| 494 | + .map(|(i, _)| KeyRow::Fixed(i)), | ||
| 495 | + ); | ||
| 496 | + } | ||
| 497 | + rows | ||
| 498 | +} | ||
| 499 | + | ||
| 405 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. | 500 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. |
| 406 | /// A short list of the sizes people name; the media's own is cycled in beside | 501 | /// A short list of the sizes people name; the media's own is cycled in beside |
| 407 | /// them, which is what makes the trip round come back to where it started. | 502 | /// them, which is what makes the trip round come back to where it started. |
| @@ -524,6 +619,36 @@ const EQ_FREQ_HIGH: f32 = 20_000.; | |||
| 524 | /// and short enough that the card still fits a 360 px window. | 619 | /// and short enough that the card still fits a 360 px window. |
| 525 | const EQ_GRAPH_H: f32 = 132.; | 620 | const EQ_GRAPH_H: f32 = 132.; |
| 526 | 621 | ||
| 622 | +/// How wide the equalizer card is allowed to get. It is the one card that is a | ||
| 623 | +/// *graph*: every pixel across is frequency resolution, and at the 320 px the | ||
| 624 | +/// other cards use, a third of an octave was a couple of pixels. Past this the | ||
| 625 | +/// curve stops gaining anything and the card starts reading as a wall. | ||
| 626 | +const EQ_W_MAX: f32 = 720.; | ||
| 627 | + | ||
| 628 | +/// The gap the card leaves either side of it, so it reads as a card on a scrim | ||
| 629 | +/// rather than as a second window: it takes the width it can get inside that. | ||
| 630 | +const EQ_W_MARGIN: f32 = 32.; | ||
| 631 | + | ||
| 632 | +/// How many bands one clip's equalizer may carry from this card. Ten because | ||
| 633 | +/// the keyboard picks a band with a digit and a keyboard has ten of them -- | ||
| 634 | +/// past that a band would be reachable by pointer only. The engine itself caps | ||
| 635 | +/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more | ||
| 636 | +/// and this card will draw and edit every one it finds. | ||
| 637 | +const EQ_BANDS_MAX: usize = 10; | ||
| 638 | + | ||
| 639 | +/// One press of the frequency keys, as a factor: a sixth of an octave, so a | ||
| 640 | +/// band walks the whole axis in about sixty presses and still lands close | ||
| 641 | +/// enough to a named frequency to aim at one. | ||
| 642 | +const EQ_FREQ_STEP: f32 = 1.122_462; | ||
| 643 | + | ||
| 644 | +/// One press of the Q keys, as a factor, and the range they move in. Below the | ||
| 645 | +/// bottom a peak is barely a peak any more; above the top it is a whistle on | ||
| 646 | +/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside | ||
| 647 | +/// them, so nothing a file carries has to be dragged into range first. | ||
| 648 | +const EQ_Q_STEP: f32 = 1.25; | ||
| 649 | +const EQ_Q_LOW: f32 = 0.3; | ||
| 650 | +const EQ_Q_HIGH: f32 = 12.; | ||
| 651 | + | ||
| 527 | /// How many points the curve is drawn from. One per ~3 px across the card: | 652 | /// How many points the curve is drawn from. One per ~3 px across the card: |
| 528 | /// past that the line is smooth and the extra biquad evaluations are wasted. | 653 | /// past that the line is smooth and the extra biquad evaluations are wasted. |
| 529 | const EQ_CURVE_STEPS: usize = 96; | 654 | const EQ_CURVE_STEPS: usize = 96; |
| @@ -572,6 +697,11 @@ const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; | |||
| 572 | /// its weight: it is what makes a boost read as a hill rather than as a wire. | 697 | /// its weight: it is what makes a boost read as a hill rather than as a wire. |
| 573 | const EQ_FILL_INK: u32 = 0x4a9eff26; | 698 | const EQ_FILL_INK: u32 = 0x4a9eff26; |
| 574 | 699 | ||
| 700 | +/// One band's own response, drawn under the sum: a dim thread per band, so a | ||
| 701 | +/// boost pushed against a cut can be *seen* as two bands rather than as the | ||
| 702 | +/// flat line their total makes. | ||
| 703 | +const EQ_BELL_INK: u32 = 0x4a9eff66; | ||
| 704 | + | ||
| 575 | /// The colour card's four controls, in the order it lists them: what each is | 705 | /// The colour card's four controls, in the order it lists them: what each is |
| 576 | /// called and the range it moves in. The order is `ColorParams`' own, which is | 706 | /// called and the range it moves in. The order is `ColorParams`' own, which is |
| 577 | /// what [`color_band`] indexes. | 707 | /// what [`color_band`] indexes. |
| @@ -614,6 +744,48 @@ const HIST_H: f32 = 96.; | |||
| 614 | /// counts, lightened enough to read on the dark box. | 744 | /// counts, lightened enough to read on the dark box. |
| 615 | const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; | 745 | const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; |
| 616 | 746 | ||
| 747 | +/// Where the transport is. The one answer the button's glyph, its label, its | ||
| 748 | +/// enablement, the play key and the repaint loop all read -- there is no play | ||
| 749 | +/// flag anywhere else, because a second one is a second answer. | ||
| 750 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 751 | +enum Transport { | ||
| 752 | + /// No timeline open. Nothing to play and the transport is dimmed. | ||
| 753 | + Stopped, | ||
| 754 | + Playing, | ||
| 755 | + Paused, | ||
| 756 | + /// Played out: the last frame is on screen, the decoder is finished, and the | ||
| 757 | + /// clock is still running past it -- which is exactly why "is the clock | ||
| 758 | + /// going" is not the same question as "is this playing". | ||
| 759 | + Ended, | ||
| 760 | +} | ||
| 761 | + | ||
| 762 | +impl Transport { | ||
| 763 | + /// The timeline is in motion: two bars on the button, and a repaint owed | ||
| 764 | + /// every vsync. | ||
| 765 | + fn is_playing(self) -> bool { | ||
| 766 | + matches!(self, Transport::Playing) | ||
| 767 | + } | ||
| 768 | + | ||
| 769 | + /// The play key and the transport button start over from the top rather | ||
| 770 | + /// than toggling -- the end of a timeline is where every NLE does this, and | ||
| 771 | + /// the button does it because the key already did. | ||
| 772 | + fn restarts(self) -> bool { | ||
| 773 | + matches!(self, Transport::Ended) | ||
| 774 | + } | ||
| 775 | +} | ||
| 776 | + | ||
| 777 | +/// What a session's own two answers mean: the clock, unless the timeline has | ||
| 778 | +/// been played out -- `played_out` is the engine's end of stream with no frame | ||
| 779 | +/// still waiting on the pump, and it wins, because past the end a running clock | ||
| 780 | +/// is measuring wall time and not a picture. | ||
| 781 | +fn transport(playing: bool, played_out: bool) -> Transport { | ||
| 782 | + match (played_out, playing) { | ||
| 783 | + (true, _) => Transport::Ended, | ||
| 784 | + (_, true) => Transport::Playing, | ||
| 785 | + (_, false) => Transport::Paused, | ||
| 786 | + } | ||
| 787 | +} | ||
| 788 | + | ||
| 617 | struct Player { | 789 | struct Player { |
| 618 | /// The timeline, once there is one. A run with no file opens without it and | 790 | /// The timeline, once there is one. A run with no file opens without it and |
| 619 | /// waits: the first media import or project load is what fills it, and | 791 | /// waits: the first media import or project load is what fills it, and |
| @@ -625,21 +797,20 @@ struct Player { | |||
| 625 | name: SharedString, | 797 | name: SharedString, |
| 626 | image: Option<Arc<RenderImage>>, | 798 | image: Option<Arc<RenderImage>>, |
| 627 | /// A frame that arrived before its time; shown on the tick it comes due. | 799 | /// A frame that arrived before its time; shown on the tick it comes due. |
| 800 | + /// The pump's buffer, not transport state -- but a frame waiting here is | ||
| 801 | + /// what keeps a finished decoder from reading as [`Transport::Ended`] one | ||
| 802 | + /// tick early. See [`Player::transport`]. | ||
| 628 | held: Option<Frame>, | 803 | held: Option<Frame>, |
| 629 | - /// The decoder's channel closed. Frames may still be waiting in `held`. | ||
| 630 | - eos: bool, | ||
| 631 | - /// Last frame shown; nothing left to animate. | ||
| 632 | - done: bool, | ||
| 633 | /// A seek is waiting for its frame. Keeps the repaint loop alive while | 804 | /// A seek is waiting for its frame. Keeps the repaint loop alive while |
| 634 | /// paused, which is the only way the new still ever reaches the screen. | 805 | /// paused, which is the only way the new still ever reaches the screen. |
| 635 | pending_seek: bool, | 806 | pending_seek: bool, |
| 636 | /// The ruler's own box, recorded at prepaint: a mouse listener is handed | 807 | /// The ruler's own box, recorded at prepaint: a mouse listener is handed |
| 637 | /// the window position and nothing else. | 808 | /// the window position and nothing else. |
| 638 | ruler: Rc<Cell<Bounds<Pixels>>>, | 809 | ruler: Rc<Cell<Bounds<Pixels>>>, |
| 639 | - /// How much of the timeline the ruler and the lanes are showing. Held here | 810 | + /// How wide a second of timeline is drawn, and from which moment. Held here |
| 640 | /// and nowhere else: every frame-to-pixel answer in the panel comes out of | 811 | /// and nowhere else: every frame-to-pixel answer in the panel comes out of |
| 641 | /// it, so the boxes, the playhead and the pointer cannot disagree. | 812 | /// it, so the boxes, the playhead and the pointer cannot disagree. |
| 642 | - view: View, | 813 | + scale: Scale, |
| 643 | /// Which clip the edit keys act on: the lane it is in and its index there. | 814 | /// Which clip the edit keys act on: the lane it is in and its index there. |
| 644 | /// The *clicked* half, not the group -- a group is what gets marked on | 815 | /// The *clicked* half, not the group -- a group is what gets marked on |
| 645 | /// screen, but Lift has to know which half it was aimed at. Indices move | 816 | /// screen, but Lift has to know which half it was aimed at. Indices move |
| @@ -649,6 +820,10 @@ struct Player { | |||
| 649 | /// `selected` does, so it is closed by anything that can move indices -- | 820 | /// `selected` does, so it is closed by anything that can move indices -- |
| 650 | /// every stroke, and every item of its own. | 821 | /// every stroke, and every item of its own. |
| 651 | context_menu: Option<ContextMenu>, | 822 | context_menu: Option<ContextMenu>, |
| 823 | + /// The choice list a click on an enumerated setting opened, if one is up: | ||
| 824 | + /// the project resolution or a clip's fit policy, every value on screen at | ||
| 825 | + /// once. Closed by anything that closes the menus, and for the same reason. | ||
| 826 | + picker: Option<Picker>, | ||
| 652 | /// The library menu a right-click on a row opened, if one is up. Names its | 827 | /// The library menu a right-click on a row opened, if one is up. Names its |
| 653 | /// row by file and stream rather than by position, so it acts on the row it | 828 | /// row by file and stream rather than by position, so it acts on the row it |
| 654 | /// was opened on however the list is rebuilt under it. | 829 | /// was opened on however the list is rebuilt under it. |
| @@ -704,6 +879,16 @@ struct Player { | |||
| 704 | /// the value being dragged, and stale between drags, which costs nothing -- | 879 | /// the value being dragged, and stale between drags, which costs nothing -- |
| 705 | /// no drag starts without a press on the box it moves. | 880 | /// no drag starts without a press on the box it moves. |
| 706 | grab: u32, | 881 | grab: u32, |
| 882 | + /// Whether a drag or a trim is pulled onto the edges near it. On by | ||
| 883 | + /// default, because clips meeting exactly is what a timeline is for, and off | ||
| 884 | + /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement | ||
| 885 | + /// no magnet may take away. | ||
| 886 | + snap: bool, | ||
| 887 | + /// The frame the live gesture is about to land on, or `None` while it is | ||
| 888 | + /// over open bed: the line every lane draws so the snap is seen before it | ||
| 889 | + /// happens rather than discovered after the release. Stale between gestures, | ||
| 890 | + /// which costs nothing -- it is drawn only while one is live. | ||
| 891 | + snap_cue: Option<u32>, | ||
| 707 | last_scrub: Instant, | 892 | last_scrub: Instant, |
| 708 | last_target: u32, | 893 | last_target: u32, |
| 709 | /// The running export. While it owns the UI the editor is read-only. | 894 | /// The running export. While it owns the UI the editor is read-only. |
| @@ -891,6 +1076,9 @@ impl Player { | |||
| 891 | /// the channel and only the last of them is shown, which *is* the | 1076 | /// the channel and only the last of them is shown, which *is* the |
| 892 | /// drop-when-behind policy. A frame that is not due yet waits in `held`. | 1077 | /// drop-when-behind policy. A frame that is not due yet waits in `held`. |
| 893 | fn pump(&mut self, window: &mut Window) { | 1078 | fn pump(&mut self, window: &mut Window) { |
| 1079 | + // Where the transport was before this drain, so the crossing into | ||
| 1080 | + // `Ended` can be recognised as the one transition it is. | ||
| 1081 | + let was = self.transport(); | ||
| 894 | // No timeline, nothing to catch up to: the window is showing its empty | 1082 | // No timeline, nothing to catch up to: the window is showing its empty |
| 895 | // state and there is no decoder to drain. | 1083 | // state and there is no decoder to drain. |
| 896 | let Some(session) = &mut self.session else { | 1084 | let Some(session) = &mut self.session else { |
| @@ -906,10 +1094,7 @@ impl Player { | |||
| 906 | // them apart -- `frame.index` is already a timeline index. | 1094 | // them apart -- `frame.index` is already a timeline index. |
| 907 | None => match session.try_frame() { | 1095 | None => match session.try_frame() { |
| 908 | Some(frame) => frame, | 1096 | Some(frame) => frame, |
| 909 | - None => { | 1097 | + None => break, |
| 910 | - self.eos = session.is_eos(); | ||
| 911 | - break; | ||
| 912 | - } | ||
| 913 | }, | 1098 | }, |
| 914 | }; | 1099 | }; |
| 915 | if f64::from(frame.index) <= target { | 1100 | if f64::from(frame.index) <= target { |
| @@ -944,29 +1129,56 @@ impl Player { | |||
| 944 | } | 1129 | } |
| 945 | } | 1130 | } |
| 946 | 1131 | ||
| 947 | - if self.eos && self.held.is_none() && !self.done { | 1132 | + if self.transport() == Transport::Ended { |
| 948 | - self.done = true; | ||
| 949 | // A seek whose worker never produced a frame (vanished file) would | 1133 | // A seek whose worker never produced a frame (vanished file) would |
| 950 | - // otherwise repaint at vsync forever. | 1134 | + // otherwise repaint at vsync forever. Held true for as long as the |
| 1135 | + // state does, not just on the crossing: nothing else is coming. | ||
| 951 | self.pending_seek = false; | 1136 | self.pending_seek = false; |
| 952 | - let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); | 1137 | + if was != Transport::Ended { |
| 953 | - eprintln!( | 1138 | + // Ended is a *stopped* transport, so the clock stops with it, |
| 954 | - "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", | 1139 | + // on the out point the timecode and the playhead have been |
| 955 | - self.displayed, | 1140 | + // showing all along. Nothing else ever stopped it: past the |
| 956 | - self.dropped, | 1141 | + // last frame wall time takes over and `now()` walks off the end |
| 957 | - session.now() | 1142 | + // of the timeline for as long as the window is left open -- and |
| 958 | - ); | 1143 | + // the playhead is what a cut, a paste, an insert and the |
| 1144 | + // analyser all act at, so every one of them was aiming into | ||
| 1145 | + // empty space (measured: a 5 s timeline recognised its end at | ||
| 1146 | + // clock 17.5 s under a slow renderer). End of stream is left | ||
| 1147 | + // set, so this is still `Ended` and the next press restarts. | ||
| 1148 | + if let Some(session) = &mut self.session { | ||
| 1149 | + session.halt_at_end(); | ||
| 1150 | + } | ||
| 1151 | + let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); | ||
| 1152 | + eprintln!( | ||
| 1153 | + "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", | ||
| 1154 | + self.displayed, | ||
| 1155 | + self.dropped, | ||
| 1156 | + self.session.as_ref().map_or(0., PlaybackSession::now) | ||
| 1157 | + ); | ||
| 1158 | + } | ||
| 959 | } | 1159 | } |
| 960 | } | 1160 | } |
| 961 | 1161 | ||
| 962 | - /// Every end-of-stream flag is app state and the engine knows nothing about | 1162 | + /// Where the transport is, asked of the session rather than remembered: |
| 963 | - /// it, so clearing them after a reseek is what stops the picture from | 1163 | + /// end of stream is the engine's own flag (any seek clears it, which is why |
| 964 | - /// staying frozen on the old last frame. Edits reseek inside the engine and | 1164 | + /// an edit past the end revives the picture) and so is the clock. A held |
| 965 | - /// still owe this. | 1165 | + /// frame is one still owed to the screen, so the end is not the end yet. |
| 1166 | + fn transport(&self) -> Transport { | ||
| 1167 | + let Some(session) = &self.session else { | ||
| 1168 | + return Transport::Stopped; | ||
| 1169 | + }; | ||
| 1170 | + transport( | ||
| 1171 | + session.is_playing(), | ||
| 1172 | + session.is_eos() && self.held.is_none(), | ||
| 1173 | + ) | ||
| 1174 | + } | ||
| 1175 | + | ||
| 1176 | + /// A frame owed to the screen after a reseek, and the buffered one dropped: | ||
| 1177 | + /// what stops the picture from staying frozen on the old last frame. The | ||
| 1178 | + /// end-of-stream flag itself is the engine's and its own seek clears it -- | ||
| 1179 | + /// edits reseek inside the engine and still owe this. | ||
| 966 | fn reset_after_reseek(&mut self) { | 1180 | fn reset_after_reseek(&mut self) { |
| 967 | self.held = None; | 1181 | self.held = None; |
| 968 | - self.eos = false; | ||
| 969 | - self.done = false; | ||
| 970 | self.pending_seek = true; | 1182 | self.pending_seek = true; |
| 971 | // An edit moves the indices a drag in flight is holding -- a stroke | 1183 | // An edit moves the indices a drag in flight is holding -- a stroke |
| 972 | // during one is exactly that -- and an edge committed against a moved | 1184 | // during one is exactly that -- and an edge committed against a moved |
| @@ -1026,12 +1238,57 @@ impl Player { | |||
| 1026 | ActionId::Speed => self.open_speed(cx), | 1238 | ActionId::Speed => self.open_speed(cx), |
| 1027 | ActionId::Silence => self.open_silence(cx), | 1239 | ActionId::Silence => self.open_silence(cx), |
| 1028 | ActionId::Mix => self.open_mix(None, cx), | 1240 | ActionId::Mix => self.open_mix(None, cx), |
| 1241 | + ActionId::ToggleSnap => self.toggle_snap(cx), | ||
| 1029 | // Nothing to cancel while nothing is exporting; the export guard in | 1242 | // Nothing to cancel while nothing is exporting; the export guard in |
| 1030 | // the key handler is what answers this one while there is. | 1243 | // the key handler is what answers this one while there is. |
| 1031 | ActionId::CancelExport => {} | 1244 | ActionId::CancelExport => {} |
| 1032 | } | 1245 | } |
| 1033 | } | 1246 | } |
| 1034 | 1247 | ||
| 1248 | + /// The magnet off and on again, in words: a snap that stops working | ||
| 1249 | + /// silently reads as a bug, and one that starts working silently reads as | ||
| 1250 | + /// one too. The line goes with it -- nothing is being promised any more. | ||
| 1251 | + fn toggle_snap(&mut self, cx: &mut Context<Self>) { | ||
| 1252 | + self.snap = !self.snap; | ||
| 1253 | + self.snap_cue = None; | ||
| 1254 | + self.notice = Some(match self.snap { | ||
| 1255 | + true => "SNAP ON — drags land on clip edges, the playhead and the start".into(), | ||
| 1256 | + false => "SNAP OFF — drags land exactly where the hand leaves them".into(), | ||
| 1257 | + }); | ||
| 1258 | + cx.notify(); | ||
| 1259 | + } | ||
| 1260 | + | ||
| 1261 | + /// Whether the editor can be asked for `action` right now, and why not when | ||
| 1262 | + /// it cannot. `on` is the clip the question is about -- the one a clip menu | ||
| 1263 | + /// was opened on -- and `None` asks about the marked clip instead, which is | ||
| 1264 | + /// what a menu that hangs over no clip in particular means by "this one". | ||
| 1265 | + /// | ||
| 1266 | + /// The player's half of [`enable`]: it reads the state, the table decides. | ||
| 1267 | + fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable { | ||
| 1268 | + let Some(session) = &self.session else { | ||
| 1269 | + return enable(action, Ctx::default()); | ||
| 1270 | + }; | ||
| 1271 | + let clip = on | ||
| 1272 | + .or(self.selected) | ||
| 1273 | + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane))); | ||
| 1274 | + enable( | ||
| 1275 | + action, | ||
| 1276 | + Ctx { | ||
| 1277 | + clip, | ||
| 1278 | + image: clip.is_some_and(|(clip, _)| { | ||
| 1279 | + session | ||
| 1280 | + .sources() | ||
| 1281 | + .get(clip.source) | ||
| 1282 | + .is_some_and(|s| engine::is_image(&s.path)) | ||
| 1283 | + }), | ||
| 1284 | + playhead: frame_at(session.now(), self.fps), | ||
| 1285 | + timeline: true, | ||
| 1286 | + clipboard: self.clipboard.is_some(), | ||
| 1287 | + exporting: self.exporting().is_some(), | ||
| 1288 | + }, | ||
| 1289 | + ) | ||
| 1290 | + } | ||
| 1291 | + | ||
| 1035 | /// The one place a clip becomes *the* selected one: a click, a right-click | 1292 | /// The one place a clip becomes *the* selected one: a click, a right-click |
| 1036 | /// that opens the menu, and every selection key go through here, so what a | 1293 | /// that opens the menu, and every selection key go through here, so what a |
| 1037 | /// keyboard marks and what a pointer marks are the same state marked the | 1294 | /// keyboard marks and what a pointer marks are the same state marked the |
| @@ -1127,31 +1384,54 @@ impl Player { | |||
| 1127 | return; | 1384 | return; |
| 1128 | }; | 1385 | }; |
| 1129 | let next = next_fit(session.fit_of(lane, idx)); | 1386 | let next = next_fit(session.fit_of(lane, idx)); |
| 1130 | - if session.set_fit(lane, idx, next) { | 1387 | + self.apply_fit(lane, idx, next, cx); |
| 1388 | + } | ||
| 1389 | + | ||
| 1390 | + /// One clip's fit policy set, whichever asked: the stroke that steps to the | ||
| 1391 | + /// next one and the list that names one outright come through here, so they | ||
| 1392 | + /// cannot differ in what they do or in what they say they did. | ||
| 1393 | + fn apply_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy, cx: &mut Context<Self>) { | ||
| 1394 | + if let Some(session) = &mut self.session | ||
| 1395 | + && session.set_fit(lane, idx, fit) | ||
| 1396 | + { | ||
| 1131 | let (w, h) = session.resolution(); | 1397 | let (w, h) = session.resolution(); |
| 1132 | - self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(next)).into()); | 1398 | + self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(fit)).into()); |
| 1133 | self.reset_after_reseek(); | 1399 | self.reset_after_reseek(); |
| 1134 | } | 1400 | } |
| 1135 | cx.notify(); | 1401 | cx.notify(); |
| 1136 | } | 1402 | } |
| 1137 | 1403 | ||
| 1138 | - /// Magnifies the timeline about a point that stays put: `anchor` is where | 1404 | + /// The scale against the bed it is drawn on and the timeline it is drawn |
| 1139 | - /// along the bed to hold still (a ctrl+wheel holds the pointer), and with | 1405 | + /// from: every clamp, zoom and scroll is worked out through this, and the |
| 1140 | - /// none it is the playhead -- so the frame being worked on is still the | 1406 | + /// bed is measured off the ruler's probe rather than remembered, so a |
| 1407 | + /// resized window is a resized view on the very next answer. | ||
| 1408 | + fn view(&self) -> View { | ||
| 1409 | + View { | ||
| 1410 | + scale: self.scale, | ||
| 1411 | + bed: f32::from(self.ruler.get().size.width), | ||
| 1412 | + duration: self.drawn_duration(), | ||
| 1413 | + fps: self.fps, | ||
| 1414 | + } | ||
| 1415 | + } | ||
| 1416 | + | ||
| 1417 | + /// Magnifies the timeline about a point that stays put: `anchor` is how many | ||
| 1418 | + /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and | ||
| 1419 | + /// with none it is the playhead -- so the frame being worked on is still the | ||
| 1141 | /// frame on screen after the zoom. Clamped at both ends by [`View`]: out | 1420 | /// frame on screen after the zoom. Clamped at both ends by [`View`]: out |
| 1142 | - /// stops at the whole timeline, in at a handful of frames. | 1421 | + /// stops at [`ZOOM_MAX_SECONDS`] on the bed, in at a handful of frames. |
| 1143 | fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) { | 1422 | fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) { |
| 1144 | - let duration = self.drawn_duration(); | 1423 | + let view = self.view(); |
| 1145 | - let at = self.playhead(duration); | 1424 | + let at = self.playhead(view.duration); |
| 1146 | - let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.)); | 1425 | + let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed)); |
| 1147 | - self.view = self.view.zoomed(factor, anchor, duration, self.fps); | 1426 | + self.scale = view.zoomed(factor, anchor); |
| 1148 | cx.notify(); | 1427 | cx.notify(); |
| 1149 | } | 1428 | } |
| 1150 | 1429 | ||
| 1151 | - /// All the way back out: the whole timeline across the bed, which is what | 1430 | + /// All the way back out: the whole timeline across the bed, and the one |
| 1152 | - /// the panel shows before anyone has zoomed at all. | 1431 | + /// thing that reads the timeline's own length to decide how wide a second |
| 1432 | + /// is drawn. | ||
| 1153 | fn zoom_fit(&mut self, cx: &mut Context<Self>) { | 1433 | fn zoom_fit(&mut self, cx: &mut Context<Self>) { |
| 1154 | - self.view = View::default(); | 1434 | + self.scale = self.view().fit(); |
| 1155 | cx.notify(); | 1435 | cx.notify(); |
| 1156 | } | 1436 | } |
| 1157 | 1437 | ||
| @@ -1170,13 +1450,66 @@ impl Player { | |||
| 1170 | return; | 1450 | return; |
| 1171 | }; | 1451 | }; |
| 1172 | let (width, height) = next_resolution(session.resolution(), session.native_resolution()); | 1452 | let (width, height) = next_resolution(session.resolution(), session.native_resolution()); |
| 1173 | - if session.set_resolution(width, height) { | 1453 | + self.apply_resolution(width, height, cx); |
| 1454 | + } | ||
| 1455 | + | ||
| 1456 | + /// The project resized, whichever asked: the stroke that steps to the next | ||
| 1457 | + /// size and the list that names one outright come through here. | ||
| 1458 | + fn apply_resolution(&mut self, width: u32, height: u32, cx: &mut Context<Self>) { | ||
| 1459 | + if let Some(session) = &mut self.session | ||
| 1460 | + && session.set_resolution(width, height) | ||
| 1461 | + { | ||
| 1174 | self.notice = Some(format!("PROJECT: {width}x{height}").into()); | 1462 | self.notice = Some(format!("PROJECT: {width}x{height}").into()); |
| 1175 | self.reset_after_reseek(); | 1463 | self.reset_after_reseek(); |
| 1176 | } | 1464 | } |
| 1177 | cx.notify(); | 1465 | cx.notify(); |
| 1178 | } | 1466 | } |
| 1179 | 1467 | ||
| 1468 | + /// Opens a choice list on a setting, where it was asked for. One floating | ||
| 1469 | + /// thing at a time: the click that opens it is the click that closes | ||
| 1470 | + /// whatever menu it was opened from. | ||
| 1471 | + fn open_picker(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) { | ||
| 1472 | + self.context_menu = None; | ||
| 1473 | + self.library_menu = None; | ||
| 1474 | + self.picker = Some(Picker { of, at }); | ||
| 1475 | + cx.notify(); | ||
| 1476 | + } | ||
| 1477 | + | ||
| 1478 | + /// A row of the open list was picked. Closes the list first -- the rule | ||
| 1479 | + /// every menu item here follows -- then does exactly what the stroke for | ||
| 1480 | + /// that setting does, through the same door. | ||
| 1481 | + fn choose(&mut self, choice: Choice, cx: &mut Context<Self>) { | ||
| 1482 | + self.picker = None; | ||
| 1483 | + match choice { | ||
| 1484 | + Choice::Size(w, h) => self.apply_resolution(w, h, cx), | ||
| 1485 | + Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), | ||
| 1486 | + // The same field the row's key steps, set outright: a list picks a | ||
| 1487 | + // value, it does not step to one. | ||
| 1488 | + Choice::AudioRate(kbps) => { | ||
| 1489 | + self.audio_kbps = kbps; | ||
| 1490 | + cx.notify(); | ||
| 1491 | + } | ||
| 1492 | + } | ||
| 1493 | + } | ||
| 1494 | + | ||
| 1495 | + /// Every value the open list offers, in the order it lists them. Empty | ||
| 1496 | + /// without a timeline, which is the state where nothing here has a value to | ||
| 1497 | + /// offer -- and where the surfaces that open the list are dimmed anyway. | ||
| 1498 | + fn choices(&self, of: Pick) -> Vec<ChoiceRow> { | ||
| 1499 | + let Some(session) = &self.session else { | ||
| 1500 | + return Vec::new(); | ||
| 1501 | + }; | ||
| 1502 | + match of { | ||
| 1503 | + Pick::Resolution => { | ||
| 1504 | + resolution_choices(session.resolution(), session.native_resolution()) | ||
| 1505 | + } | ||
| 1506 | + Pick::Fit(lane, idx) => { | ||
| 1507 | + fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) | ||
| 1508 | + } | ||
| 1509 | + Pick::AudioRate => audio_rate_choices(self.audio_kbps), | ||
| 1510 | + } | ||
| 1511 | + } | ||
| 1512 | + | ||
| 1180 | /// Opens the colour card on the clip a grade would go on: the clip that was | 1513 | /// Opens the colour card on the clip a grade would go on: the clip that was |
| 1181 | /// clicked when it is a video one, and otherwise the clip the picture is | 1514 | /// clicked when it is a video one, and otherwise the clip the picture is |
| 1182 | /// coming from -- the one the engine's own compositing rule picks, which is | 1515 | /// coming from -- the one the engine's own compositing rule picks, which is |
| @@ -1864,41 +2197,78 @@ impl Player { | |||
| 1864 | cx.notify(); | 2197 | cx.notify(); |
| 1865 | } | 2198 | } |
| 1866 | 2199 | ||
| 1867 | - /// Moves one band and says whether anything changed. Live only: the write | 2200 | + /// Changes the picked band in place and says whether anything moved. Every |
| 1868 | - /// is [`commit_eq`](Player::commit_eq)'s. | 2201 | + /// edit of a band goes through here -- the drag, each key, each stepper |
| 1869 | - fn set_band(&mut self, band: usize, gain_db: f32) -> bool { | 2202 | + /// button -- so the card has exactly one place that clamps a band into what |
| 1870 | - let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT); | 2203 | + /// the graph can draw, and no caller has to remember the limits. |
| 1871 | - match self.eq_params.bands.get_mut(band) { | 2204 | + fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool { |
| 1872 | - Some(b) if b.gain_db != gain_db => { | 2205 | + let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else { |
| 1873 | - b.gain_db = gain_db; | 2206 | + return false; |
| 1874 | - true | 2207 | + }; |
| 1875 | - } | 2208 | + let was = *band; |
| 1876 | - _ => false, | 2209 | + change(band); |
| 2210 | + band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH); | ||
| 2211 | + band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT); | ||
| 2212 | + band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH); | ||
| 2213 | + *band != was | ||
| 2214 | + } | ||
| 2215 | + | ||
| 2216 | + /// The keyboard's and the buttons' version of a drag: one step on the picked | ||
| 2217 | + /// band, committed straight away -- neither has a release to wait for. | ||
| 2218 | + fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) { | ||
| 2219 | + if self.set_band(change) { | ||
| 2220 | + self.commit_eq(cx); | ||
| 1877 | } | 2221 | } |
| 1878 | } | 2222 | } |
| 1879 | 2223 | ||
| 1880 | - /// The keyboard's version of a drag: one step on the picked band, committed | 2224 | + /// Where the pointer sits in the graph, as the picked band's frequency and |
| 1881 | - /// straight away -- a keystroke has no release to wait for. | 2225 | + /// gain: across is the frequency axis and down is the gain one, so the |
| 1882 | - fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) { | 2226 | + /// handle follows the hand both ways rather than sliding up a rail. Called |
| 1883 | - let gain = self | 2227 | + /// on every pointer sample, so the curve bends under it; the write is the |
| 1884 | - .eq_params | 2228 | + /// release's ([`commit_eq`](Player::commit_eq)). |
| 1885 | - .bands | 2229 | + fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) { |
| 1886 | - .get(self.eq_band) | 2230 | + let bounds = self.eq_graph.get(); |
| 1887 | - .map_or(0., |b| b.gain_db); | 2231 | + let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT; |
| 1888 | - if self.set_band(self.eq_band, gain + by) { | 2232 | + let freq = eq_freq(frac_along(at.x, bounds)); |
| 1889 | - self.commit_eq(cx); | 2233 | + if self.set_band(|b| { |
| 2234 | + b.gain_db = gain; | ||
| 2235 | + b.freq_hz = freq; | ||
| 2236 | + }) { | ||
| 2237 | + cx.notify(); | ||
| 2238 | + } | ||
| 2239 | + } | ||
| 2240 | + | ||
| 2241 | + /// A band added beside the picked one, at the frequency with the most room | ||
| 2242 | + /// around it ([`inserted_band`]), and picked so the next keystroke moves the | ||
| 2243 | + /// band that was just made. Refused rather than silently ignored at the cap. | ||
| 2244 | + fn add_band(&mut self, cx: &mut Context<Self>) { | ||
| 2245 | + if self.eq_params.bands.len() >= EQ_BANDS_MAX { | ||
| 2246 | + self.notice = Some( | ||
| 2247 | + format!( | ||
| 2248 | + "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead" | ||
| 2249 | + ) | ||
| 2250 | + .into(), | ||
| 2251 | + ); | ||
| 2252 | + cx.notify(); | ||
| 2253 | + return; | ||
| 1890 | } | 2254 | } |
| 2255 | + let band = inserted_band(&self.eq_params.bands, self.eq_band); | ||
| 2256 | + self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len()); | ||
| 2257 | + self.eq_params.bands.insert(self.eq_band, band); | ||
| 2258 | + self.commit_eq(cx); | ||
| 1891 | } | 2259 | } |
| 1892 | 2260 | ||
| 1893 | - /// Where the pointer sits down the graph, as a gain on the picked band: the | 2261 | + /// Takes the picked band out. The last one stays: an equalizer of no bands |
| 1894 | - /// middle is flat and the top and bottom edges are the limit either way. | 2262 | + /// is a card with nothing to edit, and flattening is what "off" means here. |
| 1895 | - /// Called on every pointer sample, so the curve bends under the hand; the | 2263 | + fn remove_band(&mut self, cx: &mut Context<Self>) { |
| 1896 | - /// write is the release's ([`commit_eq`](Player::commit_eq)). | 2264 | + if self.eq_params.bands.len() <= 1 { |
| 1897 | - fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) { | 2265 | + self.notice = Some("LAST BAND — flatten it instead (r), or close the card".into()); |
| 1898 | - let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT; | ||
| 1899 | - if self.set_band(self.eq_band, gain) { | ||
| 1900 | cx.notify(); | 2266 | cx.notify(); |
| 2267 | + return; | ||
| 1901 | } | 2268 | } |
| 2269 | + self.eq_params.bands.remove(self.eq_band); | ||
| 2270 | + self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1); | ||
| 2271 | + self.commit_eq(cx); | ||
| 1902 | } | 2272 | } |
| 1903 | 2273 | ||
| 1904 | /// Which band a press on the graph grabs: the nearest one along the | 2274 | /// Which band a press on the graph grabs: the nearest one along the |
| @@ -1935,16 +2305,17 @@ impl Player { | |||
| 1935 | /// door a ruler click uses -- so a step while playing keeps playing, exactly | 2305 | /// door a ruler click uses -- so a step while playing keeps playing, exactly |
| 1936 | /// as a click does. It starts from the frame the transport is showing, which | 2306 | /// as a click does. It starts from the frame the transport is showing, which |
| 1937 | /// past the end is the last one, and that is what lets a step back off EOS | 2307 | /// past the end is the last one, and that is what lets a step back off EOS |
| 1938 | - /// revive the picture ([`Player::reset_after_reseek`] clears `done`). Both | 2308 | + /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both |
| 1939 | /// ends clamp, so the two go-to actions are this same step asked for more | 2309 | /// ends clamp, so the two go-to actions are this same step asked for more |
| 1940 | /// frames than the timeline has. Selection is untouched: a seek is not an | 2310 | /// frames than the timeline has. Selection is untouched: a seek is not an |
| 1941 | /// edit, and nothing it does moves a clip index. | 2311 | /// edit, and nothing it does moves a clip index. |
| 1942 | fn step(&mut self, frames: i64, cx: &mut Context<Self>) { | 2312 | fn step(&mut self, frames: i64, cx: &mut Context<Self>) { |
| 2313 | + let ended = self.transport() == Transport::Ended; | ||
| 1943 | let Some(session) = &self.session else { | 2314 | let Some(session) = &self.session else { |
| 1944 | return; | 2315 | return; |
| 1945 | }; | 2316 | }; |
| 1946 | let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0); | 2317 | let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0); |
| 1947 | - let now = match self.done { | 2318 | + let now = match ended { |
| 1948 | true => last, | 2319 | true => last, |
| 1949 | false => i64::from(frame_at(session.now(), self.fps)), | 2320 | false => i64::from(frame_at(session.now(), self.fps)), |
| 1950 | }; | 2321 | }; |
| @@ -2184,9 +2555,8 @@ impl Player { | |||
| 2184 | let (path, stream) = key.clone(); | 2555 | let (path, stream) = key.clone(); |
| 2185 | async move { | 2556 | async move { |
| 2186 | engine::waveform::peaks(&path, stream, WAVE_BPS) | 2557 | engine::waveform::peaks(&path, stream, WAVE_BPS) |
| 2187 | - .ok() | 2558 | + .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks)))) |
| 2188 | - .flatten() | 2559 | + .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display())) |
| 2189 | - .map(|peaks| Arc::new(normalise(peaks))) | ||
| 2190 | } | 2560 | } |
| 2191 | }); | 2561 | }); |
| 2192 | cx.spawn(async move |this, cx| { | 2562 | cx.spawn(async move |this, cx| { |
| @@ -2195,11 +2565,14 @@ impl Player { | |||
| 2195 | this.waves.insert( | 2565 | this.waves.insert( |
| 2196 | key, | 2566 | key, |
| 2197 | match decoded { | 2567 | match decoded { |
| 2198 | - Some(peaks) => Wave::Peaks(peaks), | 2568 | + Ok(Some(peaks)) => Wave::Peaks(peaks), |
| 2199 | - // Either no audio track or a file we could not read | 2569 | + // No audio track: an answer, and not worth asking |
| 2200 | - // it from; both mean the lane has nothing to draw, | 2570 | + // about again. |
| 2201 | - // and neither is worth asking about again. | 2571 | + Ok(None) => Wave::Silent, |
| 2202 | - None => Wave::Silent, | 2572 | + // A file whose sound we could not read is not a |
| 2573 | + // silent one, and a lane that drew it as silent is | ||
| 2574 | + // how a broken decode passes for a design choice. | ||
| 2575 | + Err(_) => Wave::Failed, | ||
| 2203 | }, | 2576 | }, |
| 2204 | ); | 2577 | ); |
| 2205 | cx.notify(); | 2578 | cx.notify(); |
| @@ -2296,8 +2669,8 @@ impl Player { | |||
| 2296 | if self.exporting().is_some() { | 2669 | if self.exporting().is_some() { |
| 2297 | return; | 2670 | return; |
| 2298 | } | 2671 | } |
| 2299 | - let (Some(start), Some(was)) = ( | 2672 | + let (Some((start, _)), Some(was)) = ( |
| 2300 | - self.drop_frame(from, idx, to, x), | 2673 | + self.drop_frame(from, idx, x), |
| 2301 | self.session | 2674 | self.session |
| 2302 | .as_ref() | 2675 | .as_ref() |
| 2303 | .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), | 2676 | .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), |
| @@ -2353,46 +2726,83 @@ impl Player { | |||
| 2353 | /// there is no such clip to move. The engine has the last word on where it | 2726 | /// there is no such clip to move. The engine has the last word on where it |
| 2354 | /// may actually go -- this is the ask, not the answer. | 2727 | /// may actually go -- this is the ask, not the answer. |
| 2355 | /// | 2728 | /// |
| 2356 | - /// ponytail: the bed ends where the timeline does, so a clip cannot be | 2729 | + /// ponytail: the bed now runs past the last frame whenever the timeline is |
| 2357 | - /// dragged *past* the last frame -- the pointer has no pixel out there to | 2730 | + /// shorter than the view ([`Scale::time_at`] clamps at the head only), so a |
| 2358 | - /// name and [`View::time_at`] clamps to the duration. Room to the right is | 2731 | + /// clip *can* be dragged out there. Zoomed in against the far end it cannot: |
| 2359 | - /// made by pulling a tail out first ([`Player::drawn_duration`] already | 2732 | + /// the scroll clamp pins the bed's right edge to the duration, and the |
| 2360 | - /// lengthens the bed for exactly that gesture). The upgrade is to draw the | 2733 | + /// pointer has no pixel past it. The upgrade is to let the scroll clamp |
| 2361 | - /// bed past the end while a clip drag is in flight, the way a trim already | 2734 | + /// leave a screen of empty bed after the end, the way every NLE does. |
| 2362 | - /// does: `drawn_duration` would take the dragged clip's length the same way | 2735 | + fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> { |
| 2363 | - /// it takes a trim's reach. | 2736 | + let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?; |
| 2364 | - fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> { | ||
| 2365 | - let session = self.session.as_ref()?; | ||
| 2366 | - let clip = session.lane_clips(from).get(idx).copied()?; | ||
| 2367 | let raw = self.frame_under(x).saturating_sub(self.grab); | 2737 | let raw = self.frame_under(x).saturating_sub(self.grab); |
| 2368 | - // The edges worth landing on: both ends of every clip already on the | 2738 | + let marks = self.snap_targets(Some((from, idx))); |
| 2369 | - // lane it is being let go over, the playhead, and the head of the | 2739 | + Some(self.snap_to(raw, clip.frames(), &marks)) |
| 2370 | - // timeline. Never the group's own boxes -- a clip does not snap to | ||
| 2371 | - // where it already is. | ||
| 2372 | - let mut marks: Vec<u32> = session | ||
| 2373 | - .lane_clips(to) | ||
| 2374 | - .iter() | ||
| 2375 | - .enumerate() | ||
| 2376 | - .filter(|&(i, c)| { | ||
| 2377 | - (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link) | ||
| 2378 | - }) | ||
| 2379 | - .flat_map(|(_, c)| [c.start, c.end()]) | ||
| 2380 | - .collect(); | ||
| 2381 | - marks.push(frame_at(session.now(), self.fps)); | ||
| 2382 | - marks.push(0); | ||
| 2383 | - Some(snapped(raw, clip.frames(), self.snap_frames(), &marks)) | ||
| 2384 | } | 2740 | } |
| 2385 | 2741 | ||
| 2386 | - /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is | 2742 | + /// Which index the clip in the hand is at *now*: [`live_idx`] against the |
| 2387 | - /// a distance on screen, so zoomed right in it is worth less than a frame | 2743 | + /// lane the drag named, since a stroke during the gesture moves the indices |
| 2388 | - /// (no snap at all, which is what a hand placing single frames wants) and | 2744 | + /// gpui froze into the payload. Both halves of a drag ask it -- the line |
| 2389 | - /// zoomed out to the whole timeline it is worth many. | 2745 | + /// drawn in flight and the drop that commits -- so the promise and the |
| 2390 | - fn snap_frames(&self) -> u32 { | 2746 | + /// landing are made about one clip. |
| 2391 | - let bed = f64::from(f32::from(self.ruler.get().size.width)); | 2747 | + fn dragged(&self, drag: &ClipDrag) -> Option<usize> { |
| 2392 | - if bed <= 0. { | 2748 | + let session = self.session.as_ref()?; |
| 2393 | - return 0; | 2749 | + live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip) |
| 2750 | + } | ||
| 2751 | + | ||
| 2752 | + /// The line while the clip is still in the hand: the very answer | ||
| 2753 | + /// [`Player::drop_frame`] will commit, worked out on every move of the drag, | ||
| 2754 | + /// so what the eye was promised is where the release puts it. A pointer that | ||
| 2755 | + /// has wandered off the bed promises nothing. | ||
| 2756 | + fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) { | ||
| 2757 | + let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue); | ||
| 2758 | + self.set_cue(cue, x, cx); | ||
| 2759 | + } | ||
| 2760 | + | ||
| 2761 | + /// The same line for a library row on its way to a lane: it goes down at | ||
| 2762 | + /// the frame it is let go on ([`Player::insert_source`]), so that frame is | ||
| 2763 | + /// what snaps and what is drawn. No length to snap by -- the file's own is | ||
| 2764 | + /// not known until the engine has placed it -- so only its head lands. | ||
| 2765 | + fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) { | ||
| 2766 | + let marks = self.snap_targets(None); | ||
| 2767 | + let cue = self.snap_to(self.frame_under(x), 0, &marks).1; | ||
| 2768 | + self.set_cue(cue, x, cx); | ||
| 2769 | + } | ||
| 2770 | + | ||
| 2771 | + /// Sets the line, or takes it away, and repaints only when it moved: a | ||
| 2772 | + /// pointer dragged off the bed (up to the library, say) is not promising a | ||
| 2773 | + /// landing any more. | ||
| 2774 | + fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) { | ||
| 2775 | + let bed = self.ruler.get(); | ||
| 2776 | + let cue = cue.filter(|_| x >= bed.left() && x <= bed.right()); | ||
| 2777 | + if cue != self.snap_cue { | ||
| 2778 | + self.snap_cue = cue; | ||
| 2779 | + cx.notify(); | ||
| 2394 | } | 2780 | } |
| 2395 | - (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u32 | 2781 | + } |
| 2782 | + | ||
| 2783 | + /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its | ||
| 2784 | + /// lanes, so a clip meets a take one track over as readily as one beside it. | ||
| 2785 | + fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> { | ||
| 2786 | + let Some(session) = &self.session else { | ||
| 2787 | + return Vec::new(); | ||
| 2788 | + }; | ||
| 2789 | + let lanes = session.lanes(); | ||
| 2790 | + let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect(); | ||
| 2791 | + let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx))); | ||
| 2792 | + snap_marks(&clips, skip, frame_at(session.now(), self.fps)) | ||
| 2793 | + } | ||
| 2794 | + | ||
| 2795 | + /// Where a gesture at `raw` lands and the mark that pulled it there, with | ||
| 2796 | + /// the switch honoured: snapping off, nothing moves and no line is drawn. | ||
| 2797 | + fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) { | ||
| 2798 | + snap_cue(self.snap, raw, len, self.snap_frames(), marks) | ||
| 2799 | + } | ||
| 2800 | + | ||
| 2801 | + /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's | ||
| 2802 | + /// own width drops out of it, since a pixel is now worth the same stretch of | ||
| 2803 | + /// timeline wherever the view sits. | ||
| 2804 | + fn snap_frames(&self) -> u32 { | ||
| 2805 | + self.scale.snap_frames(self.fps) | ||
| 2396 | } | 2806 | } |
| 2397 | 2807 | ||
| 2398 | /// Opens the clip menu on the box under the pointer, from the right button | 2808 | /// Opens the clip menu on the box under the pointer, from the right button |
| @@ -2449,26 +2859,36 @@ impl Player { | |||
| 2449 | /// against the same duration the boxes are drawn to, so the edge tracks the | 2859 | /// against the same duration the boxes are drawn to, so the edge tracks the |
| 2450 | /// pointer exactly. | 2860 | /// pointer exactly. |
| 2451 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { | 2861 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { |
| 2452 | - let at = self.frame_under(x); | 2862 | + let Some(trim) = self.trim else { |
| 2453 | - let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { | ||
| 2454 | return; | 2863 | return; |
| 2455 | }; | 2864 | }; |
| 2456 | - let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { | 2865 | + // The edge is pulled onto the same marks a whole clip is, by itself: |
| 2866 | + // there is no other end travelling with it, so it snaps at length zero. | ||
| 2867 | + let marks = self.snap_targets(Some((trim.lane, trim.idx))); | ||
| 2868 | + let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks); | ||
| 2869 | + let Some((lo, hi)) = self | ||
| 2870 | + .session | ||
| 2871 | + .as_ref() | ||
| 2872 | + .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge)) | ||
| 2873 | + else { | ||
| 2457 | return; | 2874 | return; |
| 2458 | }; | 2875 | }; |
| 2459 | - trim.to = at.clamp(lo, hi); | 2876 | + let to = at.clamp(lo, hi); |
| 2877 | + // The line only stands where the edge actually stopped: a mark the | ||
| 2878 | + // engine's own room clamped away was never reached. | ||
| 2879 | + self.set_cue(cue.filter(|_| to == at), x, cx); | ||
| 2880 | + self.trim = Some(Trim { to, ..trim }); | ||
| 2460 | cx.notify(); | 2881 | cx.notify(); |
| 2461 | } | 2882 | } |
| 2462 | 2883 | ||
| 2463 | /// The timeline frame a pointer at window x is on: along the same bed the | 2884 | /// The timeline frame a pointer at window x is on: along the same bed the |
| 2464 | - /// ruler is measured on, through the same [`View`] every box is drawn | 2885 | + /// ruler is measured on, through the same [`Scale`] every box is drawn |
| 2465 | /// through, so a zoomed-in panel answers with the frame under the pointer | 2886 | /// through, so a zoomed-in panel answers with the frame under the pointer |
| 2466 | /// and not with the one that would have been there unzoomed. The one | 2887 | /// and not with the one that would have been there unzoomed. The one |
| 2467 | /// question a trim, a grab and a drop all ask. | 2888 | /// question a trim, a grab and a drop all ask. |
| 2468 | fn frame_under(&self, x: Pixels) -> u32 { | 2889 | fn frame_under(&self, x: Pixels) -> u32 { |
| 2469 | - let duration = self.drawn_duration(); | ||
| 2470 | frame_at( | 2890 | frame_at( |
| 2471 | - self.view.time_at(frac_along(x, self.ruler.get()), duration), | 2891 | + self.scale.time_at(px_along(x, self.ruler.get())), |
| 2472 | self.fps, | 2892 | self.fps, |
| 2473 | ) | 2893 | ) |
| 2474 | } | 2894 | } |
| @@ -2499,39 +2919,13 @@ impl Player { | |||
| 2499 | }) else { | 2919 | }) else { |
| 2500 | return clip; | 2920 | return clip; |
| 2501 | }; | 2921 | }; |
| 2502 | - match trim.edge { | 2922 | + let still = self.session.as_ref().is_some_and(|session| { |
| 2503 | - // A still grows forward from source frame 0 instead, exactly as | 2923 | + session |
| 2504 | - // `Project::trim` writes it: with the in-point clamped at 0 the box | 2924 | + .sources() |
| 2505 | - // below would slide left rather than stretch, and the release would | 2925 | + .get(clip.source) |
| 2506 | - // then commit a wider clip than the drag drew. | 2926 | + .is_some_and(|s| engine::is_image(&s.path)) |
| 2507 | - Edge::Start | 2927 | + }); |
| 2508 | - if self.session.as_ref().is_some_and(|session| { | 2928 | + trimmed_clip(clip, trim.edge, trim.to, still) |
| 2509 | - session | ||
| 2510 | - .sources() | ||
| 2511 | - .get(clip.source) | ||
| 2512 | - .is_some_and(|s| engine::is_image(&s.path)) | ||
| 2513 | - }) => | ||
| 2514 | - { | ||
| 2515 | - Clip { | ||
| 2516 | - in_frame: 0, | ||
| 2517 | - out_frame: clip.end().saturating_sub(trim.to).max(1), | ||
| 2518 | - start: trim.to, | ||
| 2519 | - ..clip | ||
| 2520 | - } | ||
| 2521 | - } | ||
| 2522 | - // The in-point follows the head, exactly as `Project::trim` moves | ||
| 2523 | - // it: what stays on screen plays what it always played. | ||
| 2524 | - Edge::Start => Clip { | ||
| 2525 | - in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start)) | ||
| 2526 | - .clamp(0, i64::from(clip.out_frame - 1)) as u32, | ||
| 2527 | - start: trim.to, | ||
| 2528 | - ..clip | ||
| 2529 | - }, | ||
| 2530 | - Edge::End => Clip { | ||
| 2531 | - out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1), | ||
| 2532 | - ..clip | ||
| 2533 | - }, | ||
| 2534 | - } | ||
| 2535 | } | 2929 | } |
| 2536 | 2930 | ||
| 2537 | /// How long the timeline is *drawn* as: its own length, and while a tail is | 2931 | /// How long the timeline is *drawn* as: its own length, and while a tail is |
| @@ -2539,6 +2933,15 @@ impl Player { | |||
| 2539 | /// at the last frame has nowhere to put a pointer that means "longer", so | 2933 | /// at the last frame has nowhere to put a pointer that means "longer", so |
| 2540 | /// without this the last clip on the timeline could be pulled in and never | 2934 | /// without this the last clip on the timeline could be pulled in and never |
| 2541 | /// let back out. | 2935 | /// let back out. |
| 2936 | + /// | ||
| 2937 | + /// Scroll room only, now that a second is an absolute number of pixels | ||
| 2938 | + /// ([`Scale`]): the extra length loosens [`View::settled`]'s clamp, which is | ||
| 2939 | + /// where the pixels past the last frame come from, and moves no box by a | ||
| 2940 | + /// pixel. It is still the *only* headroom at the tail -- zoomed in against | ||
| 2941 | + /// the end, that clamp pins the bed's right edge to the duration and an | ||
| 2942 | + /// End-trim of the last clip would have nowhere to be dragged to. What it | ||
| 2943 | + /// must not do is be read as a length anyone is told: the timecode reads | ||
| 2944 | + /// `PlaybackSession::timeline_duration` for exactly that reason. | ||
| 2542 | fn drawn_duration(&self) -> f64 { | 2945 | fn drawn_duration(&self) -> f64 { |
| 2543 | let Some(session) = &self.session else { | 2946 | let Some(session) = &self.session else { |
| 2544 | return 0.; | 2947 | return 0.; |
| @@ -2555,12 +2958,11 @@ impl Player { | |||
| 2555 | } | 2958 | } |
| 2556 | } | 2959 | } |
| 2557 | 2960 | ||
| 2558 | - /// Where the playhead is, as the panel draws it. The clock keeps running | 2961 | + /// Where the playhead is, as the panel draws it: pinned to the out point |
| 2559 | - /// after the last frame (wall time takes over at audio EOF) while the | 2962 | + /// once playback is done, and clamped to the drawn duration otherwise -- a |
| 2560 | - /// picture is frozen, so what the UI shows is the clamped one, pinned to | 2963 | + /// tail being dragged draws past the timeline it is about to become. |
| 2561 | - /// the out-point once playback is done. | ||
| 2562 | fn playhead(&self, duration: f64) -> f64 { | 2964 | fn playhead(&self, duration: f64) -> f64 { |
| 2563 | - if self.done { | 2965 | + if self.transport() == Transport::Ended { |
| 2564 | duration | 2966 | duration |
| 2565 | } else { | 2967 | } else { |
| 2566 | self.session | 2968 | self.session |
| @@ -2755,11 +3157,11 @@ impl Player { | |||
| 2755 | self.export_path = PathBuf::new(); | 3157 | self.export_path = PathBuf::new(); |
| 2756 | self.project_path = PathBuf::new(); | 3158 | self.project_path = PathBuf::new(); |
| 2757 | self.fps = 30.; | 3159 | self.fps = 30.; |
| 2758 | - // No decoder to wait for a frame from: the hint is what shows. | 3160 | + // No decoder to wait for a frame from: the hint is what shows. The |
| 3161 | + // transport reads `Stopped` from the session being gone, so there is no | ||
| 3162 | + // end-of-stream state left to clear here. | ||
| 2759 | self.reset_after_reseek(); | 3163 | self.reset_after_reseek(); |
| 2760 | self.pending_seek = false; | 3164 | self.pending_seek = false; |
| 2761 | - self.eos = false; | ||
| 2762 | - self.done = false; | ||
| 2763 | } | 3165 | } |
| 2764 | 3166 | ||
| 2765 | /// One item of a library row's menu, done. Every one of them closes the | 3167 | /// One item of a library row's menu, done. Every one of them closes the |
| @@ -3128,9 +3530,12 @@ impl Player { | |||
| 3128 | let Some(session) = &self.session else { | 3530 | let Some(session) = &self.session else { |
| 3129 | return; | 3531 | return; |
| 3130 | }; | 3532 | }; |
| 3533 | + // Clamped to the timeline here rather than in the mapping: there is bed | ||
| 3534 | + // past the last frame now, and a seek out there is a seek to the end. | ||
| 3131 | let t = self | 3535 | let t = self |
| 3132 | - .view | 3536 | + .scale |
| 3133 | - .time_at(frac_along(x, self.ruler.get()), session.timeline_duration()); | 3537 | + .time_at(px_along(x, self.ruler.get())) |
| 3538 | + .clamp(0., session.timeline_duration()); | ||
| 3134 | let target = (t * self.fps) as u32; | 3539 | let target = (t * self.fps) as u32; |
| 3135 | if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { | 3540 | if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { |
| 3136 | self.last_target = target; | 3541 | self.last_target = target; |
| @@ -3175,11 +3580,11 @@ impl Player { | |||
| 3175 | return; | 3580 | return; |
| 3176 | } | 3581 | } |
| 3177 | // Nothing to play is a message, not a transport state. An empty | 3582 | // Nothing to play is a message, not a transport state. An empty |
| 3178 | - // timeline is `done` from its one black frame onward, so the restart | 3583 | + // timeline is [`Transport::Ended`] from its one black frame onward, so |
| 3179 | - // below would start a clock against a zero-length timeline -- and it is | 3584 | + // the restart below would start a clock against a zero-length timeline |
| 3180 | - // `done` again by the next repaint, so no later press could ever stop | 3585 | + // -- and it is Ended again by the next repaint, so no later press could |
| 3181 | - // it: the button would read "Pause" and never pause. A delete can empty | 3586 | + // ever stop it: the button would read "Pause" and never pause. A delete |
| 3182 | - // the timeline mid-play, and that press must still stop it. | 3587 | + // can empty the timeline mid-play, and that press must still stop it. |
| 3183 | if nothing_to_play(self.session.as_ref()) { | 3588 | if nothing_to_play(self.session.as_ref()) { |
| 3184 | match self.session.as_mut().filter(|s| s.is_playing()) { | 3589 | match self.session.as_mut().filter(|s| s.is_playing()) { |
| 3185 | Some(session) => session.pause(), | 3590 | Some(session) => session.pause(), |
| @@ -3188,15 +3593,25 @@ impl Player { | |||
| 3188 | cx.notify(); | 3593 | cx.notify(); |
| 3189 | return; | 3594 | return; |
| 3190 | } | 3595 | } |
| 3191 | - if self.done { | 3596 | + match self.transport() { |
| 3192 | - self.seek(0., cx); | 3597 | + // Nothing open: the button is dimmed and the key says nothing. |
| 3193 | - if let Some(session) = &mut self.session { | 3598 | + Transport::Stopped => {} |
| 3194 | - session.play(); | 3599 | + // Back to the top and away, for the key and the button alike -- |
| 3600 | + // whichever asked, the transport was showing Play. | ||
| 3601 | + state if state.restarts() => { | ||
| 3602 | + self.seek(0., cx); | ||
| 3603 | + if let Some(session) = &mut self.session { | ||
| 3604 | + session.play(); | ||
| 3605 | + } | ||
| 3606 | + } | ||
| 3607 | + _ => { | ||
| 3608 | + if let Some(session) = &mut self.session { | ||
| 3609 | + session.toggle(); | ||
| 3610 | + // A paused timeline animates nothing; this is the repaint | ||
| 3611 | + // that puts the new glyph up. | ||
| 3612 | + cx.notify(); | ||
| 3613 | + } | ||
| 3195 | } | 3614 | } |
| 3196 | - } else if let Some(session) = &mut self.session { | ||
| 3197 | - session.toggle(); | ||
| 3198 | - // Past EOF nothing else asks for a repaint. | ||
| 3199 | - cx.notify(); | ||
| 3200 | } | 3615 | } |
| 3201 | } | 3616 | } |
| 3202 | 3617 | ||
| @@ -3437,11 +3852,9 @@ impl Render for Player { | |||
| 3437 | window.set_window_title(&title); | 3852 | window.set_window_title(&title); |
| 3438 | self.titled = title; | 3853 | self.titled = title; |
| 3439 | } | 3854 | } |
| 3440 | - // No shadow flag: the clock is the only truth about play state. | 3855 | + // No shadow flag: the session is the only truth about play state, and |
| 3441 | - let playing = self | 3856 | + // [`Player::transport`] is the one place it is read. |
| 3442 | - .session | 3857 | + let state = self.transport(); |
| 3443 | - .as_ref() | ||
| 3444 | - .is_some_and(PlaybackSession::is_playing); | ||
| 3445 | // A paused timeline has nothing to animate; the toggle handlers notify, | 3858 | // A paused timeline has nothing to animate; the toggle handlers notify, |
| 3446 | // which is what starts the loop again. A paused seek keeps the loop | 3859 | // which is what starts the loop again. A paused seek keeps the loop |
| 3447 | // running by itself until `pump` has the frame it asked for. An export | 3860 | // running by itself until `pump` has the frame it asked for. An export |
| @@ -3449,7 +3862,7 @@ impl Render for Player { | |||
| 3449 | // the screen on a repaint. A notice does not: it waits to be dismissed | 3862 | // the screen on a repaint. A notice does not: it waits to be dismissed |
| 3450 | // rather than for a clock, so keeping the loop alive for it would spin | 3863 | // rather than for a clock, so keeping the loop alive for it would spin |
| 3451 | // the GPU until someone answered it. | 3864 | // the GPU until someone answered it. |
| 3452 | - if (playing && !self.done) || self.pending_seek || self.export.is_some() { | 3865 | + if state.is_playing() || self.pending_seek || self.export.is_some() { |
| 3453 | window.request_animation_frame(); | 3866 | window.request_animation_frame(); |
| 3454 | } | 3867 | } |
| 3455 | 3868 | ||
| @@ -3462,7 +3875,7 @@ impl Render for Player { | |||
| 3462 | // edit that shortens the timeline moves the far end of the view, and a | 3875 | // edit that shortens the timeline moves the far end of the view, and a |
| 3463 | // playhead that has run off the bed pulls the view after it -- which is | 3876 | // playhead that has run off the bed pulls the view after it -- which is |
| 3464 | // what makes a zoomed-in timeline scroll while it plays. | 3877 | // what makes a zoomed-in timeline scroll while it plays. |
| 3465 | - self.view = self.view.following(position, duration, self.fps); | 3878 | + self.scale = self.view().following(position); |
| 3466 | 3879 | ||
| 3467 | div() | 3880 | div() |
| 3468 | .track_focus(&self.focus) | 3881 | .track_focus(&self.focus) |
| @@ -3534,6 +3947,14 @@ impl Render for Player { | |||
| 3534 | // it takes focus, ledger:182) so this listener is its input, | 3947 | // it takes focus, ledger:182) so this listener is its input, |
| 3535 | // exactly as it is a waiting row's. | 3948 | // exactly as it is a waiting row's. |
| 3536 | if this.export_open { | 3949 | if this.export_open { |
| 3950 | + // A list open over the card is the innermost thing on | ||
| 3951 | + // screen, so it is what a stroke closes first -- the rule | ||
| 3952 | + // every menu here follows, said before the card's own keys | ||
| 3953 | + // so escape does not take the card out from under it. | ||
| 3954 | + if this.picker.take().is_some() { | ||
| 3955 | + cx.notify(); | ||
| 3956 | + return; | ||
| 3957 | + } | ||
| 3537 | if key == ESCAPE { | 3958 | if key == ESCAPE { |
| 3538 | this.export_open = false; | 3959 | this.export_open = false; |
| 3539 | } else if key == "enter" { | 3960 | } else if key == "enter" { |
| @@ -3587,31 +4008,55 @@ impl Render for Player { | |||
| 3587 | // cannot move at all, and every one of them is listed in the | 4008 | // cannot move at all, and every one of them is listed in the |
| 3588 | // keys menu (keymap.rs `FIXED`) rather than being a secret. | 4009 | // keys menu (keymap.rs `FIXED`) rather than being a secret. |
| 3589 | if this.eq_open.is_some() { | 4010 | if this.eq_open.is_some() { |
| 4011 | + // Shift makes the two horizontal keys Q instead of | ||
| 4012 | + // frequency: both are the *width* of the same hump, so they | ||
| 4013 | + // sit on the same axis rather than on two keys nobody would | ||
| 4014 | + // guess. Wider is a lower Q, which is why left widens. | ||
| 4015 | + let shift = event.keystroke.modifiers.shift; | ||
| 3590 | if key == ESCAPE { | 4016 | if key == ESCAPE { |
| 3591 | // Nothing to undo: every change is already at the clip, | 4017 | // Nothing to undo: every change is already at the clip, |
| 3592 | // and undo is undo's own key. | 4018 | // and undo is undo's own key. |
| 3593 | this.eq_open = None; | 4019 | this.eq_open = None; |
| 3594 | this.eq_dragging = false; | 4020 | this.eq_dragging = false; |
| 3595 | } else if key == "up" { | 4021 | } else if key == "up" { |
| 3596 | - this.nudge_band(EQ_STEP, cx); | 4022 | + this.nudge_band(|b| b.gain_db += EQ_STEP, cx); |
| 3597 | } else if key == "down" { | 4023 | } else if key == "down" { |
| 3598 | - this.nudge_band(-EQ_STEP, cx); | 4024 | + this.nudge_band(|b| b.gain_db -= EQ_STEP, cx); |
| 4025 | + } else if key == "left" && shift { | ||
| 4026 | + this.nudge_band(|b| b.q /= EQ_Q_STEP, cx); | ||
| 4027 | + } else if key == "right" && shift { | ||
| 4028 | + this.nudge_band(|b| b.q *= EQ_Q_STEP, cx); | ||
| 4029 | + } else if key == "left" { | ||
| 4030 | + this.nudge_band(|b| b.freq_hz /= EQ_FREQ_STEP, cx); | ||
| 4031 | + } else if key == "right" { | ||
| 4032 | + this.nudge_band(|b| b.freq_hz *= EQ_FREQ_STEP, cx); | ||
| 3599 | } else if key == "r" { | 4033 | } else if key == "r" { |
| 3600 | for band in &mut this.eq_params.bands { | 4034 | for band in &mut this.eq_params.bands { |
| 3601 | band.gain_db = 0.; | 4035 | band.gain_db = 0.; |
| 3602 | } | 4036 | } |
| 3603 | this.commit_eq(cx); | 4037 | this.commit_eq(cx); |
| 4038 | + } else if key == "f" { | ||
| 4039 | + // This one band back to flat, which is the undo of one | ||
| 4040 | + // hand movement -- `r` is the undo of the whole card. | ||
| 4041 | + this.nudge_band(|b| b.gain_db = 0., cx); | ||
| 4042 | + } else if key == "a" { | ||
| 4043 | + this.add_band(cx); | ||
| 4044 | + } else if key == "x" { | ||
| 4045 | + this.remove_band(cx); | ||
| 3604 | } else if key == "s" { | 4046 | } else if key == "s" { |
| 3605 | // The analyser off and on. Nothing is committed: it is | 4047 | // The analyser off and on. Nothing is committed: it is |
| 3606 | // what the card *shows*, so it survives no further than | 4048 | // what the card *shows*, so it survives no further than |
| 3607 | // this window. | 4049 | // this window. |
| 3608 | this.eq_spectrum = !this.eq_spectrum; | 4050 | this.eq_spectrum = !this.eq_spectrum; |
| 3609 | } else if let Ok(digit) = key.parse::<usize>() { | 4051 | } else if let Ok(digit) = key.parse::<usize>() { |
| 3610 | - // 1-based, as the rows are numbered on screen; a digit | 4052 | + // As the keys are laid out: 1-9 then 0 for the tenth, |
| 3611 | - // past the last band picks nothing rather than panics. | 4053 | + // which is the cap ([`EQ_BANDS_MAX`]). A digit past the |
| 3612 | - if let Some(band) = digit.checked_sub(1) | 4054 | + // last band picks nothing rather than panics. |
| 3613 | - && band < this.eq_params.bands.len() | 4055 | + let band = match digit { |
| 3614 | - { | 4056 | + 0 => EQ_BANDS_MAX - 1, |
| 4057 | + n => n - 1, | ||
| 4058 | + }; | ||
| 4059 | + if band < this.eq_params.bands.len() { | ||
| 3615 | this.eq_band = band; | 4060 | this.eq_band = band; |
| 3616 | } | 4061 | } |
| 3617 | } | 4062 | } |
| @@ -3715,9 +4160,12 @@ impl Render for Player { | |||
| 3715 | // Both menus, taken rather than short-circuited: the library's | 4160 | // Both menus, taken rather than short-circuited: the library's |
| 3716 | // one names a row the edits below can remove, so it closes on a | 4161 | // one names a row the edits below can remove, so it closes on a |
| 3717 | // stroke exactly as the clip menu does. | 4162 | // stroke exactly as the clip menu does. |
| 4163 | + // A choice list goes the same way and for the same reason: it | ||
| 4164 | + // names a clip index too, and escape is the way out of it. | ||
| 3718 | let clip_menu = this.context_menu.take().is_some(); | 4165 | let clip_menu = this.context_menu.take().is_some(); |
| 3719 | let row_menu = this.library_menu.take().is_some(); | 4166 | let row_menu = this.library_menu.take().is_some(); |
| 3720 | - if clip_menu || row_menu { | 4167 | + let list = this.picker.take().is_some(); |
| 4168 | + if clip_menu || row_menu || list { | ||
| 3721 | cx.notify(); | 4169 | cx.notify(); |
| 3722 | if key == ESCAPE { | 4170 | if key == ESCAPE { |
| 3723 | return; | 4171 | return; |
| @@ -3750,6 +4198,26 @@ impl Render for Player { | |||
| 3750 | } | 4198 | } |
| 3751 | } | 4199 | } |
| 3752 | })) | 4200 | })) |
| 4201 | + // A drop event carries no path of its own -- gpui only tells the | ||
| 4202 | + // target that something landed -- so the line that promises where | ||
| 4203 | + // it will land is fed by the drag's own moves, which do carry the | ||
| 4204 | + // pointer (gpui div.rs:282). On the root, because a drag crosses | ||
| 4205 | + // the window: it starts on a clip or on a library row and ends over | ||
| 4206 | + // a lane, and only an ancestor of both hears all of it. | ||
| 4207 | + .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| { | ||
| 4208 | + // The clip the payload named, wherever an edit mid-drag has | ||
| 4209 | + // since put it ([`Player::dragged`]): the line has to promise a | ||
| 4210 | + // landing for the take actually in the hand. | ||
| 4211 | + let drag = *event.drag(cx); | ||
| 4212 | + if let Some(idx) = this.dragged(&drag) { | ||
| 4213 | + this.preview_drop(drag.lane, idx, event.event.position.x, cx); | ||
| 4214 | + } | ||
| 4215 | + })) | ||
| 4216 | + .on_drag_move( | ||
| 4217 | + cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| { | ||
| 4218 | + this.preview_place(event.event.position.x, cx); | ||
| 4219 | + }), | ||
| 4220 | + ) | ||
| 3753 | // Scrubbing is tracked on the root because the pointer leaves the | 4221 | // Scrubbing is tracked on the root because the pointer leaves the |
| 3754 | // 6 px ruler on the first drag and its own listeners then stop | 4222 | // 6 px ruler on the first drag and its own listeners then stop |
| 3755 | // firing; the root's hitbox is the whole window. | 4223 | // firing; the root's hitbox is the whole window. |
| @@ -3758,7 +4226,7 @@ impl Render for Player { | |||
| 3758 | // the equalizer drag is tracked here for the ruler's reason. | 4226 | // the equalizer drag is tracked here for the ruler's reason. |
| 3759 | if this.eq_dragging { | 4227 | if this.eq_dragging { |
| 3760 | if event.pressed_button == Some(MouseButton::Left) { | 4228 | if event.pressed_button == Some(MouseButton::Left) { |
| 3761 | - this.drag_band(event.position.y, cx); | 4229 | + this.drag_band(event.position, cx); |
| 3762 | } else { | 4230 | } else { |
| 3763 | // Released outside the window: the up below never came, | 4231 | // Released outside the window: the up below never came, |
| 3764 | // so this is where the gesture ends -- and it still owes | 4232 | // so this is where the gesture ends -- and it still owes |
| @@ -3828,7 +4296,7 @@ impl Render for Player { | |||
| 3828 | if std::mem::take(&mut this.eq_dragging) { | 4296 | if std::mem::take(&mut this.eq_dragging) { |
| 3829 | // The release lands exactly, then the gesture is written | 4297 | // The release lands exactly, then the gesture is written |
| 3830 | // once -- the append-only table's whole reason. | 4298 | // once -- the append-only table's whole reason. |
| 3831 | - this.drag_band(event.position.y, cx); | 4299 | + this.drag_band(event.position, cx); |
| 3832 | this.commit_eq(cx); | 4300 | this.commit_eq(cx); |
| 3833 | return; | 4301 | return; |
| 3834 | } | 4302 | } |
| @@ -3918,7 +4386,7 @@ impl Render for Player { | |||
| 3918 | // Above the panel and only when there is one to show, so it costs | 4386 | // Above the panel and only when there is one to show, so it costs |
| 3919 | // the picture nothing the rest of the time. | 4387 | // the picture nothing the rest of the time. |
| 3920 | .children(self.notice_bar(cx)) | 4388 | .children(self.notice_bar(cx)) |
| 3921 | - .child(self.panel(position, duration, playing, cx)) | 4389 | + .child(self.panel(position, duration, state, cx)) |
| 3922 | // Over the panel it was opened on, and under the cards: it is only | 4390 | // Over the panel it was opened on, and under the cards: it is only |
| 3923 | // ever up while neither of them is (`modal`). | 4391 | // ever up while neither of them is (`modal`). |
| 3924 | .children(self.context_card(window.viewport_size(), cx)) | 4392 | .children(self.context_card(window.viewport_size(), cx)) |
| @@ -3930,11 +4398,14 @@ impl Render for Player { | |||
| 3930 | // column, and only one of the two is ever up. | 4398 | // column, and only one of the two is ever up. |
| 3931 | .children(self.keys_overlay(cx)) | 4399 | .children(self.keys_overlay(cx)) |
| 3932 | .children(self.export_card(window.viewport_size(), cx)) | 4400 | .children(self.export_card(window.viewport_size(), cx)) |
| 3933 | - .children(self.eq_card(cx)) | 4401 | + .children(self.eq_card(window.viewport_size(), cx)) |
| 3934 | .children(self.color_card(cx)) | 4402 | .children(self.color_card(cx)) |
| 3935 | .children(self.speed_card(cx)) | 4403 | .children(self.speed_card(cx)) |
| 3936 | .children(self.silence_card(cx)) | 4404 | .children(self.silence_card(cx)) |
| 3937 | .children(self.mix_card(cx)) | 4405 | .children(self.mix_card(cx)) |
| 4406 | + // Last, so it floats over whatever opened it -- the panel's button | ||
| 4407 | + // or a clip menu -- rather than under it. | ||
| 4408 | + .children(self.picker_card(window.viewport_size(), cx)) | ||
| 3938 | } | 4409 | } |
| 3939 | } | 4410 | } |
| 3940 | 4411 | ||
| @@ -4239,21 +4710,22 @@ impl Player { | |||
| 4239 | &self, | 4710 | &self, |
| 4240 | position: f64, | 4711 | position: f64, |
| 4241 | duration: f64, | 4712 | duration: f64, |
| 4242 | - playing: bool, | 4713 | + state: Transport, |
| 4243 | cx: &mut Context<Self>, | 4714 | cx: &mut Context<Self>, |
| 4244 | ) -> impl IntoElement { | 4715 | ) -> impl IntoElement { |
| 4245 | - // Where the playhead is *on the bed*, which at the fit is where along | 4716 | + // Where the playhead is *on the bed*, in pixels from its left edge. |
| 4246 | - // the timeline it is and zoomed in is where along the visible slice. | 4717 | + // Clamped to the bed because it is drawn as a width as well as an |
| 4247 | - // Clamped because it is drawn as a width as well as an offset, and the | 4718 | + // offset, and the view follows the playhead anyway, so it is never off |
| 4248 | - // view follows the playhead anyway, so it is never off the bed. | 4719 | + // the bed for long. |
| 4249 | - let filled = self.view.frac_at(position, duration).clamp(0., 1.); | 4720 | + let bed_w = f32::from(self.ruler.get().size.width); |
| 4721 | + let filled = self.scale.px_at(position).clamp(0., bed_w); | ||
| 4250 | // An export owns the hint slot and the ruler while it runs: the | 4722 | // An export owns the hint slot and the ruler while it runs: the |
| 4251 | // percentage and the accent bar are the same number, so the playhead | 4723 | // percentage and the accent bar are the same number, so the playhead |
| 4252 | // fill doubles as the progress bar for free. | 4724 | // fill doubles as the progress bar for free. |
| 4253 | let exporting = self.exporting().is_some(); | 4725 | let exporting = self.exporting().is_some(); |
| 4254 | // Everything but Import and Keys needs a timeline to act on: with none | 4726 | // Everything but Import and Keys needs a timeline to act on: with none |
| 4255 | // open they are dimmed rather than silently doing nothing. | 4727 | // open they are dimmed rather than silently doing nothing. |
| 4256 | - let live = self.session.is_some() && !exporting; | 4728 | + let live = state != Transport::Stopped && !exporting; |
| 4257 | // The project's own picture size, for the button that cycles it: read | 4729 | // The project's own picture size, for the button that cycles it: read |
| 4258 | // per render like everything else here, so a cycle shows on the button | 4730 | // per render like everything else here, so a cycle shows on the button |
| 4259 | // that made it. | 4731 | // that made it. |
| @@ -4269,7 +4741,7 @@ impl Player { | |||
| 4269 | // closure would hold it for as long as the iterator lives. | 4741 | // closure would hold it for as long as the iterator lives. |
| 4270 | let mut rows = Vec::new(); | 4742 | let mut rows = Vec::new(); |
| 4271 | for &lane in &lanes { | 4743 | for &lane in &lanes { |
| 4272 | - rows.push(self.lane_row(lane, duration, filled, cx)); | 4744 | + rows.push(self.lane_row(lane, filled, cx)); |
| 4273 | } | 4745 | } |
| 4274 | let (hint, filled) = if let Some(export) = self.exporting() { | 4746 | let (hint, filled) = if let Some(export) = self.exporting() { |
| 4275 | let progress = export.progress(); | 4747 | let progress = export.progress(); |
| @@ -4299,7 +4771,7 @@ impl Player { | |||
| 4299 | // of this line is what a narrow window truncates. | 4771 | // of this line is what a narrow window truncates. |
| 4300 | ( | 4772 | ( |
| 4301 | join_detail( | 4773 | join_detail( |
| 4302 | - &self.live_decode(position, playing), | 4774 | + &self.live_decode(position, state.is_playing()), |
| 4303 | &format!( | 4775 | &format!( |
| 4304 | "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ | 4776 | "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ |
| 4305 | import", | 4777 | import", |
| @@ -4338,9 +4810,9 @@ impl Player { | |||
| 4338 | .overflow_x_scroll() | 4810 | .overflow_x_scroll() |
| 4339 | .child(control( | 4811 | .child(control( |
| 4340 | "transport", | 4812 | "transport", |
| 4341 | - Some(transport_glyph(playing).into_any_element()), | 4813 | + Some(transport_glyph(state).into_any_element()), |
| 4342 | - if playing { "Pause" } else { "Play" }, | 4814 | + if state.is_playing() { "Pause" } else { "Play" }, |
| 4343 | - if nothing_to_play(self.session.as_ref()) && !playing { | 4815 | + if nothing_to_play(self.session.as_ref()) && !state.is_playing() { |
| 4344 | format!("{} — put a clip on a lane first", key(ActionId::Play)) | 4816 | format!("{} — put a clip on a lane first", key(ActionId::Play)) |
| 4345 | } else { | 4817 | } else { |
| 4346 | key(ActionId::Play) | 4818 | key(ActionId::Play) |
| @@ -4350,7 +4822,7 @@ impl Player { | |||
| 4350 | // against nothing (the key press answers with the | 4822 | // against nothing (the key press answers with the |
| 4351 | // notice). Still live while it *is* playing: a delete | 4823 | // notice). Still live while it *is* playing: a delete |
| 4352 | // can empty the timeline mid-play and that has to stop. | 4824 | // can empty the timeline mid-play and that has to stop. |
| 4353 | - live && (playing || !nothing_to_play(self.session.as_ref())), | 4825 | + live && (state.is_playing() || !nothing_to_play(self.session.as_ref())), |
| 4354 | cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), | 4826 | cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), |
| 4355 | )) | 4827 | )) |
| 4356 | .child(separator()) | 4828 | .child(separator()) |
| @@ -4447,35 +4919,38 @@ impl Player { | |||
| 4447 | )) | 4919 | )) |
| 4448 | .child(separator()) | 4920 | .child(separator()) |
| 4449 | // The size every clip is composed onto, which is also the | 4921 | // The size every clip is composed onto, which is also the |
| 4450 | - // size the export comes out at: the one project setting a | 4922 | + // size the export comes out at. Five sizes, so a click opens |
| 4451 | - // stroke used to be the only way to. Cycles exactly as the | 4923 | + // the list of them with this one marked and picks whichever |
| 4452 | - // key does, and says where it is now rather than opening a | 4924 | + // was meant: a button that stepped one on per press made the |
| 4453 | - // list to close again. | 4925 | + // user click round the ladder to get back to where they |
| 4926 | + // were. The stroke still steps, for the hand already on it. | ||
| 4454 | .child(control( | 4927 | .child(control( |
| 4455 | "resolution", | 4928 | "resolution", |
| 4456 | None, | 4929 | None, |
| 4457 | resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), | 4930 | resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), |
| 4458 | match resolution { | 4931 | match resolution { |
| 4459 | Some((w, h)) => format!( | 4932 | Some((w, h)) => format!( |
| 4460 | - "{} — the project is {w}x{h}; cycles source → 2160p → 1080p → 720p → 480p", | 4933 | + "click to pick a size — the project is {w}x{h}; {} steps to the next", |
| 4461 | key(ActionId::Resolution) | 4934 | key(ActionId::Resolution) |
| 4462 | ), | 4935 | ), |
| 4463 | None => format!("{} — open a file first", key(ActionId::Resolution)), | 4936 | None => format!("{} — open a file first", key(ActionId::Resolution)), |
| 4464 | }, | 4937 | }, |
| 4465 | live, | 4938 | live, |
| 4466 | - cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(cx)), | 4939 | + cx.listener(|this, event: &ClickEvent, _, cx| { |
| 4940 | + this.open_picker(Pick::Resolution, event.position(), cx) | ||
| 4941 | + }), | ||
| 4467 | )) | 4942 | )) |
| 4468 | // How much of the timeline the panel below is showing -- | 4943 | // How much of the timeline the panel below is showing -- |
| 4469 | // beside the resolution, since neither of them edits | 4944 | // beside the resolution, since neither of them edits |
| 4470 | // anything: they are both what is being looked at. The | 4945 | // anything: they are both what is being looked at. The |
| 4471 | - // middle one reads as the state (1.0x is the whole | 4946 | + // middle one says how much of it is on the bed, and is the |
| 4472 | - // timeline) and is the way back to it. | 4947 | + // way back to the whole of it. |
| 4473 | .child(control( | 4948 | .child(control( |
| 4474 | "zoom-out", | 4949 | "zoom-out", |
| 4475 | None, | 4950 | None, |
| 4476 | "−", | 4951 | "−", |
| 4477 | format!( | 4952 | format!( |
| 4478 | - "{} — show more of the timeline; stops at the whole of it", | 4953 | + "{} — show more of the timeline; stops at four hours on the bed", |
| 4479 | key(ActionId::ZoomOut) | 4954 | key(ActionId::ZoomOut) |
| 4480 | ), | 4955 | ), |
| 4481 | live, | 4956 | live, |
| @@ -4486,13 +4961,17 @@ impl Player { | |||
| 4486 | .child(control( | 4961 | .child(control( |
| 4487 | "zoom-fit", | 4962 | "zoom-fit", |
| 4488 | None, | 4963 | None, |
| 4489 | - format!("{:.1}x", self.view.zoom), | 4964 | + // How much timeline is on the bed, not a multiple of |
| 4965 | + // "the whole of it": the scale no longer knows what the | ||
| 4966 | + // whole of it is, and a number that changed on every | ||
| 4967 | + // import was a number that lied. | ||
| 4968 | + span_label(self.view().span()), | ||
| 4490 | format!( | 4969 | format!( |
| 4491 | "{} — fit the whole timeline; showing {} to {}", | 4970 | "{} — fit the whole timeline; showing {} to {}", |
| 4492 | key(ActionId::ZoomFit), | 4971 | key(ActionId::ZoomFit), |
| 4493 | - timecode(self.view.start, self.fps), | 4972 | + timecode(self.scale.start, self.fps), |
| 4494 | timecode( | 4973 | timecode( |
| 4495 | - (self.view.start + self.view.span(duration)).min(duration), | 4974 | + (self.scale.start + self.view().span()).min(duration), |
| 4496 | self.fps | 4975 | self.fps |
| 4497 | ) | 4976 | ) |
| 4498 | ), | 4977 | ), |
| @@ -4510,6 +4989,25 @@ impl Player { | |||
| 4510 | live, | 4989 | live, |
| 4511 | cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), | 4990 | cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), |
| 4512 | )) | 4991 | )) |
| 4992 | + // The magnet, beside the zoom for the zoom's own reason: it | ||
| 4993 | + // changes nothing on the timeline, it changes how the hand | ||
| 4994 | + // meets it. The label is the state, as the volume's is -- | ||
| 4995 | + // a toggle that looks the same either way says nothing. | ||
| 4996 | + .child(control( | ||
| 4997 | + "snap", | ||
| 4998 | + None, | ||
| 4999 | + if self.snap { "Snap" } else { "No snap" }, | ||
| 5000 | + format!( | ||
| 5001 | + "{} — {}", | ||
| 5002 | + key(ActionId::ToggleSnap), | ||
| 5003 | + match self.snap { | ||
| 5004 | + true => "drags and trims land on clip edges, the playhead and the start", | ||
| 5005 | + false => "drags and trims land exactly where the hand leaves them", | ||
| 5006 | + } | ||
| 5007 | + ), | ||
| 5008 | + live, | ||
| 5009 | + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)), | ||
| 5010 | + )) | ||
| 4513 | // Import is not here: it belongs to the media list it adds | 5011 | // Import is not here: it belongs to the media list it adds |
| 4514 | // to, and two doors into one action is a question about | 5012 | // to, and two doors into one action is a question about |
| 4515 | // which one is the real one. | 5013 | // which one is the real one. |
| @@ -4560,8 +5058,10 @@ impl Player { | |||
| 4560 | .child(control( | 5058 | .child(control( |
| 4561 | "keys", | 5059 | "keys", |
| 4562 | None, | 5060 | None, |
| 4563 | - "Keys", | 5061 | + "Actions", |
| 4564 | - "show and change the keybindings".to_string(), | 5062 | + // The pointer's way to every action there is, including |
| 5063 | + // the ones no button here has room for. | ||
| 5064 | + "do any action, or change the key that does it".to_string(), | ||
| 4565 | !exporting, | 5065 | !exporting, |
| 4566 | cx.listener(|this, _: &ClickEvent, _, cx| { | 5066 | cx.listener(|this, _: &ClickEvent, _, cx| { |
| 4567 | this.keys_open = !this.keys_open; | 5067 | this.keys_open = !this.keys_open; |
| @@ -4580,10 +5080,20 @@ impl Player { | |||
| 4580 | .gap(px(12.)) | 5080 | .gap(px(12.)) |
| 4581 | // Fixed width and one line: changing digits must not push | 5081 | // Fixed width and one line: changing digits must not push |
| 4582 | // the row around, nor wrap and change its height. | 5082 | // the row around, nor wrap and change its height. |
| 5083 | + // The timeline's own length, never the drawn one: a tail | ||
| 5084 | + // being dragged inflates the bed to the room that edge has | ||
| 5085 | + // ([`Player::drawn_duration`]), and for a still that room is | ||
| 5086 | + // ten minutes -- a total that jumped to 10:00:00 the moment | ||
| 5087 | + // a picture's edge was pressed, and back on release. | ||
| 4583 | .child(div().flex_none().w(px(TIME_W)).truncate().child(format!( | 5088 | .child(div().flex_none().w(px(TIME_W)).truncate().child(format!( |
| 4584 | "{} / {}", | 5089 | "{} / {}", |
| 4585 | timecode(position, self.fps), | 5090 | timecode(position, self.fps), |
| 4586 | - timecode(duration, self.fps) | 5091 | + timecode( |
| 5092 | + self.session | ||
| 5093 | + .as_ref() | ||
| 5094 | + .map_or(0., PlaybackSession::timeline_duration), | ||
| 5095 | + self.fps | ||
| 5096 | + ) | ||
| 4587 | ))) | 5097 | ))) |
| 4588 | .child( | 5098 | .child( |
| 4589 | div() | 5099 | div() |
| @@ -4643,7 +5153,7 @@ impl Player { | |||
| 4643 | if dy == 0. { | 5153 | if dy == 0. { |
| 4644 | return; | 5154 | return; |
| 4645 | } | 5155 | } |
| 4646 | - let anchor = frac_along(event.position.x, this.ruler.get()); | 5156 | + let anchor = px_along(event.position.x, this.ruler.get()); |
| 4647 | let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; | 5157 | let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; |
| 4648 | this.zoom(factor, Some(anchor), cx); | 5158 | this.zoom(factor, Some(anchor), cx); |
| 4649 | }, | 5159 | }, |
| @@ -4665,7 +5175,7 @@ impl Player { | |||
| 4665 | .child( | 5175 | .child( |
| 4666 | div() | 5176 | div() |
| 4667 | .h_full() | 5177 | .h_full() |
| 4668 | - .w(relative(filled)) | 5178 | + .w(px(filled)) |
| 4669 | .rounded(px(3.)) | 5179 | .rounded(px(3.)) |
| 4670 | .bg(rgb(ACCENT)), | 5180 | .bg(rgb(ACCENT)), |
| 4671 | ), | 5181 | ), |
| @@ -4771,83 +5281,115 @@ impl Player { | |||
| 4771 | ctrl: false, | 5281 | ctrl: false, |
| 4772 | } | 5282 | } |
| 4773 | .pretty(); | 5283 | .pretty(); |
| 4774 | - // Every stroke that works, under its heading, and both halves of the | 5284 | + // Every action there is, under its heading, and the strokes the modal |
| 4775 | - // list come from the registry: one row per action -- an action with two | 5285 | + // cards answer to beside them -- `keys_rows` is the whole of the order |
| 4776 | - // strokes reads as one line ("x or delete") and a rebind replaces that | 5286 | + // and every word in it comes off the registry. |
| 4777 | - // whole set -- then the strokes the modal cards answer to, which are | 5287 | + // |
| 4778 | - // shown but not offered, because nothing may unbind the way out. | 5288 | + // A row is two targets, not one: its label *does* the action, which is |
| 5289 | + // the pointer's way to the ones no button carries, and its stroke | ||
| 5290 | + // changes that stroke. An action with two strokes reads as one line | ||
| 5291 | + // ("x or delete") and a rebind replaces that whole set. | ||
| 4779 | let mut rows: Vec<AnyElement> = Vec::new(); | 5292 | let mut rows: Vec<AnyElement> = Vec::new(); |
| 4780 | - for category in keymap::Category::ALL { | 5293 | + let row = || { |
| 4781 | - let actions = ActionId::ALL | 5294 | + div() |
| 4782 | - .into_iter() | 5295 | + .flex() |
| 4783 | - .enumerate() | 5296 | + // The floor, not the height: a row that needed two lines |
| 4784 | - .filter(|(_, a)| a.category() == category); | 5297 | + // would otherwise paint over the one under it. |
| 4785 | - let fixed = keymap::FIXED.iter().filter(|f| f.category == category); | 5298 | + .min_h(px(KEYS_ROW_H)) |
| 4786 | - let mut headed = false; | 5299 | + .items_center() |
| 4787 | - let mut head = |rows: &mut Vec<AnyElement>| { | 5300 | + .justify_between() |
| 4788 | - if !std::mem::replace(&mut headed, true) { | 5301 | + .gap(px(12.)) |
| 4789 | - rows.push( | 5302 | + .px(px(6.)) |
| 4790 | - div() | 5303 | + .rounded(px(3.)) |
| 4791 | - .flex_none() | 5304 | + }; |
| 4792 | - .px(px(6.)) | 5305 | + for (i, key_row) in keys_rows().into_iter().enumerate() { |
| 4793 | - .pt(px(4.)) | 5306 | + rows.push(match key_row { |
| 4794 | - .text_size(px(11.)) | 5307 | + KeyRow::Head(category) => div() |
| 4795 | - .text_color(rgb(INK_DIM)) | 5308 | + .flex_none() |
| 4796 | - .child(category.label()) | 5309 | + .px(px(6.)) |
| 4797 | - .into_any_element(), | 5310 | + .pt(px(4.)) |
| 4798 | - ); | 5311 | + .text_size(px(11.)) |
| 4799 | - } | 5312 | + .text_color(rgb(INK_DIM)) |
| 4800 | - }; | 5313 | + .child(category.label()) |
| 4801 | - for (i, action) in actions { | 5314 | + .into_any_element(), |
| 4802 | - head(&mut rows); | 5315 | + KeyRow::Act(action) => { |
| 4803 | - let capturing = self.rebinding == Some(action); | 5316 | + let capturing = self.rebinding == Some(action); |
| 4804 | - let out = out.clone(); | 5317 | + // Why the label half will not answer, if it will not: the |
| 4805 | - rows.push( | 5318 | + // registry's one answer, the same the clip menu dims by. |
| 4806 | - div() | 5319 | + let refusal = self.enable(action, None); |
| 4807 | - .id(("bind", i)) | 5320 | + let out = out.clone(); |
| 4808 | - .flex() | 5321 | + row() |
| 4809 | - // The floor, not the height: a row that needed two lines | ||
| 4810 | - // would otherwise paint over the one under it. | ||
| 4811 | - .min_h(px(KEYS_ROW_H)) | ||
| 4812 | - .items_center() | ||
| 4813 | - .justify_between() | ||
| 4814 | - .gap(px(12.)) | ||
| 4815 | - .px(px(6.)) | ||
| 4816 | - .rounded(px(3.)) | ||
| 4817 | - .cursor_pointer() | ||
| 4818 | - .hover(|s| s.bg(rgb(HOVER))) | ||
| 4819 | .when(capturing, |d| d.bg(rgb(SELECTED))) | 5322 | .when(capturing, |d| d.bg(rgb(SELECTED))) |
| 4820 | - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 5323 | + .child( |
| 4821 | - this.rebinding = Some(action); | ||
| 4822 | - cx.notify(); | ||
| 4823 | - })) | ||
| 4824 | - .child(action.label()) | ||
| 4825 | - .child(if capturing { | ||
| 4826 | div() | 5324 | div() |
| 4827 | - .text_color(rgb(INK_DIM)) | 5325 | + .id(("do", i)) |
| 4828 | - .child(format!("press a key — {out} cancels")) | 5326 | + .flex_1() |
| 4829 | - } else { | 5327 | + .min_w(px(0.)) |
| 4830 | - div().child(self.keymap.display(action)) | 5328 | + .flex() |
| 4831 | - }) | 5329 | + .min_h(px(KEYS_ROW_H)) |
| 4832 | - .into_any_element(), | 5330 | + .items_center() |
| 4833 | - ); | 5331 | + .child(action.label()) |
| 4834 | - } | 5332 | + // The reason rides on the label rather than in |
| 4835 | - for f in fixed { | 5333 | + // the stroke column, which the rebind half |
| 4836 | - head(&mut rows); | 5334 | + // needs whatever the editor's state is: an |
| 4837 | - rows.push( | 5335 | + // action nobody can ask for right now is still |
| 4838 | - div() | 5336 | + // one whose key may be changed. |
| 4839 | - .flex() | 5337 | + .when_some(refusal.why(), |d, why| { |
| 4840 | - .min_h(px(KEYS_ROW_H)) | 5338 | + let why: SharedString = why.into(); |
| 4841 | - .items_center() | 5339 | + d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into()) |
| 4842 | - .justify_between() | 5340 | + }) |
| 4843 | - .gap(px(12.)) | 5341 | + .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) |
| 4844 | - .px(px(6.)) | 5342 | + .when(refusal.yes(), |d| { |
| 5343 | + d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click( | ||
| 5344 | + cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5345 | + // The card goes first: several of | ||
| 5346 | + // these open a card of their own, | ||
| 5347 | + // and every edit moves the indices | ||
| 5348 | + // the menus are holding. | ||
| 5349 | + this.keys_open = false; | ||
| 5350 | + this.rebinding = None; | ||
| 5351 | + this.act(action, cx); | ||
| 5352 | + cx.notify(); | ||
| 5353 | + }), | ||
| 5354 | + ) | ||
| 5355 | + }), | ||
| 5356 | + ) | ||
| 5357 | + .child( | ||
| 5358 | + // ponytail: the column is as wide as the stroke it | ||
| 5359 | + // prints, so a one-character chord gives this half a | ||
| 5360 | + // hit area under the 24px WCAG 2.5.8 floor -- tall | ||
| 5361 | + // enough, narrow. Upgrade: a min_w of HIT_MIN here. | ||
| 5362 | + div() | ||
| 5363 | + .id(("bind", i)) | ||
| 5364 | + .flex_none() | ||
| 5365 | + .flex() | ||
| 5366 | + .min_h(px(KEYS_ROW_H)) | ||
| 5367 | + .items_center() | ||
| 5368 | + .cursor_pointer() | ||
| 5369 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 5370 | + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5371 | + this.rebinding = Some(action); | ||
| 5372 | + cx.notify(); | ||
| 5373 | + })) | ||
| 5374 | + .child(if capturing { | ||
| 5375 | + div() | ||
| 5376 | + .text_color(rgb(INK_DIM)) | ||
| 5377 | + .child(format!("press a key — {out} cancels")) | ||
| 5378 | + } else { | ||
| 5379 | + div().child(self.keymap.display(action)) | ||
| 5380 | + }), | ||
| 5381 | + ) | ||
| 5382 | + .into_any_element() | ||
| 5383 | + } | ||
| 5384 | + KeyRow::Fixed(f) => { | ||
| 5385 | + let f = &keymap::FIXED[f]; | ||
| 5386 | + row() | ||
| 4845 | .child(f.label) | 5387 | .child(f.label) |
| 4846 | // Dim, and no hover: this one is not a row you can click. | 5388 | // Dim, and no hover: this one is not a row you can click. |
| 4847 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) | 5389 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) |
| 4848 | - .into_any_element(), | 5390 | + .into_any_element() |
| 4849 | - ); | 5391 | + } |
| 4850 | - } | 5392 | + }); |
| 4851 | } | 5393 | } |
| 4852 | Some( | 5394 | Some( |
| 4853 | div() | 5395 | div() |
| @@ -4874,7 +5416,7 @@ impl Player { | |||
| 4874 | // Title and instruction are two children, never one | 5416 | // Title and instruction are two children, never one |
| 4875 | // wrapping line: a fixed-height slot whose text wrapped | 5417 | // wrapping line: a fixed-height slot whose text wrapped |
| 4876 | // painted its second line over the first row. | 5418 | // painted its second line over the first row. |
| 4877 | - .child(div().flex_none().px(px(6.)).child("Keybindings")) | 5419 | + .child(div().flex_none().px(px(6.)).child("Actions & keys")) |
| 4878 | // One status line, under the title where the eye starts. | 5420 | // One status line, under the title where the eye starts. |
| 4879 | // A refusal takes it over -- it is the more urgent of the | 5421 | // A refusal takes it over -- it is the more urgent of the |
| 4880 | // two, and the notice bar it would otherwise appear in is | 5422 | // two, and the notice bar it would otherwise appear in is |
| @@ -4892,7 +5434,10 @@ impl Player { | |||
| 4892 | .child( | 5434 | .child( |
| 4893 | self.notice | 5435 | self.notice |
| 4894 | .clone() | 5436 | .clone() |
| 4895 | - .unwrap_or_else(|| "click a row, then press a key".into()), | 5437 | + .unwrap_or_else(|| { |
| 5438 | + "click an action to do it · click its key to change it" | ||
| 5439 | + .into() | ||
| 5440 | + }), | ||
| 4896 | ), | 5441 | ), |
| 4897 | ) | 5442 | ) |
| 4898 | // Capped and scrolling rather than as tall as the action | 5443 | // Capped and scrolling rather than as tall as the action |
| @@ -5141,9 +5686,11 @@ impl Player { | |||
| 5141 | // The other half of the file, and the one this card used to write at a | 5686 | // The other half of the file, and the one this card used to write at a |
| 5142 | // fixed rate without saying so: what the *sound* is coded at, for every | 5687 | // fixed rate without saying so: what the *sound* is coded at, for every |
| 5143 | // format that codes it -- the AAC inside a video export as much as an | 5688 | // format that codes it -- the AAC inside a video export as much as an |
| 5144 | - // MP3. One row that cycles, like the container's, rather than four more | 5689 | + // MP3. Four rates, so the pointer gets the *list* of them |
| 5145 | - // rows above the fold; dimmed with the reason where this timeline has | 5690 | + // ([`Pick::AudioRate`]) rather than a button clicked round -- the |
| 5146 | - // no rate to pick, like the quality rows are. | 5691 | + // resolution row's rule, and the key still steps as `ctrl+r` still |
| 5692 | + // does. Dimmed with the reason where this timeline has no rate to pick, | ||
| 5693 | + // like the quality rows are. | ||
| 5147 | let sound = self.audio_rate_refusal(); | 5694 | let sound = self.audio_rate_refusal(); |
| 5148 | let mut r = entry( | 5695 | let mut r = entry( |
| 5149 | ("sound", 0), | 5696 | ("sound", 0), |
| @@ -5151,20 +5698,14 @@ impl Player { | |||
| 5151 | "Sound".into(), | 5698 | "Sound".into(), |
| 5152 | match sound { | 5699 | match sound { |
| 5153 | Some(why) => why.into(), | 5700 | Some(why) => why.into(), |
| 5154 | - None => format!( | 5701 | + None => format!("{} kbps — b steps", self.audio_kbps).into(), |
| 5155 | - "{} kbps — b for {}", | ||
| 5156 | - self.audio_kbps, | ||
| 5157 | - next_audio_kbps(self.audio_kbps) | ||
| 5158 | - ) | ||
| 5159 | - .into(), | ||
| 5160 | }, | 5702 | }, |
| 5161 | false, | 5703 | false, |
| 5162 | sound.is_none(), | 5704 | sound.is_none(), |
| 5163 | ); | 5705 | ); |
| 5164 | if sound.is_none() { | 5706 | if sound.is_none() { |
| 5165 | - r = r.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | 5707 | + r = r.on_click(cx.listener(|this, event: &ClickEvent, _, cx| { |
| 5166 | - this.cycle_audio_kbps(); | 5708 | + this.open_picker(Pick::AudioRate, event.position(), cx) |
| 5167 | - cx.notify(); | ||
| 5168 | })); | 5709 | })); |
| 5169 | } | 5710 | } |
| 5170 | list.push(r.into_any_element()); | 5711 | list.push(r.into_any_element()); |
| @@ -5359,22 +5900,30 @@ impl Player { | |||
| 5359 | } | 5900 | } |
| 5360 | 5901 | ||
| 5361 | /// The equalizer of one audio clip: its frequency response drawn as a | 5902 | /// The equalizer of one audio clip: its frequency response drawn as a |
| 5362 | - /// curve, a handle per band sitting on it, and a row that flattens them | 5903 | + /// curve, a handle per band sitting on it, each band's own bell under the |
| 5363 | - /// all. The curve is the clip's actual filter (`EqParams::response_db` | 5904 | + /// sum, and a row that reads and moves the picked band's three numbers. The |
| 5364 | - /// reads the coefficients the samples go through), and it is redrawn on | 5905 | + /// curve is the clip's actual filter (`EqParams::response_db` reads the |
| 5365 | - /// every pointer sample of a drag, so the shape bends under the hand. | 5906 | + /// coefficients the samples go through), and it is redrawn on every pointer |
| 5907 | + /// sample of a drag, so the shape bends under the hand. | ||
| 5366 | /// | 5908 | /// |
| 5367 | - /// The same scrim and width as the other two cards, and the same plain divs | 5909 | + /// Wider than the other cards and wider still on a bigger window |
| 5368 | - /// -- nothing here takes focus, so the root keeps the keyboard and the | 5910 | + /// ([`eq_card_w`]): every pixel across is frequency resolution, which none |
| 5369 | - /// card's own strokes (`1`–`5`, up, down, `r`) reach it. | 5911 | + /// of the row-shaped cards have any use for. The same scrim and the same |
| 5912 | + /// plain divs -- nothing here takes focus, so the root keeps the keyboard | ||
| 5913 | + /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`, | ||
| 5914 | + /// `s`) reach it. | ||
| 5370 | /// | 5915 | /// |
| 5371 | /// Every change is written at the clip as it is made | 5916 | /// Every change is written at the clip as it is made |
| 5372 | /// ([`Player::commit_eq`]), so what the card shows is always what is | 5917 | /// ([`Player::commit_eq`]), so what the card shows is always what is |
| 5373 | /// playing: there is no OK button to forget, and closing it changes | 5918 | /// playing: there is no OK button to forget, and closing it changes |
| 5374 | /// nothing. What takes a curve back off is undo, like every other edit. | 5919 | /// nothing. What takes a curve back off is undo, like every other edit. |
| 5375 | - fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> { | 5920 | + fn eq_card( |
| 5376 | - let (lane, idx) = self.eq_open?; | 5921 | + &self, |
| 5377 | - // The rate the engine filters this timeline at, so the drawn curve is | 5922 | + viewport: Size<Pixels>, |
| 5923 | + cx: &mut Context<Self>, | ||
| 5924 | + ) -> Option<impl IntoElement> { | ||
| 5925 | + let (lane, idx) = self.eq_open?; | ||
| 5926 | + // The rate the engine filters this timeline at, so the drawn curve is | ||
| 5378 | // the one those coefficients make -- near the top of the axis a 44.1 kHz | 5927 | // the one those coefficients make -- near the top of the axis a 44.1 kHz |
| 5379 | // clip and a 48 kHz one are not the same shape. | 5928 | // clip and a 48 kHz one are not the same shape. |
| 5380 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); | 5929 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); |
| @@ -5426,13 +5975,20 @@ impl Player { | |||
| 5426 | .bg(rgb(HOVER_DIM)) | 5975 | .bg(rgb(HOVER_DIM)) |
| 5427 | .cursor_pointer() | 5976 | .cursor_pointer() |
| 5428 | // The press picks the band under it *and* is already the first | 5977 | // The press picks the band under it *and* is already the first |
| 5429 | - // sample of the drag, so a plain click sets a value. | 5978 | + // sample of the drag, so a plain click sets a value. A second click |
| 5979 | + // takes that band back to flat instead: the gesture that undoes one | ||
| 5980 | + // handle, with no modifier to remember. | ||
| 5430 | .on_mouse_down( | 5981 | .on_mouse_down( |
| 5431 | MouseButton::Left, | 5982 | MouseButton::Left, |
| 5432 | cx.listener(|this, event: &MouseDownEvent, _, cx| { | 5983 | cx.listener(|this, event: &MouseDownEvent, _, cx| { |
| 5433 | this.eq_band = this.nearest_band(event.position.x); | 5984 | this.eq_band = this.nearest_band(event.position.x); |
| 5985 | + if event.click_count >= 2 { | ||
| 5986 | + this.eq_dragging = false; | ||
| 5987 | + this.nudge_band(|b| b.gain_db = 0., cx); | ||
| 5988 | + return; | ||
| 5989 | + } | ||
| 5434 | this.eq_dragging = true; | 5990 | this.eq_dragging = true; |
| 5435 | - this.drag_band(event.position.y, cx); | 5991 | + this.drag_band(event.position, cx); |
| 5436 | }), | 5992 | }), |
| 5437 | ) | 5993 | ) |
| 5438 | .child(bounds_probe(self.eq_graph.clone())) | 5994 | .child(bounds_probe(self.eq_graph.clone())) |
| @@ -5524,7 +6080,7 @@ impl Player { | |||
| 5524 | }) | 6080 | }) |
| 5525 | .child( | 6081 | .child( |
| 5526 | div() | 6082 | div() |
| 5527 | - .w(px(KEYS_W)) | 6083 | + .w(px(eq_card_w(f32::from(viewport.width)))) |
| 5528 | .flex() | 6084 | .flex() |
| 5529 | .flex_col() | 6085 | .flex_col() |
| 5530 | .gap(px(2.)) | 6086 | .gap(px(2.)) |
| @@ -5545,28 +6101,15 @@ impl Player { | |||
| 5545 | .text_size(px(11.)) | 6101 | .text_size(px(11.)) |
| 5546 | .text_color(rgb(INK_DIM)) | 6102 | .text_color(rgb(INK_DIM)) |
| 5547 | .child(self.notice.clone().unwrap_or_else(|| { | 6103 | .child(self.notice.clone().unwrap_or_else(|| { |
| 5548 | - "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into() | 6104 | + "drag a handle, or a digit picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum, esc closes".into() |
| 5549 | })), | 6105 | })), |
| 5550 | ) | 6106 | ) |
| 5551 | .child(graph) | 6107 | .child(graph) |
| 5552 | - // Which band the keyboard is holding and what it is set | 6108 | + // Which band the keyboard is holding and every number it |
| 5553 | - // to: the curve shows the sum, and a band pushed against | 6109 | + // is set to, each with the pair of buttons that moves it: |
| 5554 | - // one pulling the other way is not readable off it. | 6110 | + // the curve shows the sum, and a band pushed against one |
| 5555 | - .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( | 6111 | + // pulling the other way is not readable off it. |
| 5556 | - match picked { | 6112 | + .child(self.eq_numbers(picked, cx)) |
| 5557 | - // Q as well as the two the curve shows: it is | ||
| 5558 | - // how wide the hump under the handle is, and | ||
| 5559 | - // nothing else on the card says so. | ||
| 5560 | - Some(band) => format!( | ||
| 5561 | - "{} {} {:+.1} dB — Q {:.2}", | ||
| 5562 | - self.eq_band + 1, | ||
| 5563 | - band_label(band), | ||
| 5564 | - band.gain_db, | ||
| 5565 | - band.q | ||
| 5566 | - ), | ||
| 5567 | - None => "no bands".into(), | ||
| 5568 | - }, | ||
| 5569 | - )) | ||
| 5570 | .child( | 6113 | .child( |
| 5571 | div() | 6114 | div() |
| 5572 | .mt(px(4.)) | 6115 | .mt(px(4.)) |
| @@ -5590,7 +6133,45 @@ impl Player { | |||
| 5590 | } | 6133 | } |
| 5591 | this.commit_eq(cx); | 6134 | this.commit_eq(cx); |
| 5592 | })) | 6135 | })) |
| 5593 | - .child("Flatten"), | 6136 | + .child("Flatten all"), |
| 6137 | + ) | ||
| 6138 | + // The two that change how many bands there are. | ||
| 6139 | + // The engine takes any cascade -- the count was | ||
| 6140 | + // only ever fixed because this card had no way | ||
| 6141 | + // to say otherwise. | ||
| 6142 | + .child( | ||
| 6143 | + div() | ||
| 6144 | + .id("eq-add") | ||
| 6145 | + .flex() | ||
| 6146 | + .flex_1() | ||
| 6147 | + .h(px(CONTROL_H)) | ||
| 6148 | + .items_center() | ||
| 6149 | + .justify_center() | ||
| 6150 | + .rounded(px(3.)) | ||
| 6151 | + .bg(rgb(CHROME)) | ||
| 6152 | + .cursor_pointer() | ||
| 6153 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 6154 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 6155 | + this.add_band(cx) | ||
| 6156 | + })) | ||
| 6157 | + .child("Add band"), | ||
| 6158 | + ) | ||
| 6159 | + .child( | ||
| 6160 | + div() | ||
| 6161 | + .id("eq-remove") | ||
| 6162 | + .flex() | ||
| 6163 | + .flex_1() | ||
| 6164 | + .h(px(CONTROL_H)) | ||
| 6165 | + .items_center() | ||
| 6166 | + .justify_center() | ||
| 6167 | + .rounded(px(3.)) | ||
| 6168 | + .bg(rgb(CHROME)) | ||
| 6169 | + .cursor_pointer() | ||
| 6170 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 6171 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 6172 | + this.remove_band(cx) | ||
| 6173 | + })) | ||
| 6174 | + .child("Remove band"), | ||
| 5594 | ) | 6175 | ) |
| 5595 | // The analyser's switch, next to the one other | 6176 | // The analyser's switch, next to the one other |
| 5596 | // button the card has: `s` does the same, and a | 6177 | // button the card has: `s` does the same, and a |
| @@ -5625,6 +6206,103 @@ impl Player { | |||
| 5625 | ) | 6206 | ) |
| 5626 | } | 6207 | } |
| 5627 | 6208 | ||
| 6209 | + /// The picked band's three numbers -- where it sits, how far it pushes and | ||
| 6210 | + /// how wide it is -- each beside the pair of buttons that moves it. The | ||
| 6211 | + /// arrows do the same three things, but a value only a key can change is a | ||
| 6212 | + /// value a hand on the pointer cannot reach at all, which is the same reason | ||
| 6213 | + /// [`Player::mbps_steppers`] exists. | ||
| 6214 | + fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context<Self>) -> impl IntoElement { | ||
| 6215 | + let row = div() | ||
| 6216 | + .flex_none() | ||
| 6217 | + .flex() | ||
| 6218 | + .items_center() | ||
| 6219 | + .gap(px(10.)) | ||
| 6220 | + .px(px(6.)) | ||
| 6221 | + .text_size(px(11.)); | ||
| 6222 | + let Some(band) = picked.copied() else { | ||
| 6223 | + return row.child("no bands — a adds one"); | ||
| 6224 | + }; | ||
| 6225 | + let step = |id: &'static str, | ||
| 6226 | + label: &'static str, | ||
| 6227 | + change: fn(&mut Band), | ||
| 6228 | + cx: &mut Context<Self>| { | ||
| 6229 | + div() | ||
| 6230 | + .id(id) | ||
| 6231 | + .flex() | ||
| 6232 | + .w(px(HIT_MIN)) | ||
| 6233 | + .h(px(HIT_MIN)) | ||
| 6234 | + .items_center() | ||
| 6235 | + .justify_center() | ||
| 6236 | + .rounded(px(3.)) | ||
| 6237 | + .bg(rgb(CHROME)) | ||
| 6238 | + .cursor_pointer() | ||
| 6239 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 6240 | + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 6241 | + this.nudge_band(change, cx) | ||
| 6242 | + })) | ||
| 6243 | + .child(label) | ||
| 6244 | + }; | ||
| 6245 | + let number = |value: String, | ||
| 6246 | + ids: (&'static str, &'static str), | ||
| 6247 | + by: (fn(&mut Band), fn(&mut Band)), | ||
| 6248 | + cx: &mut Context<Self>| { | ||
| 6249 | + div() | ||
| 6250 | + .flex() | ||
| 6251 | + .items_center() | ||
| 6252 | + .gap(px(4.)) | ||
| 6253 | + .child(div().child(value)) | ||
| 6254 | + .child(step(ids.0, "−", by.0, cx)) | ||
| 6255 | + .child(step(ids.1, "+", by.1, cx)) | ||
| 6256 | + }; | ||
| 6257 | + row.child(format!( | ||
| 6258 | + "Band {} of {}", | ||
| 6259 | + self.eq_band + 1, | ||
| 6260 | + self.eq_params.bands.len() | ||
| 6261 | + )) | ||
| 6262 | + .child(number( | ||
| 6263 | + band_label(&band), | ||
| 6264 | + ("eq-freq-down", "eq-freq-up"), | ||
| 6265 | + ( | ||
| 6266 | + |b| b.freq_hz /= EQ_FREQ_STEP, | ||
| 6267 | + |b| b.freq_hz *= EQ_FREQ_STEP, | ||
| 6268 | + ), | ||
| 6269 | + cx, | ||
| 6270 | + )) | ||
| 6271 | + .child(number( | ||
| 6272 | + format!("{:+.1} dB", band.gain_db), | ||
| 6273 | + ("eq-gain-down", "eq-gain-up"), | ||
| 6274 | + (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP), | ||
| 6275 | + cx, | ||
| 6276 | + )) | ||
| 6277 | + // Q is width, so its buttons are labelled by what they *do* to the | ||
| 6278 | + // hump rather than by which way the number goes: a wider band is a | ||
| 6279 | + // smaller Q, and nobody should have to know that to use the card. | ||
| 6280 | + .child(number( | ||
| 6281 | + format!("Q {:.2}", band.q), | ||
| 6282 | + ("eq-q-wider", "eq-q-narrower"), | ||
| 6283 | + (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP), | ||
| 6284 | + cx, | ||
| 6285 | + )) | ||
| 6286 | + .child( | ||
| 6287 | + div() | ||
| 6288 | + .id("eq-flat-band") | ||
| 6289 | + .flex() | ||
| 6290 | + .h(px(HIT_MIN)) | ||
| 6291 | + .px(px(8.)) | ||
| 6292 | + .items_center() | ||
| 6293 | + .rounded(px(3.)) | ||
| 6294 | + .bg(rgb(CHROME)) | ||
| 6295 | + .cursor_pointer() | ||
| 6296 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 6297 | + .on_click( | ||
| 6298 | + cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 6299 | + this.nudge_band(|b| b.gain_db = 0., cx) | ||
| 6300 | + }), | ||
| 6301 | + ) | ||
| 6302 | + .child("Flatten this"), | ||
| 6303 | + ) | ||
| 6304 | + } | ||
| 6305 | + | ||
| 5628 | /// The colour card: the graded frame's histogram over a row per control, | 6306 | /// The colour card: the graded frame's histogram over a row per control, |
| 5629 | /// each row a bar the pointer drags straight to a value -- no stepper | 6307 | /// each row a bar the pointer drags straight to a value -- no stepper |
| 5630 | /// buttons, because a slider is a thing to pull, and the arrow keys still | 6308 | /// buttons, because a slider is a thing to pull, and the arrow keys still |
| @@ -6462,7 +7140,6 @@ impl Player { | |||
| 6462 | let menu = self.context_menu?; | 7140 | let menu = self.context_menu?; |
| 6463 | let session = self.session.as_ref()?; | 7141 | let session = self.session.as_ref()?; |
| 6464 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; | 7142 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; |
| 6465 | - let playhead = frame_at(session.now(), self.fps); | ||
| 6466 | let source = session.sources().get(clip.source).cloned()?; | 7143 | let source = session.sources().get(clip.source).cloned()?; |
| 6467 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); | 7144 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); |
| 6468 | let row = |n: usize| { | 7145 | let row = |n: usize| { |
| @@ -6516,7 +7193,20 @@ impl Player { | |||
| 6516 | } | 7193 | } |
| 6517 | } else { | 7194 | } else { |
| 6518 | for action in MENU_ITEMS { | 7195 | for action in MENU_ITEMS { |
| 6519 | - let enabled = applicable(&clip, menu.lane, action, playhead); | 7196 | + // The registry's own answer, the same one the actions card |
| 7197 | + // dims a row with -- and a row that takes no click says *why* | ||
| 7198 | + // rather than printing a stroke that would do nothing. | ||
| 7199 | + let refusal = self.enable(action, Some((menu.lane, menu.idx))); | ||
| 7200 | + // A grade on a waveform, an equalizer on a picture, a silence | ||
| 7201 | + // scan on a still: things that do not exist for what was | ||
| 7202 | + // right-clicked, so the menu is the list of what this clip can | ||
| 7203 | + // do rather than the registry with most of it struck through. | ||
| 7204 | + // The state refusals below stay, dimmed and saying why -- the | ||
| 7205 | + // next click of the playhead lights them. | ||
| 7206 | + if !refusal.listed() { | ||
| 7207 | + continue; | ||
| 7208 | + } | ||
| 7209 | + let enabled = refusal.yes(); | ||
| 6520 | // The one item that is not about this clip says so, and says it | 7210 | // The one item that is not about this clip says so, and says it |
| 6521 | // here rather than in the registry: the stroke is global too, | 7211 | // here rather than in the registry: the stroke is global too, |
| 6522 | // but its row in the keys menu is not sitting on a clip. | 7212 | // but its row in the keys menu is not sitting on a clip. |
| @@ -6528,20 +7218,42 @@ impl Player { | |||
| 6528 | rows.push( | 7218 | rows.push( |
| 6529 | row(rows.len()) | 7219 | row(rows.len()) |
| 6530 | .child(label) | 7220 | .child(label) |
| 6531 | - .child( | 7221 | + .child(match refusal.why() { |
| 6532 | - div() | 7222 | + // One truncated line, like the details side: a |
| 7223 | + // reason that wrapped would make the card taller | ||
| 7224 | + // than the height `menu_at` placed it by. | ||
| 7225 | + Some(why) => div() | ||
| 7226 | + .min_w(px(0.)) | ||
| 7227 | + .truncate() | ||
| 7228 | + .text_size(px(11.)) | ||
| 7229 | + .text_color(rgb(INK_DIM)) | ||
| 7230 | + .child(why), | ||
| 7231 | + None => div() | ||
| 6533 | .text_color(rgb(INK_DIM)) | 7232 | .text_color(rgb(INK_DIM)) |
| 6534 | .child(self.keymap.display(action)), | 7233 | .child(self.keymap.display(action)), |
| 6535 | - ) | 7234 | + }) |
| 6536 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) | 7235 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) |
| 6537 | .when(enabled, |d| { | 7236 | .when(enabled, |d| { |
| 6538 | d.cursor_pointer() | 7237 | d.cursor_pointer() |
| 6539 | .hover(|s| s.bg(rgb(HOVER))) | 7238 | .hover(|s| s.bg(rgb(HOVER))) |
| 6540 | - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 7239 | + .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| { |
| 6541 | // Closed first: the action moves the very | 7240 | // Closed first: the action moves the very |
| 6542 | // indices this menu is holding. | 7241 | // indices this menu is holding. |
| 6543 | this.context_menu = None; | 7242 | this.context_menu = None; |
| 6544 | - this.act(action, cx); | 7243 | + // The one item that is a *choice* and not a |
| 7244 | + // doing: four policies, so the pointer gets | ||
| 7245 | + // the list of them on this clip rather than | ||
| 7246 | + // the next one stepped to behind the click. | ||
| 7247 | + // The stroke still steps -- same door. | ||
| 7248 | + if action == ActionId::Fit { | ||
crates/engine-hw/src/lib.rsmodified+4 -3
| @@ -59,7 +59,8 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle; | |||
| 59 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' | 59 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' |
| 60 | /// files at `Demuxer`). | 60 | /// files at `Demuxer`). |
| 61 | /// | 61 | /// |
| 62 | -/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main. | 62 | +/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main at |
| 63 | +/// either depth. | ||
| 63 | /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit | 64 | /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit |
| 64 | /// I420 every frame here is ([`Session::emit`]). | 65 | /// I420 every frame here is ([`Session::emit`]). |
| 65 | /// | 66 | /// |
| @@ -67,8 +68,8 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle; | |||
| 67 | /// interface all the way to the renderer. That costs the low two bits of a Main | 68 | /// interface all the way to the renderer. That costs the low two bits of a Main |
| 68 | /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every | 69 | /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every |
| 69 | /// stage between here and the texture upload, not to this file. | 70 | /// stage between here and the texture upload, not to this file. |
| 70 | -/// VP9 profile 2 and 10-bit AV1 are still refused by `Demuxer`: neither codec | 71 | +/// VP9 profile 2 is still refused by `Demuxer`: a VP9 stream does not state its |
| 71 | -/// states its depth where this reads it. | 72 | +/// depth where that reads it (an `av1C` and an `hvcC` both do). |
| 72 | enum Decoder { | 73 | enum Decoder { |
| 73 | H264(Dec<H264>), | 74 | H264(Dec<H264>), |
| 74 | Hevc(Dec<H265>), | 75 | Hevc(Dec<H265>), |
crates/engine/Cargo.tomlmodified+10 -0
| @@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [ | |||
| 66 | ] } | 66 | ] } |
| 67 | oxideav-ac3 = "=0.0.10" | 67 | oxideav-ac3 = "=0.0.10" |
| 68 | oxideav-core = "0.1.34" | 68 | oxideav-core = "0.1.34" |
| 69 | +# The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- | ||
| 70 | +# `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which | ||
| 71 | +# is why both names are needed for the three formats. MIT, pure Rust, and both | ||
| 72 | +# asked for without their default features: nothing here *draws* a cue yet (see | ||
| 73 | +# `crate::subtitle`), so the rendering stacks are dead weight. Only `oxideav-ass` | ||
| 74 | +# actually loses one -- it depends on `oxideav-subtitle` with defaults on, so | ||
| 75 | +# that crate's `text` feature (the bitmap font and rasterizer) is unified back | ||
| 76 | +# in whatever this line says. Nothing here calls into it. | ||
| 77 | +oxideav-subtitle = { version = "0.1.2", default-features = false } | ||
| 78 | +oxideav-ass = { version = "0.0.9", default-features = false } | ||
| 69 | # The software AV1 encoder, and the only new name in this list that was already | 79 | # The software AV1 encoder, and the only new name in this list that was already |
| 70 | # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image | 80 | # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image |
| 71 | # crate, so this links what the build already compiled. BSD-2 with the AOM | 81 | # crate, so this links what the build already compiled. BSD-2 with the AOM |
crates/engine/src/audio.rsmodified+381 -90
| @@ -66,10 +66,6 @@ const PRE_ROLL: u32 = 2; | |||
| 66 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. | 66 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. |
| 67 | const SAMPLES_PER_PACKET: u32 = 1024; | 67 | const SAMPLES_PER_PACKET: u32 = 1024; |
| 68 | 68 | ||
| 69 | -/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks | ||
| 70 | -/// of 256), the way 1024 is fixed for AAC-LC. | ||
| 71 | -const AC3_SAMPLES_PER_FRAME: u32 = 1536; | ||
| 72 | - | ||
| 73 | /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the | 69 | /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the |
| 74 | /// 256-sample overlap-add the target frame is reconstructed with. | 70 | /// 256-sample overlap-add the target frame is reconstructed with. |
| 75 | const AC3_PRE_ROLL: u32 = 1; | 71 | const AC3_PRE_ROLL: u32 = 1; |
| @@ -207,10 +203,14 @@ impl AudioSession { | |||
| 207 | /// pause — the master clock counts what the device has been fed, so a hole | 203 | /// pause — the master clock counts what the device has been fed, so a hole |
| 208 | /// that fed nothing would stall the whole timeline on it. | 204 | /// that fed nothing would stall the whole timeline on it. |
| 209 | /// | 205 | /// |
| 206 | + /// A segment naming a source that has **no track** is the same silence: a | ||
| 207 | + /// clip of a silent file is a hole with a picture over it, and the timeline | ||
| 208 | + /// let it in on exactly that footing ([`crate::PlaybackSession::import`]). | ||
| 209 | + /// | ||
| 210 | /// Only the sources some segment names are opened. `Ok(None)` when `sources` | 210 | /// Only the sources some segment names are opened. `Ok(None)` when `sources` |
| 211 | - /// is empty or its first entry has no AAC track; a later source that is | 211 | + /// is empty or its first entry has no AAC track; a later source that |
| 212 | - /// missing audio or disagrees on rate/layout is an `Err` — import refuses | 212 | + /// disagrees on rate/layout is an `Err` — import refuses those up front (one |
| 213 | - /// those up front (one timeline, one output device), this is the backstop. | 213 | + /// timeline, one output device), this is the backstop. |
| 214 | pub fn open_multi_segments( | 214 | pub fn open_multi_segments( |
| 215 | sources: &[PathBuf], | 215 | sources: &[PathBuf], |
| 216 | segs: &[(Option<usize>, f64, f64)], | 216 | segs: &[(Option<usize>, f64, f64)], |
| @@ -298,11 +298,18 @@ impl AudioSession { | |||
| 298 | first.check_decoder()?; | 298 | first.check_decoder()?; |
| 299 | 299 | ||
| 300 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | 300 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); |
| 301 | + // ...and which of them turned out to have no track at all, so a silent | ||
| 302 | + // source is opened once like any other rather than once per segment | ||
| 303 | + // naming it. | ||
| 304 | + let mut silent: Vec<bool> = sources.iter().map(|_| false).collect(); | ||
| 301 | tracks[at] = Some(first); | 305 | tracks[at] = Some(first); |
| 302 | for &(source, ..) in segs { | 306 | for &(source, ..) in segs { |
| 303 | let Some(source) = source else { | 307 | let Some(source) = source else { |
| 304 | continue; // a gap opens no file | 308 | continue; // a gap opens no file |
| 305 | }; | 309 | }; |
| 310 | + if silent.get(source) == Some(&true) { | ||
| 311 | + continue; | ||
| 312 | + } | ||
| 306 | let slot = tracks | 313 | let slot = tracks |
| 307 | .get_mut(source) | 314 | .get_mut(source) |
| 308 | .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; | 315 | .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; |
| @@ -310,8 +317,14 @@ impl AudioSession { | |||
| 310 | continue; // already opened, and the checks below already ran | 317 | continue; // already opened, and the checks below already ran |
| 311 | } | 318 | } |
| 312 | let (path, stream) = &sources[source]; | 319 | let (path, stream) = &sources[source]; |
| 313 | - let track = Track::open(path, *stream)? | 320 | + // A source with no audio track at all is not a failure: its |
| 314 | - .ok_or_else(|| format!("source {source} has no audio track"))?; | 321 | + // segments are silence, exactly as a gap's are, and the slot stays |
| 322 | + // empty to say so. That is what a silent clip on an audio lane | ||
| 323 | + // means -- a picture over a hole. | ||
| 324 | + let Some(track) = Track::open(path, *stream)? else { | ||
| 325 | + silent[source] = true; | ||
| 326 | + continue; | ||
| 327 | + }; | ||
| 315 | if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { | 328 | if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { |
| 316 | return Err(format!( | 329 | return Err(format!( |
| 317 | "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", | 330 | "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", |
| @@ -328,14 +341,15 @@ impl AudioSession { | |||
| 328 | 341 | ||
| 329 | let segments: Vec<Segment> = segs | 342 | let segments: Vec<Segment> = segs |
| 330 | .iter() | 343 | .iter() |
| 331 | - .map(|&(source, start_secs, end_secs)| match source { | 344 | + // A gap, and a source with no track to decode, are the same stretch |
| 332 | - Some(source) => tracks[source] | 345 | + // of nothing: as many frames of silence as the window is long. |
| 333 | - .as_ref() | 346 | + .map(|&(source, start_secs, end_secs)| { |
| 334 | - .expect("opened above") | 347 | + match source.and_then(|source| Some((source, tracks[source].as_ref()?))) { |
| 335 | - .segment(source, start_secs, end_secs), | 348 | + Some((source, track)) => track.segment(source, start_secs, end_secs), |
| 336 | - None => Segment::silence( | 349 | + None => Segment::silence( |
| 337 | - ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, | 350 | + ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, |
| 338 | - ), | 351 | + ), |
| 352 | + } | ||
| 339 | }) | 353 | }) |
| 340 | .collect(); | 354 | .collect(); |
| 341 | // Chunk numbering is continuous across every join, counted from the first | 355 | // Chunk numbering is continuous across every join, counted from the first |
| @@ -541,17 +555,26 @@ impl AudioSession { | |||
| 541 | /// -- nothing to tell the user there. Header only, and only worth calling | 555 | /// -- nothing to tell the user there. Header only, and only worth calling |
| 542 | /// once the open has already returned no audio. | 556 | /// once the open has already returned no audio. |
| 543 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | 557 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| 544 | - // Matroska: AAC is read out of one ([`Track::open`]) and everything | 558 | + // Matroska: what symphonia reads out of one ([`Track::open`]) plus the |
| 545 | - // else -- Opus, AC-3, DTS, none of which symphonia decodes at any | 559 | + // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder |
| 546 | - // version -- is named rather than left playing silent with no reason | 560 | + // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here |
| 547 | - // given. A Matroska file with no audio track at all returns `None` here | 561 | + // has at any version -- is named rather than left playing silent with no |
| 548 | - // like any other silent file. | 562 | + // reason given. A Matroska file with no audio track at all returns |
| 563 | + // `None` here like any other silent file. | ||
| 549 | if crate::demux::is_matroska(path.as_ref()) { | 564 | if crate::demux::is_matroska(path.as_ref()) { |
| 550 | - return Ok( | 565 | + let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { |
| 551 | - crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { | 566 | + return Ok(None); |
| 552 | - format!("the {codec} track of this Matroska file cannot be decoded (AAC only)") | 567 | + }; |
| 553 | - }), | 568 | + // An AC-3 track that came up silent all the same is one that could |
| 554 | - ); | 569 | + // not be read -- a laced block, an unreadable syncframe -- and the |
| 570 | + // reader's own words are the ones worth showing. | ||
| 571 | + return Ok(Some(match MkvAc3Track::open(path.as_ref()) { | ||
| 572 | + Ok(Some(_)) => return Ok(None), | ||
| 573 | + Ok(None) => format!( | ||
| 574 | + "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" | ||
| 575 | + ), | ||
| 576 | + Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), | ||
| 577 | + })); | ||
| 555 | } | 578 | } |
| 556 | let file = File::open(path.as_ref())?; | 579 | let file = File::open(path.as_ref())?; |
| 557 | let size = file.metadata()?.len(); | 580 | let size = file.metadata()?.len(); |
| @@ -599,11 +622,29 @@ impl AudioSession { | |||
| 599 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { | 622 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 600 | let path = path.as_ref(); | 623 | let path = path.as_ref(); |
| 601 | // A Matroska file has exactly one readable audio stream here -- the | 624 | // A Matroska file has exactly one readable audio stream here -- the |
| 602 | - // reader's default track ([`SymTrack::open`]) -- so it lists like a | 625 | + // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one |
| 626 | + // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a | ||
| 603 | // standalone audio file rather than like an mp4, and one with no | 627 | // standalone audio file rather than like an mp4, and one with no |
| 604 | // readable track at all lists as the silent source it is. | 628 | // readable track at all lists as the silent source it is. |
| 605 | if crate::demux::is_matroska(path) { | 629 | if crate::demux::is_matroska(path) { |
| 606 | - let Ok(track) = SymTrack::open(path) else { | 630 | + // The AC-3 row describes what the decoder *emits*, which is the |
| 631 | + // stereo the §7.8 downmix hands the timeline, not the 5.1 the file | ||
| 632 | + // carries -- exactly as the mp4 AC-3 rows do. | ||
| 633 | + if let Ok(Some(track)) = MkvAc3Track::open(path) { | ||
| 634 | + return Ok(vec![StreamInfo { | ||
| 635 | + index: 0, | ||
| 636 | + codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), | ||
| 637 | + channels: track.channels, | ||
| 638 | + sample_rate: track.sample_rate, | ||
| 639 | + lang: None, | ||
| 640 | + decodable: matches!(track.channels, 1 | 2), | ||
| 641 | + }]); | ||
| 642 | + } | ||
| 643 | + // No audio track lists as the silent source it is; a track that | ||
| 644 | + // will not open at all is an `Err` here, as it is in | ||
| 645 | + // [`Track::open`] -- a listing that quietly came back empty for a | ||
| 646 | + // broken file is how a lane ends up silent with nothing to go on. | ||
| 647 | + let Some(track) = SymTrack::open(path)? else { | ||
| 607 | return Ok(Vec::new()); | 648 | return Ok(Vec::new()); |
| 608 | }; | 649 | }; |
| 609 | return Ok(vec![StreamInfo { | 650 | return Ok(vec![StreamInfo { |
| @@ -616,7 +657,7 @@ impl AudioSession { | |||
| 616 | }]); | 657 | }]); |
| 617 | } | 658 | } |
| 618 | if crate::is_audio(path) { | 659 | if crate::is_audio(path) { |
| 619 | - let track = SymTrack::open(path)?; | 660 | + let track = SymTrack::open_required(path)?; |
| 620 | return Ok(vec![StreamInfo { | 661 | return Ok(vec![StreamInfo { |
| 621 | index: 0, | 662 | index: 0, |
| 622 | codec: track.codec.into(), | 663 | codec: track.codec.into(), |
| @@ -743,15 +784,18 @@ impl AudioSession { | |||
| 743 | /// half a packet over the whole list however many files it spans, and the | 784 | /// half a packet over the whole list however many files it spans, and the |
| 744 | /// extra priming packet is still the very first segment's alone. | 785 | /// extra priming packet is still the very first segment's alone. |
| 745 | /// | 786 | /// |
| 746 | - /// Every source must declare the same [`AacTrackParams`]: the copy becomes | 787 | + /// Every source that *has* a track must declare the same |
| 747 | - /// one output track with one esds. Import refuses a mismatch up front; the | 788 | + /// [`AacTrackParams`]: the copy becomes one output track with one esds. |
| 748 | - /// check here is the backstop, as is the missing-track `Err`. | 789 | + /// Import refuses a mismatch up front; the check here is the backstop. |
| 749 | /// | 790 | /// |
| 750 | /// A segment naming **no** source is a gap, and is copied as that many | 791 | /// A segment naming **no** source is a gap, and is copied as that many |
| 751 | /// packets of [`silent_packet`] silence — the rounding debt carried through | 792 | /// packets of [`silent_packet`] silence — the rounding debt carried through |
| 752 | /// it like any other, so the hole occupies its exact duration and the audio | 793 | /// it like any other, so the hole occupies its exact duration and the audio |
| 753 | /// after it stays in sync with the picture. A gap the track *opens* on gets | 794 | /// after it stays in sync with the picture. A gap the track *opens* on gets |
| 754 | - /// one silent packet more, which is the priming a reader drops. | 795 | + /// one silent packet more, which is the priming a reader drops. A segment |
| 796 | + /// naming a *silent* source is written the same way: a clip whose file has | ||
| 797 | + /// no audio track is a hole with a picture over it, and the timeline it | ||
| 798 | + /// joined already said so ([`crate::PlaybackSession::import`]). | ||
| 755 | pub fn copy_multi_segments( | 799 | pub fn copy_multi_segments( |
| 756 | sources: &[PathBuf], | 800 | sources: &[PathBuf], |
| 757 | segs: &[(Option<usize>, f64, f64)], | 801 | segs: &[(Option<usize>, f64, f64)], |
| @@ -770,24 +814,34 @@ impl AudioSession { | |||
| 770 | sources: &[(PathBuf, usize)], | 814 | sources: &[(PathBuf, usize)], |
| 771 | segs: &[(Option<usize>, f64, f64)], | 815 | segs: &[(Option<usize>, f64, f64)], |
| 772 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { | 816 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { |
| 773 | - let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else { | 817 | + // The output track is declared from the first source that has one -- |
| 818 | + // not simply the first one named, which may be a silent clip. Such a | ||
| 819 | + // clip defines no rate and no layout; it is written as silence below | ||
| 820 | + // and the track goes on being the audible sources' track. | ||
| 821 | + let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect(); | ||
| 822 | + let mut first = None; | ||
| 823 | + for &(source, ..) in segs { | ||
| 824 | + let Some(source) = source else { continue }; | ||
| 825 | + if let Some(track) = source_at(&mut tracks, sources, source)? { | ||
| 826 | + first = Some(track.track_params()); | ||
| 827 | + break; | ||
| 828 | + } | ||
| 829 | + } | ||
| 830 | + let Some(params) = first else { | ||
| 774 | return Ok(None); // no segments, or nothing but silence | 831 | return Ok(None); // no segments, or nothing but silence |
| 775 | }; | 832 | }; |
| 776 | - let (path, stream) = sources | ||
| 777 | - .get(first) | ||
| 778 | - .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; | ||
| 779 | - let Some(track) = copy_track(path, *stream)? else { | ||
| 780 | - return Ok(None); // silent source, silent export | ||
| 781 | - }; | ||
| 782 | - let params = track.track_params(); | ||
| 783 | - let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect(); | ||
| 784 | - tracks[first] = Some(track); | ||
| 785 | 833 | ||
| 786 | let sample_rate = params.sample_rate; | 834 | let sample_rate = params.sample_rate; |
| 787 | let mut err = 0i64; | 835 | let mut err = 0i64; |
| 788 | let mut packets: Vec<AacPacket> = Vec::new(); | 836 | let mut packets: Vec<AacPacket> = Vec::new(); |
| 789 | for &(source, start_secs, end_secs) in segs { | 837 | for &(source, start_secs, end_secs) in segs { |
| 790 | - let Some(source) = source else { | 838 | + // A gap, and a clip whose source carries no track, are the same hole |
| 839 | + // to write: silence for as long as the window is. | ||
| 840 | + let named = match source { | ||
| 841 | + Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)), | ||
| 842 | + None => None, | ||
| 843 | + }; | ||
| 844 | + let Some((source, track)) = named else { | ||
| 791 | let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; | 845 | let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; |
| 792 | let bytes = silent_packet(params.chan_conf)?; | 846 | let bytes = silent_packet(params.chan_conf)?; |
| 793 | // A reader drops the first packet of an AAC track as the | 847 | // A reader drops the first packet of an AAC track as the |
| @@ -805,7 +859,6 @@ impl AudioSession { | |||
| 805 | } | 859 | } |
| 806 | continue; | 860 | continue; |
| 807 | }; | 861 | }; |
| 808 | - let track = source_at(&mut tracks, sources, source)?; | ||
| 809 | if track.track_params() != params { | 862 | if track.track_params() != params { |
| 810 | return Err(format!( | 863 | return Err(format!( |
| 811 | "source {source} audio is {:?}, the timeline's is {params:?}", | 864 | "source {source} audio is {:?}, the timeline's is {params:?}", |
| @@ -866,24 +919,25 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> { | |||
| 866 | } | 919 | } |
| 867 | } | 920 | } |
| 868 | 921 | ||
| 869 | -/// The source at `index`, on the stream it names, opened on first use. Sources | 922 | +/// The source at `index`, on the stream it names, opened on first use -- and |
| 870 | -/// a segment list never names are never touched: a project's list only grows. | 923 | +/// `None` for a source that has no track at all, which the caller writes as |
| 924 | +/// silence exactly as it writes a gap. The outer `Option` is "has it been | ||
| 925 | +/// opened", the inner one "was there anything in it", so a silent source is | ||
| 926 | +/// opened once like any other. Sources a segment list never names are never | ||
| 927 | +/// touched: a project's list only grows. | ||
| 871 | fn source_at<'a>( | 928 | fn source_at<'a>( |
| 872 | - tracks: &'a mut [Option<AacTrack>], | 929 | + tracks: &'a mut [Option<Option<AacTrack>>], |
| 873 | sources: &[(PathBuf, usize)], | 930 | sources: &[(PathBuf, usize)], |
| 874 | index: usize, | 931 | index: usize, |
| 875 | -) -> crate::Result<&'a mut AacTrack> { | 932 | +) -> crate::Result<Option<&'a mut AacTrack>> { |
| 876 | let slot = tracks | 933 | let slot = tracks |
| 877 | .get_mut(index) | 934 | .get_mut(index) |
| 878 | .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; | 935 | .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; |
| 879 | if slot.is_none() { | 936 | if slot.is_none() { |
| 880 | let (path, stream) = &sources[index]; | 937 | let (path, stream) = &sources[index]; |
| 881 | - *slot = Some( | 938 | + *slot = Some(copy_track(path, *stream)?); |
| 882 | - copy_track(path, *stream)? | ||
| 883 | - .ok_or_else(|| format!("source {index} has no audio track"))?, | ||
| 884 | - ); | ||
| 885 | } | 939 | } |
| 886 | - Ok(slot.as_mut().expect("just opened")) | 940 | + Ok(slot.as_mut().expect("just opened").as_mut()) |
| 887 | } | 941 | } |
| 888 | 942 | ||
| 889 | /// A source's track for the *copy* path, which needs raw AAC access units. | 943 | /// A source's track for the *copy* path, which needs raw AAC access units. |
| @@ -924,7 +978,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { | |||
| 924 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` | 978 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` |
| 925 | // sample table can hold. The export decodes it and encodes AAC, exactly | 979 | // sample table can hold. The export decodes it and encodes AAC, exactly |
| 926 | // as it does for every other source no copy reaches. | 980 | // as it does for every other source no copy reaches. |
| 927 | - Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), | 981 | + Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), |
| 928 | } | 982 | } |
| 929 | } | 983 | } |
| 930 | 984 | ||
| @@ -947,6 +1001,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error { | |||
| 947 | enum Track { | 1001 | enum Track { |
| 948 | Aac(AacTrack), | 1002 | Aac(AacTrack), |
| 949 | Ac3(Ac3Track), | 1003 | Ac3(Ac3Track), |
| 1004 | + /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an | ||
| 1005 | + /// mp4's sample table. | ||
| 1006 | + Mkv(MkvAc3Track), | ||
| 950 | Sym(SymTrack), | 1007 | Sym(SymTrack), |
| 951 | } | 1008 | } |
| 952 | 1009 | ||
| @@ -965,20 +1022,43 @@ impl Track { | |||
| 965 | /// has exactly one, so any `stream` above 0 there is a promise the file | 1022 | /// has exactly one, so any `stream` above 0 there is a promise the file |
| 966 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. | 1023 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. |
| 967 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { | 1024 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { |
| 968 | - // A Matroska file goes straight to symphonia, whose `mkv` reader is the | 1025 | + // A Matroska file goes to symphonia, whose `mkv` reader is the one thing |
| 969 | - // one thing here that reads its packets -- neither mp4 reader can open | 1026 | + // here that reads its packets -- neither mp4 reader can open the file at |
| 970 | - // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia | 1027 | + // all -- except for the two codecs symphonia has no decoder for at any |
| 971 | - // has no such decoder at any version) leaves the source the silent one | 1028 | + // version and this project does: AC-3 and E-AC-3 are handed to the Dolby |
| 972 | - // it always was, which `AudioSession::unsupported` puts into words, | 1029 | + // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither |
| 973 | - // rather than failing the import of a file whose picture is fine. | 1030 | + // one can decode (Opus, DTS) leaves the source the silent one it always |
| 1031 | + // was, which `AudioSession::unsupported` puts into words, rather than | ||
| 1032 | + // failing the import of a file whose picture is fine. A track that will | ||
| 1033 | + // not open at all is *not* in that group: see below. | ||
| 974 | if crate::demux::is_matroska(path) { | 1034 | if crate::demux::is_matroska(path) { |
| 975 | if stream > 0 { | 1035 | if stream > 0 { |
| 976 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | 1036 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); |
| 977 | } | 1037 | } |
| 978 | - return Ok(SymTrack::open(path) | 1038 | + match MkvAc3Track::open(path) { |
| 979 | - .ok() | 1039 | + Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), |
| 980 | - .filter(|t| t.decoder().is_ok()) | 1040 | + Ok(None) => {} |
| 981 | - .map(Self::Sym)); | 1041 | + // Named on the way past rather than returned: symphonia gets the |
| 1042 | + // same file next and may read the track perfectly well (a laced | ||
| 1043 | + // block is [`MkvAc3Track`]'s limitation, not the file's), and | ||
| 1044 | + // if it cannot either, *its* `Err` is the one that comes back. | ||
| 1045 | + Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), | ||
| 1046 | + } | ||
| 1047 | + // Two things are silent here and no more: a file with no audio | ||
| 1048 | + // track at all, and a track whose codec nothing in this project | ||
| 1049 | + // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts | ||
| 1050 | + // that into words). A track that will not *open* is an `Err`, the | ||
| 1051 | + // same answer the mp4 arm gives: turned into silence it would play | ||
| 1052 | + // and export as a hole with only an eprintln to say why, which is a | ||
| 1053 | + // bug wearing a feature's clothes. | ||
| 1054 | + let Some(track) = SymTrack::open(path)? else { | ||
| 1055 | + return Ok(None); | ||
| 1056 | + }; | ||
| 1057 | + if let Err(e) = track.decoder() { | ||
| 1058 | + eprintln!("matroska audio: {}: {e}", path.display()); | ||
| 1059 | + return Ok(None); | ||
| 1060 | + } | ||
| 1061 | + return Ok(Some(Self::Sym(track))); | ||
| 982 | } | 1062 | } |
| 983 | let audio_file = crate::is_audio(path); | 1063 | let audio_file = crate::is_audio(path); |
| 984 | // Ahead of the AAC reader, because that one answers "not AAC" for a | 1064 | // Ahead of the AAC reader, because that one answers "not AAC" for a |
| @@ -999,13 +1079,14 @@ impl Track { | |||
| 999 | if stream > 0 { | 1079 | if stream > 0 { |
| 1000 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | 1080 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); |
| 1001 | } | 1081 | } |
| 1002 | - SymTrack::open(path).map(|track| Some(Self::Sym(track))) | 1082 | + SymTrack::open_required(path).map(|track| Some(Self::Sym(track))) |
| 1003 | } | 1083 | } |
| 1004 | 1084 | ||
| 1005 | fn sample_rate(&self) -> u32 { | 1085 | fn sample_rate(&self) -> u32 { |
| 1006 | match self { | 1086 | match self { |
| 1007 | Self::Aac(t) => t.sample_rate, | 1087 | Self::Aac(t) => t.sample_rate, |
| 1008 | Self::Ac3(t) => t.sample_rate, | 1088 | Self::Ac3(t) => t.sample_rate, |
| 1089 | + Self::Mkv(t) => t.sample_rate, | ||
| 1009 | Self::Sym(t) => t.sample_rate, | 1090 | Self::Sym(t) => t.sample_rate, |
| 1010 | } | 1091 | } |
| 1011 | } | 1092 | } |
| @@ -1021,6 +1102,11 @@ impl Track { | |||
| 1021 | 1 | 2 => Ok(t.channels), | 1102 | 1 | 2 => Ok(t.channels), |
| 1022 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | 1103 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| 1023 | }, | 1104 | }, |
| 1105 | + // Downmixed by the very same decoder, out of a Matroska file. | ||
| 1106 | + Self::Mkv(t) => match t.channels { | ||
| 1107 | + 1 | 2 => Ok(t.channels), | ||
| 1108 | + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | ||
| 1109 | + }, | ||
| 1024 | Self::Sym(t) => match t.channels { | 1110 | Self::Sym(t) => match t.channels { |
| 1025 | 1 | 2 => Ok(t.channels), | 1111 | 1 | 2 => Ok(t.channels), |
| 1026 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | 1112 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| @@ -1033,6 +1119,7 @@ impl Track { | |||
| 1033 | match self { | 1119 | match self { |
| 1034 | Self::Aac(t) => t.total_samples, | 1120 | Self::Aac(t) => t.total_samples, |
| 1035 | Self::Ac3(t) => t.total_samples, | 1121 | Self::Ac3(t) => t.total_samples, |
| 1122 | + Self::Mkv(t) => t.total_samples, | ||
| 1036 | Self::Sym(t) => t.total_samples, | 1123 | Self::Sym(t) => t.total_samples, |
| 1037 | } | 1124 | } |
| 1038 | } | 1125 | } |
| @@ -1042,6 +1129,9 @@ impl Track { | |||
| 1042 | match self { | 1129 | match self { |
| 1043 | Self::Aac(t) => t.priming, | 1130 | Self::Aac(t) => t.priming, |
| 1044 | Self::Ac3(t) => t.priming, | 1131 | Self::Ac3(t) => t.priming, |
| 1132 | + // Matroska writes no edit list and AC-3 has no encoder delay: | ||
| 1133 | + // block 0 is sample 0. | ||
| 1134 | + Self::Mkv(_) => 0, | ||
| 1045 | Self::Sym(t) => t.priming, | 1135 | Self::Sym(t) => t.priming, |
| 1046 | } | 1136 | } |
| 1047 | } | 1137 | } |
| @@ -1052,6 +1142,7 @@ impl Track { | |||
| 1052 | match self { | 1142 | match self { |
| 1053 | Self::Aac(t) => t.segment(source, start_secs, end_secs), | 1143 | Self::Aac(t) => t.segment(source, start_secs, end_secs), |
| 1054 | Self::Ac3(t) => t.segment(source, start_secs, end_secs), | 1144 | Self::Ac3(t) => t.segment(source, start_secs, end_secs), |
| 1145 | + Self::Mkv(t) => t.segment(source, start_secs, end_secs), | ||
| 1055 | Self::Sym(t) => { | 1146 | Self::Sym(t) => { |
| 1056 | let media_target = t.media(start_secs); | 1147 | let media_target = t.media(start_secs); |
| 1057 | Segment { | 1148 | Segment { |
| @@ -1073,7 +1164,10 @@ impl Track { | |||
| 1073 | AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; | 1164 | AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; |
| 1074 | } | 1165 | } |
| 1075 | Self::Ac3(t) => { | 1166 | Self::Ac3(t) => { |
| 1076 | - ac3_decoder(t.requested)?; | 1167 | + ac3_decoder("ac3", t.requested)?; |
| 1168 | + } | ||
| 1169 | + Self::Mkv(t) => { | ||
| 1170 | + ac3_decoder(t.mkv.codec, t.requested)?; | ||
| 1077 | } | 1171 | } |
| 1078 | Self::Sym(t) => { | 1172 | Self::Sym(t) => { |
| 1079 | t.decoder()?; | 1173 | t.decoder()?; |
| @@ -1110,7 +1204,13 @@ struct SymTrack { | |||
| 1110 | } | 1204 | } |
| 1111 | 1205 | ||
| 1112 | impl SymTrack { | 1206 | impl SymTrack { |
| 1113 | - fn open(path: &Path) -> crate::Result<Self> { | 1207 | + /// `Ok(None)` for a container that opened and holds no audio track at all -- |
| 1208 | + /// a silent source, which is a thing a file is allowed to be. Everything | ||
| 1209 | + /// else that goes wrong here is an `Err`: a file that will not open, will | ||
| 1210 | + /// not parse, or carries a track it cannot describe is *broken*, and the | ||
| 1211 | + /// difference matters because silence is played and exported without a word | ||
| 1212 | + /// while an `Err` is shown ([`Track::open`]). | ||
| 1213 | + fn open(path: &Path) -> crate::Result<Option<Self>> { | ||
| 1114 | let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); | 1214 | let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); |
| 1115 | // The extension is a hint, not a decision: the probe reads the magic and | 1215 | // The extension is a hint, not a decision: the probe reads the magic and |
| 1116 | // is free to disagree, which is what makes a mislabelled file work. | 1216 | // is free to disagree, which is what makes a mislabelled file work. |
| @@ -1124,9 +1224,9 @@ impl SymTrack { | |||
| 1124 | FormatOptions::default(), | 1224 | FormatOptions::default(), |
| 1125 | MetadataOptions::default(), | 1225 | MetadataOptions::default(), |
| 1126 | )?; | 1226 | )?; |
| 1127 | - let track = reader | 1227 | + let Some(track) = reader.default_track(SymKind::Audio) else { |
| 1128 | - .default_track(SymKind::Audio) | 1228 | + return Ok(None); |
| 1129 | - .ok_or_else(|| format!("{} has no audio track", path.display()))?; | 1229 | + }; |
| 1130 | let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay); | 1230 | let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay); |
| 1131 | let time_base = track | 1231 | let time_base = track |
| 1132 | .time_base | 1232 | .time_base |
| @@ -1147,7 +1247,7 @@ impl SymTrack { | |||
| 1147 | let codec = symphonia::default::get_codecs() | 1247 | let codec = symphonia::default::get_codecs() |
| 1148 | .get_audio_decoder(params.codec) | 1248 | .get_audio_decoder(params.codec) |
| 1149 | .map_or("an unsupported format", |d| d.codec.info.short_name); | 1249 | .map_or("an unsupported format", |d| d.codec.info.short_name); |
| 1150 | - Ok(Self { | 1250 | + Ok(Some(Self { |
| 1151 | reader, | 1251 | reader, |
| 1152 | track_id, | 1252 | track_id, |
| 1153 | sample_rate, | 1253 | sample_rate, |
| @@ -1161,7 +1261,14 @@ impl SymTrack { | |||
| 1161 | time_base, | 1261 | time_base, |
| 1162 | params, | 1262 | params, |
| 1163 | codec, | 1263 | codec, |
| 1164 | - }) | 1264 | + })) |
| 1265 | + } | ||
| 1266 | + | ||
| 1267 | + /// [`open`](Self::open) where having no audio track is itself the error: | ||
| 1268 | + /// what a standalone audio file is held to, since a song with no sound in | ||
| 1269 | + /// it is a broken file and not a silent source. | ||
| 1270 | + fn open_required(path: &Path) -> crate::Result<Self> { | ||
| 1271 | + Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into()) | ||
| 1165 | } | 1272 | } |
| 1166 | 1273 | ||
| 1167 | /// A fresh decoder: seeking mid-stream leaves state that belongs to the | 1274 | /// A fresh decoder: seeking mid-stream leaves state that belongs to the |
| @@ -1326,9 +1433,9 @@ impl Ac3Track { | |||
| 1326 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? | 1433 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? |
| 1327 | .nfchans; | 1434 | .nfchans; |
| 1328 | let requested = (nfchans > 1).then_some(2); | 1435 | let requested = (nfchans > 1).then_some(2); |
| 1329 | - let mut decoder = ac3_decoder(requested)?; | 1436 | + let mut decoder = ac3_decoder("ac3", requested)?; |
| 1330 | let channels = decode_ac3(&mut decoder, &first.bytes)? | 1437 | let channels = decode_ac3(&mut decoder, &first.bytes)? |
| 1331 | - .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16) | 1438 | + .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) |
| 1332 | .filter(|&c| c > 0) | 1439 | .filter(|&c| c > 0) |
| 1333 | .ok_or("the first AC-3 syncframe decoded to nothing")?; | 1440 | .ok_or("the first AC-3 syncframe decoded to nothing")?; |
| 1334 | 1441 | ||
| @@ -1373,6 +1480,101 @@ impl Ac3Track { | |||
| 1373 | } | 1480 | } |
| 1374 | } | 1481 | } |
| 1375 | 1482 | ||
| 1483 | +/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same | ||
| 1484 | +/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of | ||
| 1485 | +/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux | ||
| 1486 | +/// therefore arrives on the timeline as an ordinary stereo source, exactly as | ||
| 1487 | +/// the mp4 path's does, and the mono passthrough quirk is the same one. | ||
| 1488 | +/// | ||
| 1489 | +/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side | ||
| 1490 | +/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): | ||
| 1491 | +/// one block is one packet, one packet is one syncframe, and a seek lands on | ||
| 1492 | +/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in | ||
| 1493 | +/// front of it. | ||
| 1494 | +struct MkvAc3Track { | ||
| 1495 | + mkv: crate::demux::MkvAudio, | ||
| 1496 | + sample_rate: u32, | ||
| 1497 | + /// What comes *out* of the decoder, measured on the first frame — 2 for | ||
| 1498 | + /// anything from stereo to 5.1, 1 for a mono track (see `requested`). | ||
| 1499 | + channels: u16, | ||
| 1500 | + total_samples: Option<u64>, | ||
| 1501 | + /// What the decoder is asked to hand out, from this track's own layout: | ||
| 1502 | + /// `Some(2)` for anything with more than one front channel, `None` for a | ||
| 1503 | + /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's. | ||
| 1504 | + requested: Option<u16>, | ||
| 1505 | +} | ||
| 1506 | + | ||
| 1507 | +impl MkvAc3Track { | ||
| 1508 | + /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 — | ||
| 1509 | + /// that mkv is the silent source it has always been. An `Err` is a track | ||
| 1510 | + /// that is one and could not be read, which | ||
| 1511 | + /// [`AudioSession::unsupported`] quotes back to the user. | ||
| 1512 | + fn open(path: &Path) -> crate::Result<Option<Self>> { | ||
| 1513 | + let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else { | ||
| 1514 | + return Ok(None); | ||
| 1515 | + }; | ||
| 1516 | + let first = mkv | ||
| 1517 | + .frame(0)? | ||
| 1518 | + .ok_or("the AC-3 track of this Matroska file has no blocks")?; | ||
| 1519 | + // Rate and layout come out of the bit stream, which is where AC-3 | ||
| 1520 | + // states them: Matroska's `Audio` element repeats them and muxers get | ||
| 1521 | + // that wrong often enough that the frame is the better source. | ||
| 1522 | + // `nfchans` excludes the LFE in both syntaxes, which is what the | ||
| 1523 | + // downmix decision wants. | ||
| 1524 | + let (sample_rate, nfchans) = if mkv.codec == "eac3" { | ||
| 1525 | + // Annex E's BSI starts right after the 16-bit syncword. | ||
| 1526 | + let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) | ||
| 1527 | + .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; | ||
| 1528 | + (bsi.sample_rate, bsi.nfchans) | ||
| 1529 | + } else { | ||
| 1530 | + let sync = oxideav_ac3::syncinfo::parse(&first) | ||
| 1531 | + .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; | ||
| 1532 | + let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) | ||
| 1533 | + .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; | ||
| 1534 | + (sync.sample_rate, bsi.nfchans) | ||
| 1535 | + }; | ||
| 1536 | + let requested = (nfchans > 1).then_some(2); | ||
| 1537 | + let mut decoder = ac3_decoder(mkv.codec, requested)?; | ||
| 1538 | + let (pcm, samples) = | ||
| 1539 | + decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; | ||
| 1540 | + let channels = (pcm.len() as u64 / samples.max(1)) as u16; | ||
| 1541 | + if channels == 0 { | ||
| 1542 | + return Err("the first AC-3 syncframe decoded to nothing".into()); | ||
| 1543 | + } | ||
| 1544 | + // The track runs to the last block's timestamp plus that block's own | ||
| 1545 | + // frame -- a container that indexes nothing states no duration either, | ||
| 1546 | + // and every frame of a syncframe stream is the same length. | ||
| 1547 | + let last = mkv.secs(mkv.blocks().saturating_sub(1)); | ||
| 1548 | + Ok(Some(Self { | ||
| 1549 | + total_samples: Some((last * f64::from(sample_rate)) as u64 + samples), | ||
| 1550 | + sample_rate, | ||
| 1551 | + channels, | ||
| 1552 | + requested, | ||
| 1553 | + mkv, | ||
| 1554 | + })) | ||
| 1555 | + } | ||
| 1556 | + | ||
| 1557 | + /// `secs` on this source's timeline into media samples. No priming: the | ||
| 1558 | + /// container carries no edit list and AC-3 no encoder delay. | ||
| 1559 | + fn media(&self, secs: f64) -> u64 { | ||
| 1560 | + (secs.max(0.0) * f64::from(self.sample_rate)) as u64 | ||
| 1561 | + } | ||
| 1562 | + | ||
| 1563 | + /// One `[start, end)` window, resolved to blocks and media samples — | ||
| 1564 | + /// [`Ac3Track::segment`] against block timestamps instead of an `stts`. | ||
| 1565 | + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { | ||
| 1566 | + let media_target = self.media(start_secs); | ||
| 1567 | + let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize); | ||
| 1568 | + Segment { | ||
| 1569 | + source: Some(source), | ||
| 1570 | + start_id: start_id as u32, | ||
| 1571 | + start_pos: self.media(self.mkv.secs(start_id)), | ||
| 1572 | + media_target, | ||
| 1573 | + media_end: self.media(end_secs).max(media_target), | ||
| 1574 | + } | ||
| 1575 | + } | ||
| 1576 | +} | ||
| 1577 | + | ||
| 1376 | /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own | 1578 | /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own |
| 1377 | /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a | 1579 | /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a |
| 1378 | /// 5.1 track at all. Fresh per segment for the same reason every other decoder | 1580 | /// 5.1 track at all. Fresh per segment for the same reason every other decoder |
| @@ -1383,32 +1585,47 @@ impl Ac3Track { | |||
| 1383 | /// mono track asks for no downmix at all and stays the mono source it is. The | 1585 | /// mono track asks for no downmix at all and stays the mono source it is. The |
| 1384 | /// upgrade path is `Some(2)` unconditionally once the library duplicates the | 1586 | /// upgrade path is `Some(2)` unconditionally once the library duplicates the |
| 1385 | /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. | 1587 | /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. |
| 1386 | -fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | 1588 | +/// |
| 1589 | +/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers | ||
| 1590 | +/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct | ||
| 1591 | +/// behind both dispatches per packet on `bsid` in any case, so what this picks | ||
| 1592 | +/// is the capability set, not the syntax. | ||
| 1593 | +fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | ||
| 1387 | let mut registry = CodecRegistry::new(); | 1594 | let mut registry = CodecRegistry::new(); |
| 1388 | oxideav_ac3::register_codecs(&mut registry); | 1595 | oxideav_ac3::register_codecs(&mut registry); |
| 1389 | - let mut params = CodecParameters::audio(CodecId::new("ac3")); | 1596 | + let mut params = CodecParameters::audio(CodecId::new(codec)); |
| 1390 | params.channels = channels; | 1597 | params.channels = channels; |
| 1391 | registry | 1598 | registry |
| 1392 | .first_decoder(¶ms) | 1599 | .first_decoder(¶ms) |
| 1393 | .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) | 1600 | .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) |
| 1394 | } | 1601 | } |
| 1395 | 1602 | ||
| 1396 | -/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the | 1603 | +/// One syncframe in, one buffer of interleaved f32 out and the frames per |
| 1397 | -/// decoder wants more input before it can hand a frame back, which is not an | 1604 | +/// channel it holds. `Ok(None)` when the decoder wants more input before it can |
| 1398 | -/// error. The library speaks S16 little-endian; `/32768` is the whole | 1605 | +/// hand a frame back, which is not an error. The library speaks S16 |
| 1399 | -/// conversion, and it lands in the `[-1, 1)` every other reader here emits. | 1606 | +/// little-endian; `/32768` is the whole conversion, and it lands in the |
| 1400 | -fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> { | 1607 | +/// `[-1, 1)` every other reader here emits. |
| 1608 | +/// | ||
| 1609 | +/// The frame count comes back beside the samples because an E-AC-3 frame is not | ||
| 1610 | +/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 | ||
| 1611 | +/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the | ||
| 1612 | +/// channel count and every media position after it out. | ||
| 1613 | +fn decode_ac3( | ||
| 1614 | + decoder: &mut Box<dyn Decoder>, | ||
| 1615 | + bytes: &[u8], | ||
| 1616 | +) -> crate::Result<Option<(Vec<f32>, u64)>> { | ||
| 1401 | let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); | 1617 | let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); |
| 1402 | decoder | 1618 | decoder |
| 1403 | .send_packet(&packet) | 1619 | .send_packet(&packet) |
| 1404 | .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; | 1620 | .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; |
| 1405 | match decoder.receive_frame() { | 1621 | match decoder.receive_frame() { |
| 1406 | - Ok(Frame::Audio(audio)) => Ok(Some( | 1622 | + Ok(Frame::Audio(audio)) => Ok(Some(( |
| 1407 | audio.data[0] | 1623 | audio.data[0] |
| 1408 | .chunks_exact(2) | 1624 | .chunks_exact(2) |
| 1409 | .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) | 1625 | .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) |
| 1410 | .collect(), | 1626 | .collect(), |
| 1411 | - )), | 1627 | + u64::from(audio.samples), |
| 1628 | + ))), | ||
| 1412 | Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), | 1629 | Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), |
| 1413 | Err(oxideav_core::Error::NeedMore) => Ok(None), | 1630 | Err(oxideav_core::Error::NeedMore) => Ok(None), |
| 1414 | Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), | 1631 | Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), |
| @@ -2026,6 +2243,21 @@ fn run(mut w: Worker) { | |||
| 2026 | } | 2243 | } |
| 2027 | continue; | 2244 | continue; |
| 2028 | } | 2245 | } |
| 2246 | + Track::Mkv(track) => { | ||
| 2247 | + if !run_mkv_ac3( | ||
| 2248 | + track, | ||
| 2249 | + seg, | ||
| 2250 | + eq.as_mut(), | ||
| 2251 | + speed, | ||
| 2252 | + channels, | ||
| 2253 | + &mut timeline, | ||
| 2254 | + &w.tx, | ||
| 2255 | + ) || !settle(speed, channels, &mut timeline, &w.tx) | ||
| 2256 | + { | ||
| 2257 | + return; // consumer went away | ||
| 2258 | + } | ||
| 2259 | + continue; | ||
| 2260 | + } | ||
| 2029 | Track::Ac3(track) => { | 2261 | Track::Ac3(track) => { |
| 2030 | if !run_ac3( | 2262 | if !run_ac3( |
| 2031 | track, | 2263 | track, |
| @@ -2191,7 +2423,7 @@ fn run_ac3( | |||
| 2191 | timeline: &mut u64, | 2423 | timeline: &mut u64, |
| 2192 | tx: &SyncSender<AudioChunk>, | 2424 | tx: &SyncSender<AudioChunk>, |
| 2193 | ) -> bool { | 2425 | ) -> bool { |
| 2194 | - let mut decoder = match ac3_decoder(track.requested) { | 2426 | + let mut decoder = match ac3_decoder("ac3", track.requested) { |
| 2195 | Ok(decoder) => decoder, | 2427 | Ok(decoder) => decoder, |
| 2196 | Err(e) => { | 2428 | Err(e) => { |
| 2197 | eprintln!("audio decoder init failed: {e}"); | 2429 | eprintln!("audio decoder init failed: {e}"); |
| @@ -2200,7 +2432,6 @@ fn run_ac3( | |||
| 2200 | }; | 2432 | }; |
| 2201 | let mut pos = seg.start_pos; | 2433 | let mut pos = seg.start_pos; |
| 2202 | for id in seg.start_id..=track.sample_count { | 2434 | for id in seg.start_id..=track.sample_count { |
| 2203 | - let mut interleaved; | ||
| 2204 | if pos >= seg.media_end { | 2435 | if pos >= seg.media_end { |
| 2205 | return true; // segment done, on to the next one | 2436 | return true; // segment done, on to the next one |
| 2206 | } | 2437 | } |
| @@ -2212,15 +2443,75 @@ fn run_ac3( | |||
| 2212 | return true; | 2443 | return true; |
| 2213 | } | 2444 | } |
| 2214 | }; | 2445 | }; |
| 2215 | - match decode_ac3(&mut decoder, &sample.bytes) { | 2446 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) { |
| 2216 | - Ok(Some(pcm)) => interleaved = pcm, | 2447 | + Ok(Some(decoded)) => decoded, |
| 2217 | Ok(None) => continue, // the decoder wants another frame first | 2448 | Ok(None) => continue, // the decoder wants another frame first |
| 2218 | Err(e) => { | 2449 | Err(e) => { |
| 2219 | eprintln!("audio decode error at sample {id}: {e}"); | 2450 | eprintln!("audio decode error at sample {id}: {e}"); |
| 2220 | return true; | 2451 | return true; |
| 2221 | } | 2452 | } |
| 2453 | + }; | ||
| 2454 | + let next = pos + samples; | ||
| 2455 | + if !emit( | ||
| 2456 | + &mut interleaved, | ||
| 2457 | + channels, | ||
| 2458 | + seg, | ||
| 2459 | + eq.as_deref_mut(), | ||
| 2460 | + speed.as_mut(), | ||
| 2461 | + pos, | ||
| 2462 | + next, | ||
| 2463 | + timeline, | ||
| 2464 | + tx, | ||
| 2465 | + ) { | ||
| 2466 | + return false; | ||
| 2222 | } | 2467 | } |
| 2223 | - let next = pos + (interleaved.len() / channels) as u64; | 2468 | + pos = next; |
| 2469 | + } | ||
| 2470 | + true | ||
| 2471 | +} | ||
| 2472 | + | ||
| 2473 | +/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks | ||
| 2474 | +/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the | ||
| 2475 | +/// stereo downmix are the same ones; only where a packet comes from differs. | ||
| 2476 | +/// `false` means the consumer went away. | ||
| 2477 | +fn run_mkv_ac3( | ||
| 2478 | + track: &mut MkvAc3Track, | ||
| 2479 | + seg: &Segment, | ||
| 2480 | + mut eq: Option<&mut EqState>, | ||
| 2481 | + speed: &mut Option<Resample>, | ||
| 2482 | + channels: usize, | ||
| 2483 | + timeline: &mut u64, | ||
| 2484 | + tx: &SyncSender<AudioChunk>, | ||
| 2485 | +) -> bool { | ||
| 2486 | + let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { | ||
| 2487 | + Ok(decoder) => decoder, | ||
| 2488 | + Err(e) => { | ||
| 2489 | + eprintln!("audio decoder init failed: {e}"); | ||
| 2490 | + return true; | ||
| 2491 | + } | ||
| 2492 | + }; | ||
| 2493 | + let mut pos = seg.start_pos; | ||
| 2494 | + for id in seg.start_id as usize.. { | ||
| 2495 | + if pos >= seg.media_end { | ||
| 2496 | + return true; // segment done, on to the next one | ||
| 2497 | + } | ||
| 2498 | + let block = match track.mkv.frame(id) { | ||
| 2499 | + Ok(Some(bytes)) => bytes, | ||
| 2500 | + Ok(None) => return true, // end of the track | ||
| 2501 | + Err(e) => { | ||
| 2502 | + eprintln!("audio demux error at block {id}: {e}"); | ||
| 2503 | + return true; | ||
| 2504 | + } | ||
| 2505 | + }; | ||
| 2506 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) { | ||
| 2507 | + Ok(Some(decoded)) => decoded, | ||
| 2508 | + Ok(None) => continue, // the decoder wants another frame first | ||
| 2509 | + Err(e) => { | ||
| 2510 | + eprintln!("audio decode error at block {id}: {e}"); | ||
| 2511 | + return true; | ||
| 2512 | + } | ||
| 2513 | + }; | ||
| 2514 | + let next = pos + samples; | ||
| 2224 | if !emit( | 2515 | if !emit( |
| 2225 | &mut interleaved, | 2516 | &mut interleaved, |
| 2226 | channels, | 2517 | channels, |
crates/engine/src/demux.rsmodified+464 -50
| @@ -103,9 +103,10 @@ impl Demuxer { | |||
| 103 | } | 103 | } |
| 104 | 104 | ||
| 105 | /// Bits per luma sample the stream is coded at: 8 for everything but an | 105 | /// Bits per luma sample the stream is coded at: 8 for everything but an |
| 106 | - /// HEVC Main 10 track, which decodes into a P010 surface rather than an | 106 | + /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface |
| 107 | - /// NV12 one. Not part of [`VideoMeta`] because nothing above the plugin has | 107 | + /// rather than an NV12 one. Not part of [`VideoMeta`] because nothing above |
| 108 | - /// a use for it -- what comes out of the read-back is 8-bit either way. | 108 | + /// the plugin has a use for it -- what comes out of the read-back is 8-bit |
| 109 | + /// either way. | ||
| 109 | pub fn bit_depth(&self) -> u8 { | 110 | pub fn bit_depth(&self) -> u8 { |
| 110 | match self { | 111 | match self { |
| 111 | Self::Mp4(d) => d.bit_depth, | 112 | Self::Mp4(d) => d.bit_depth, |
| @@ -234,7 +235,9 @@ impl Mp4Demuxer { | |||
| 234 | let (_, entry) = sample_entry(path, track_id)?; | 235 | let (_, entry) = sample_entry(path, track_id)?; |
| 235 | let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C") | 236 | let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C") |
| 236 | .ok_or("no av1C box in the AV1 sample entry")?; | 237 | .ok_or("no av1C box in the AV1 sample entry")?; |
| 237 | - parameter_sets = parse_av1c(av1c)?; | 238 | + let (sets, depth) = parse_av1c(av1c)?; |
| 239 | + parameter_sets = sets; | ||
| 240 | + bit_depth = depth; | ||
| 238 | } | 241 | } |
| 239 | // No parameter sets: a VP9 sample is self-contained. | 242 | // No parameter sets: a VP9 sample is self-contained. |
| 240 | Codec::Vp9 => {} | 243 | Codec::Vp9 => {} |
| @@ -326,18 +329,21 @@ impl Mp4Demuxer { | |||
| 326 | } | 329 | } |
| 327 | } | 330 | } |
| 328 | 331 | ||
| 329 | -/// One Matroska block of the video track: where its bytes are and whether a | 332 | +/// One Matroska block of an indexed track: where its bytes are, whether a |
| 330 | -/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7 | 333 | +/// decoder may start on it, and when it is presented (in `TimestampScale` |
| 331 | -/// MB of index -- the price of knowing the frame count and the sync points of a | 334 | +/// ticks, which is what a sound track seeks against -- Matroska indexes no |
| 335 | +/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of | ||
| 336 | +/// index -- the price of knowing the frame count and the sync points of a | ||
| 332 | /// container that indexes neither. | 337 | /// container that indexes neither. |
| 333 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 338 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 334 | struct Block { | 339 | struct Block { |
| 335 | at: u64, | 340 | at: u64, |
| 336 | len: usize, | 341 | len: usize, |
| 337 | key: bool, | 342 | key: bool, |
| 343 | + ts: i64, | ||
| 338 | } | 344 | } |
| 339 | 345 | ||
| 340 | -/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`). | 346 | +/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). |
| 341 | /// | 347 | /// |
| 342 | /// The whole segment is walked once at open -- element *headers* only, the block | 348 | /// The whole segment is walked once at open -- element *headers* only, the block |
| 343 | /// payloads are seeked over -- because Matroska carries no sample table: the | 349 | /// payloads are seeked over -- because Matroska carries no sample table: the |
| @@ -355,10 +361,11 @@ pub struct MkvDemuxer { | |||
| 355 | /// | 361 | /// |
| 356 | /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is | 362 | /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is |
| 357 | /// an `hvcC` record verbatim -- the same blob, re-injected for the same | 363 | /// an `hvcC` record verbatim -- the same blob, re-injected for the same |
| 358 | - /// reason, as the one [`Mp4Demuxer`] carries. | 364 | + /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the |
| 365 | + /// `avcC` beside it, which is that record's H.264 twin. | ||
| 359 | config: Vec<u8>, | 366 | config: Vec<u8>, |
| 360 | - /// Bytes of the NAL length prefix an HEVC block is written with; unused by | 367 | + /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; |
| 361 | - /// AV1, whose block is one temporal unit and carries no prefixes. | 368 | + /// unused by AV1, whose block is one temporal unit and carries no prefixes. |
| 362 | nal_length: usize, | 369 | nal_length: usize, |
| 363 | /// Bits per luma sample; see [`Demuxer::bit_depth`]. | 370 | /// Bits per luma sample; see [`Demuxer::bit_depth`]. |
| 364 | bit_depth: u8, | 371 | bit_depth: u8, |
| @@ -374,7 +381,7 @@ impl MkvDemuxer { | |||
| 374 | let mut file = File::open(path)?; | 381 | let mut file = File::open(path)?; |
| 375 | let end = file.metadata()?.len(); | 382 | let end = file.metadata()?.len(); |
| 376 | let segment = mkv_segment(&mut file, end)?; | 383 | let segment = mkv_segment(&mut file, end)?; |
| 377 | - let (video, _, other) = mkv_tracks(&mut file, segment)?; | 384 | + let (video, _, other, _) = mkv_tracks(&mut file, segment)?; |
| 378 | let video = match video { | 385 | let video = match video { |
| 379 | Some(video) => video, | 386 | Some(video) => video, |
| 380 | // Named, because "no video track" is a lie about a file that has one | 387 | // Named, because "no video track" is a lie about a file that has one |
| @@ -382,7 +389,7 @@ impl MkvDemuxer { | |||
| 382 | None => { | 389 | None => { |
| 383 | return Err(match other { | 390 | return Err(match other { |
| 384 | Some(codec) => format!( | 391 | Some(codec) => format!( |
| 385 | - "{codec} video in a Matroska file is not supported — AV1 and HEVC are" | 392 | + "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are" |
| 386 | ), | 393 | ), |
| 387 | None => "this Matroska file has no video track".to_string(), | 394 | None => "this Matroska file has no video track".to_string(), |
| 388 | } | 395 | } |
| @@ -483,13 +490,99 @@ impl MkvDemuxer { | |||
| 483 | 490 | ||
| 484 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or | 491 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or |
| 485 | /// `None` for a Matroska file with no sound at all. Header only, and only worth | 492 | /// `None` for a Matroska file with no sound at all. Header only, and only worth |
| 486 | -/// calling once a session has come up silent: no audio track of a Matroska file | 493 | +/// calling once a session has come up silent: a Matroska file's sound is read |
| 487 | -/// is decoded yet, so this exists to say which one is being left out. | 494 | +/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and |
| 495 | +/// this exists to say which codec neither of them took. | ||
| 488 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { | 496 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { |
| 489 | let mut file = File::open(path)?; | 497 | let mut file = File::open(path)?; |
| 490 | let end = file.metadata()?.len(); | 498 | let end = file.metadata()?.len(); |
| 491 | let segment = mkv_segment(&mut file, end)?; | 499 | let segment = mkv_segment(&mut file, end)?; |
| 492 | - Ok(mkv_tracks(&mut file, segment)?.1) | 500 | + Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec)) |
| 501 | +} | ||
| 502 | + | ||
| 503 | +/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio | ||
| 504 | +/// track, in storage order, with the timestamp a seek resolves against. The | ||
| 505 | +/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and | ||
| 506 | +/// the two keep their own file handle and their own index -- the sound is | ||
| 507 | +/// opened by the audio worker and the picture by the decoder, never together. | ||
| 508 | +/// | ||
| 509 | +/// Matroska carries no sample table, so a block's own timestamp is the only | ||
| 510 | +/// thing a window can be resolved against; [`Self::block_at`] is what an `stts` | ||
| 511 | +/// lookup is on the mp4 side. | ||
| 512 | +pub struct MkvAudio { | ||
| 513 | + file: File, | ||
| 514 | + blocks: Vec<Block>, | ||
| 515 | + /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`. | ||
| 516 | + pub codec: &'static str, | ||
| 517 | + /// Seconds one `TimestampScale` tick is worth, resolved once at open. | ||
| 518 | + secs_per_tick: f64, | ||
| 519 | +} | ||
| 520 | + | ||
| 521 | +impl MkvAudio { | ||
| 522 | + /// `Ok(None)` when `path` has no audio track at all, or when its first one | ||
| 523 | + /// is in a codec nothing here decodes -- that file is the silent source it | ||
| 524 | + /// has always been, and [`crate::audio::AudioSession::unsupported`] names | ||
| 525 | + /// the codec. An `Err` is a track that *is* AC-3 and could not be read. | ||
| 526 | + pub fn open(path: &Path) -> crate::Result<Option<Self>> { | ||
| 527 | + let mut file = File::open(path)?; | ||
| 528 | + let end = file.metadata()?.len(); | ||
| 529 | + let segment = mkv_segment(&mut file, end)?; | ||
| 530 | + let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; | ||
| 531 | + let Some((number, codec)) = audio else { | ||
| 532 | + return Ok(None); | ||
| 533 | + }; | ||
| 534 | + let codec = match codec.as_str() { | ||
| 535 | + "A_AC3" => "ac3", | ||
| 536 | + "A_EAC3" => "eac3", | ||
| 537 | + _ => return Ok(None), | ||
| 538 | + }; | ||
| 539 | + let (blocks, _) = mkv_blocks(&mut file, segment, number)?; | ||
| 540 | + if blocks.is_empty() { | ||
| 541 | + return Err("the AC-3 track in this Matroska file has no blocks".into()); | ||
| 542 | + } | ||
| 543 | + Ok(Some(Self { | ||
| 544 | + file, | ||
| 545 | + blocks, | ||
| 546 | + codec, | ||
| 547 | + secs_per_tick: timestamp_scale as f64 / 1e9, | ||
| 548 | + })) | ||
| 549 | + } | ||
| 550 | + | ||
| 551 | + /// How many blocks the track has; one syncframe each, lacing being refused | ||
| 552 | + /// in [`mkv_blocks`]. | ||
| 553 | + pub fn blocks(&self) -> usize { | ||
| 554 | + self.blocks.len() | ||
| 555 | + } | ||
| 556 | + | ||
| 557 | + /// The bytes of block `index` -- one whole packet for the decoder, an | ||
| 558 | + /// E-AC-3 frame's dependent substreams included. `None` past the last one. | ||
| 559 | + pub fn frame(&mut self, index: usize) -> crate::Result<Option<Vec<u8>>> { | ||
| 560 | + let Some(&block) = self.blocks.get(index) else { | ||
| 561 | + return Ok(None); | ||
| 562 | + }; | ||
| 563 | + let mut bytes = vec![0u8; block.len]; | ||
| 564 | + read_exact_at(&mut self.file, block.at, &mut bytes)?; | ||
| 565 | + Ok(Some(bytes)) | ||
| 566 | + } | ||
| 567 | + | ||
| 568 | + /// When block `index` is presented, in seconds on the file's own clock. The | ||
| 569 | + /// last block's time for anything past the end, which is what a duration | ||
| 570 | + /// wants. | ||
| 571 | + pub fn secs(&self, index: usize) -> f64 { | ||
| 572 | + let index = index.min(self.blocks.len().saturating_sub(1)); | ||
| 573 | + self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick | ||
| 574 | + } | ||
| 575 | + | ||
| 576 | + /// The block a decoder is started from to hear `secs`: the last one at or | ||
| 577 | + /// before it, `pre_roll` blocks earlier so the decoder has something to warm | ||
| 578 | + /// up on before the audible part. Blocks are in storage order, which for a | ||
| 579 | + /// sound track is presentation order (no reordering exists in AC-3). | ||
| 580 | + pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize { | ||
| 581 | + let ticks = (secs / self.secs_per_tick) as i64; | ||
| 582 | + self.blocks | ||
| 583 | + .partition_point(|b| b.ts <= ticks) | ||
| 584 | + .saturating_sub(1 + pre_roll) | ||
| 585 | + } | ||
| 493 | } | 586 | } |
| 494 | 587 | ||
| 495 | /// What the `Tracks` element says about the video track. | 588 | /// What the `Tracks` element says about the video track. |
| @@ -539,17 +632,19 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { | |||
| 539 | Err("no Segment element: not a Matroska file".into()) | 632 | Err("no Segment element: not a Matroska file".into()) |
| 540 | } | 633 | } |
| 541 | 634 | ||
| 542 | -/// The video track of `segment`, the codec id of its first audio track, and the | 635 | +/// The video track of `segment`, the number and codec id of its first audio |
| 543 | -/// codec id of a video track this cannot read -- the last two are what tell a | 636 | +/// track, the codec id of a video track this cannot read, and the segment's |
| 544 | -/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`]) | 637 | +/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a |
| 545 | -/// or refuses to open at all. | 638 | +/// sound track from; it and the other codec id are what tell a user why a file |
| 639 | +/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to | ||
| 640 | +/// open at all. | ||
| 546 | /// | 641 | /// |
| 547 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful | 642 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful |
| 548 | /// of seeks whatever the file weighs. | 643 | /// of seeks whatever the file weighs. |
| 549 | fn mkv_tracks( | 644 | fn mkv_tracks( |
| 550 | file: &mut File, | 645 | file: &mut File, |
| 551 | segment: (u64, u64), | 646 | segment: (u64, u64), |
| 552 | -) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> { | 647 | +) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> { |
| 553 | let (mut video, mut audio, mut other) = (None, None, None); | 648 | let (mut video, mut audio, mut other) = (None, None, None); |
| 554 | let mut timestamp_scale = 1_000_000; | 649 | let mut timestamp_scale = 1_000_000; |
| 555 | let mut at = segment.0; | 650 | let mut at = segment.0; |
| @@ -572,7 +667,9 @@ fn mkv_tracks( | |||
| 572 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { | 667 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { |
| 573 | MkvEntry::Video(track) if video.is_none() => video = Some(track), | 668 | MkvEntry::Video(track) if video.is_none() => video = Some(track), |
| 574 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), | 669 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), |
| 575 | - MkvEntry::Audio(codec) if audio.is_none() => audio = Some(codec), | 670 | + MkvEntry::Audio(number, codec) if audio.is_none() => { |
| 671 | + audio = Some((number, codec)) | ||
| 672 | + } | ||
| 576 | _ => {} | 673 | _ => {} |
| 577 | } | 674 | } |
| 578 | } | 675 | } |
| @@ -583,7 +680,7 @@ fn mkv_tracks( | |||
| 583 | } | 680 | } |
| 584 | at = stop; | 681 | at = stop; |
| 585 | } | 682 | } |
| 586 | - Ok((video, audio, other)) | 683 | + Ok((video, audio, other, timestamp_scale)) |
| 587 | } | 684 | } |
| 588 | 685 | ||
| 589 | /// What one `TrackEntry` turned out to be. | 686 | /// What one `TrackEntry` turned out to be. |
| @@ -591,8 +688,9 @@ enum MkvEntry { | |||
| 591 | Video(MkvVideo), | 688 | Video(MkvVideo), |
| 592 | /// A video track in a codec this does not read, by the name it gives itself. | 689 | /// A video track in a codec this does not read, by the name it gives itself. |
| 593 | OtherVideo(String), | 690 | OtherVideo(String), |
| 594 | - /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...). | 691 | + /// An audio track: its track number, which is what [`MkvAudio`] indexes the |
| 595 | - Audio(String), | 692 | + /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). |
| 693 | + Audio(u64, String), | ||
| 596 | /// Subtitles, buttons: nobody's here. | 694 | /// Subtitles, buttons: nobody's here. |
| 597 | Other, | 695 | Other, |
| 598 | } | 696 | } |
| @@ -638,13 +736,23 @@ fn mkv_track_entry( | |||
| 638 | // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 | 736 | // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 |
| 639 | // sample entry carries, so it parses with the very same reader. | 737 | // sample entry carries, so it parses with the very same reader. |
| 640 | let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { | 738 | let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { |
| 641 | - (1, "V_AV1") => (Codec::Av1, 4, parse_av1c(&config)?, 8), | 739 | + (1, "V_AV1") => { |
| 740 | + let (sets, bit_depth) = parse_av1c(&config)?; | ||
| 741 | + (Codec::Av1, 4, sets, bit_depth) | ||
| 742 | + } | ||
| 642 | (1, "V_MPEGH/ISO/HEVC") => { | 743 | (1, "V_MPEGH/ISO/HEVC") => { |
| 643 | let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; | 744 | let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; |
| 644 | (Codec::Hevc, nal_length, sets, bit_depth) | 745 | (Codec::Hevc, nal_length, sets, bit_depth) |
| 645 | } | 746 | } |
| 747 | + // The `avcC` beside them, and the same story: length-prefixed blocks and | ||
| 748 | + // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole | ||
| 749 | + // H.264 path here assumes of an mp4's `avc1` too. | ||
| 750 | + (1, "V_MPEG4/ISO/AVC") => { | ||
| 751 | + let (nal_length, sets) = parse_avcc(&config)?; | ||
| 752 | + (Codec::H264, nal_length, sets, 8) | ||
| 753 | + } | ||
| 646 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), | 754 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), |
| 647 | - (2, _) => return Ok(MkvEntry::Audio(codec)), | 755 | + (2, _) => return Ok(MkvEntry::Audio(number, codec)), |
| 648 | _ => return Ok(MkvEntry::Other), | 756 | _ => return Ok(MkvEntry::Other), |
| 649 | }; | 757 | }; |
| 650 | Ok(MkvEntry::Video(MkvVideo { | 758 | Ok(MkvEntry::Video(MkvVideo { |
| @@ -660,29 +768,79 @@ fn mkv_track_entry( | |||
| 660 | })) | 768 | })) |
| 661 | } | 769 | } |
| 662 | 770 | ||
| 771 | +/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length | ||
| 772 | +/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s | ||
| 773 | +/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a | ||
| 774 | +/// Matroska file carries the identical record in `CodecPrivate`, unparsed. | ||
| 775 | +fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> { | ||
| 776 | + // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets. | ||
| 777 | + let (&flags, &sps_count) = rec | ||
| 778 | + .get(4) | ||
| 779 | + .zip(rec.get(5)) | ||
| 780 | + .ok_or("avcC record shorter than its fixed header")?; | ||
| 781 | + let mut sets = Vec::new(); | ||
| 782 | + let mut src = &rec[6..]; | ||
| 783 | + // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS | ||
| 784 | + // array, whose count is a byte of its own. | ||
| 785 | + let mut count = usize::from(sps_count & 0x1f); | ||
| 786 | + for array in 0..2 { | ||
| 787 | + if array == 1 { | ||
| 788 | + let (&pps_count, rest) = src | ||
| 789 | + .split_first() | ||
| 790 | + .ok_or("avcC record ends before its PPS count")?; | ||
| 791 | + count = usize::from(pps_count); | ||
| 792 | + src = rest; | ||
| 793 | + } | ||
| 794 | + for _ in 0..count { | ||
| 795 | + let len = usize::from(u16::from_be_bytes( | ||
| 796 | + src.get(..2) | ||
| 797 | + .ok_or("avcC NAL length past the record")? | ||
| 798 | + .try_into() | ||
| 799 | + .unwrap(), | ||
| 800 | + )); | ||
| 801 | + let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?; | ||
| 802 | + sets.extend_from_slice(&START_CODE); | ||
| 803 | + sets.extend_from_slice(nal); | ||
| 804 | + src = &src[2 + len..]; | ||
| 805 | + } | ||
| 806 | + } | ||
| 807 | + if sets.is_empty() { | ||
| 808 | + return Err("avcC record carries no SPS/PPS".into()); | ||
| 809 | + } | ||
| 810 | + Ok((usize::from(flags & 0x3) + 1, sets)) | ||
| 811 | +} | ||
| 812 | + | ||
| 663 | /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF | 813 | /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF |
| 664 | /// §2.3.3): four fixed bytes, then the sequence header OBU in the same | 814 | /// §2.3.3): four fixed bytes, then the sequence header OBU in the same |
| 665 | /// low-overhead format the blocks are in, so it needs no reframing. | 815 | /// low-overhead format the blocks are in, so it needs no reframing. |
| 666 | /// | 816 | /// |
| 817 | +/// Also the bits per luma sample, out of `high_bitdepth`/`twelve_bit` in byte 2: | ||
| 818 | +/// 10-bit decodes through the P010 pool HEVC Main 10 already goes through | ||
| 819 | +/// ([`crate::hw`]), 12-bit is refused by name because that pool is the only | ||
| 820 | +/// deeper one there is. | ||
| 821 | +/// | ||
| 667 | /// An empty record is not an error -- an encoder that repeats its sequence | 822 | /// An empty record is not an error -- an encoder that repeats its sequence |
| 668 | -/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for | 823 | +/// header in-band needs none -- and is taken as 8-bit, which is what the depth |
| 669 | -/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage` | 824 | +/// defaults to everywhere else here. |
| 670 | -/// read-back are 8-bit, and the upgrade path is a P010 pool. | 825 | +fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> { |
| 671 | -fn parse_av1c(rec: &[u8]) -> crate::Result<Vec<u8>> { | ||
| 672 | if rec.is_empty() { | 826 | if rec.is_empty() { |
| 673 | - return Ok(Vec::new()); | 827 | + return Ok((Vec::new(), 8)); |
| 674 | } | 828 | } |
| 675 | let &flags = rec | 829 | let &flags = rec |
| 676 | .get(2) | 830 | .get(2) |
| 677 | .ok_or("av1C record shorter than its fixed header")?; | 831 | .ok_or("av1C record shorter than its fixed header")?; |
| 678 | - if flags & 0x40 != 0 { | 832 | + // `twelve_bit` only says anything when `high_bitdepth` is set (AV1 §5.5.1), |
| 679 | - return Err(format!( | 833 | + // so it is read where the record means it and nowhere else. |
| 680 | - "{}-bit AV1 is not supported yet — this file is not 8-bit", | 834 | + let bit_depth = match (flags & 0x40 != 0, flags & 0x20 != 0) { |
| 681 | - if flags & 0x20 != 0 { 12 } else { 10 } | 835 | + (true, true) => { |
| 682 | - ) | 836 | + return Err( |
| 683 | - .into()); | 837 | + "12-bit AV1 is not supported — 8- and 10-bit are what the decoder carries".into(), |
| 684 | - } | 838 | + ); |
| 685 | - Ok(rec.get(4..).unwrap_or_default().to_vec()) | 839 | + } |
| 840 | + (true, false) => 10, | ||
| 841 | + _ => 8, | ||
| 842 | + }; | ||
| 843 | + Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth)) | ||
| 686 | } | 844 | } |
| 687 | 845 | ||
| 688 | /// Every block of track `number`, in storage order, with the presentation span | 846 | /// Every block of track `number`, in storage order, with the presentation span |
| @@ -743,11 +901,17 @@ fn mkv_blocks( | |||
| 743 | if block.number != number { | 901 | if block.number != number { |
| 744 | continue; | 902 | continue; |
| 745 | } | 903 | } |
| 746 | - // Lacing packs several frames into one block. Audio muxers use it, | 904 | + // Lacing packs several frames into one block, behind a header of |
| 747 | - // video ones do not, and guessing at frame boundaries inside a laced | 905 | + // frame sizes this does not read. Video muxers write none; an audio |
| 748 | - // block is not something to do silently. | 906 | + // muxer may, and guessing at frame boundaries inside a laced block |
| 907 | + // is not something to do silently. | ||
| 908 | + // | ||
| 909 | + // ponytail: a laced audio track is refused by name rather than | ||
| 910 | + // played. The upgrade path is the three lace headers of the spec | ||
| 911 | + // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg, | ||
| 912 | + // which writes the fixtures and most remuxes, laces nothing. | ||
| 749 | if block.flags & 0x06 != 0 { | 913 | if block.flags & 0x06 != 0 { |
| 750 | - return Err("laced video blocks are not supported".into()); | 914 | + return Err("laced Matroska blocks are not supported".into()); |
| 751 | } | 915 | } |
| 752 | let ts = cluster_ts + i64::from(block.rel); | 916 | let ts = cluster_ts + i64::from(block.rel); |
| 753 | span = Some(match span { | 917 | span = Some(match span { |
| @@ -758,6 +922,7 @@ fn mkv_blocks( | |||
| 758 | at: block.at, | 922 | at: block.at, |
| 759 | len: block.len, | 923 | len: block.len, |
| 760 | key, | 924 | key, |
| 925 | + ts, | ||
| 761 | }); | 926 | }); |
| 762 | } | 927 | } |
| 763 | } | 928 | } |
| @@ -1138,6 +1303,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option<u32> { | |||
| 1138 | )) | 1303 | )) |
| 1139 | } | 1304 | } |
| 1140 | 1305 | ||
| 1306 | +/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares | ||
| 1307 | +/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the | ||
| 1308 | +/// walk, and it reads every track type 0x11 the file has -- including the ones | ||
| 1309 | +/// nothing here can render, which is how a caller names what it is leaving out | ||
| 1310 | +/// instead of quietly opening a film with no subtitles in the list. | ||
| 1311 | +#[derive(Debug)] | ||
| 1312 | +pub struct MkvSubtitle { | ||
| 1313 | + pub number: u64, | ||
| 1314 | + /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ... | ||
| 1315 | + pub codec: String, | ||
| 1316 | + /// `Language`, ISO-639-2, `und` when the file says nothing. | ||
| 1317 | + pub language: String, | ||
| 1318 | + /// `Name`, the human label a muxer wrote, often empty. | ||
| 1319 | + pub name: String, | ||
| 1320 | + /// `CodecPrivate`: the ASS script header (`[Script Info]` through the | ||
| 1321 | + /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`. | ||
| 1322 | + pub private: Vec<u8>, | ||
| 1323 | + /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs. | ||
| 1324 | + /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks | ||
| 1325 | + /// are megabytes of pictures, and nothing here can draw one. | ||
| 1326 | + pub cues: Vec<MkvCue>, | ||
| 1327 | +} | ||
| 1328 | + | ||
| 1329 | +/// One subtitle block: when it shows and the bytes it shows. | ||
| 1330 | +#[derive(Debug)] | ||
| 1331 | +pub struct MkvCue { | ||
| 1332 | + /// Microseconds from the start of the file -- the block timestamp scaled by | ||
| 1333 | + /// the segment's `TimestampScale`, which is the unit | ||
| 1334 | + /// [`crate::subtitle::Cue`] keeps. | ||
| 1335 | + pub start_us: i64, | ||
| 1336 | + /// `BlockDuration`, microseconds. `None` for a block that declares none, | ||
| 1337 | + /// which leaves how long the cue stays up to the caller. | ||
| 1338 | + pub duration_us: Option<i64>, | ||
| 1339 | + /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated | ||
| 1340 | + /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`. | ||
| 1341 | + pub payload: Vec<u8>, | ||
| 1342 | +} | ||
| 1343 | + | ||
| 1344 | +/// The subtitle tracks of a Matroska file, in file order. An mp4's are not read | ||
| 1345 | +/// (its `tx3g` is a different beast, and no file this project opens carries | ||
| 1346 | +/// one); anything that is not a Matroska file at all is an error, as it is for | ||
| 1347 | +/// [`matroska_audio_codec`]. | ||
| 1348 | +/// | ||
| 1349 | +/// Two passes at most: the header walk stops at the first `Cluster`, and the | ||
| 1350 | +/// cue pass runs only when there is a text track to fill. | ||
| 1351 | +pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> { | ||
| 1352 | + let mut file = File::open(path)?; | ||
| 1353 | + let end = file.metadata()?.len(); | ||
| 1354 | + let segment = mkv_segment(&mut file, end)?; | ||
| 1355 | + let mut tracks: Vec<MkvSubtitle> = Vec::new(); | ||
| 1356 | + let mut timestamp_scale = 1_000_000; | ||
| 1357 | + let mut at = segment.0; | ||
| 1358 | + while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? { | ||
| 1359 | + match id { | ||
| 1360 | + CLUSTER => break, | ||
| 1361 | + INFO => { | ||
| 1362 | + let mut at = body; | ||
| 1363 | + while let Some(e) = ebml_element(&mut file, at, stop)? { | ||
| 1364 | + if e.0 == TIMESTAMP_SCALE { | ||
| 1365 | + timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1); | ||
| 1366 | + } | ||
| 1367 | + at = e.2; | ||
| 1368 | + } | ||
| 1369 | + } | ||
| 1370 | + TRACKS => { | ||
| 1371 | + let mut at = body; | ||
| 1372 | + while let Some(e) = ebml_element(&mut file, at, stop)? { | ||
| 1373 | + if e.0 == TRACK_ENTRY { | ||
| 1374 | + tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?); | ||
| 1375 | + } | ||
| 1376 | + at = e.2; | ||
| 1377 | + } | ||
| 1378 | + } | ||
| 1379 | + _ => {} | ||
| 1380 | + } | ||
| 1381 | + at = stop; | ||
| 1382 | + } | ||
| 1383 | + // The text tracks only: see `MkvSubtitle::cues`. | ||
| 1384 | + let wanted: Vec<u64> = tracks | ||
| 1385 | + .iter() | ||
| 1386 | + .filter(|t| t.codec.starts_with("S_TEXT")) | ||
| 1387 | + .map(|t| t.number) | ||
| 1388 | + .collect(); | ||
| 1389 | + if !wanted.is_empty() { | ||
| 1390 | + mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?; | ||
| 1391 | + } | ||
| 1392 | + Ok(tracks) | ||
| 1393 | +} | ||
| 1394 | + | ||
| 1395 | +/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. | ||
| 1396 | +fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> { | ||
| 1397 | + const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 1398 | + const TRACK_NAME: u32 = 0x536E; | ||
| 1399 | + const SUBTITLE: u64 = 0x11; | ||
| 1400 | + let (mut number, mut kind, mut codec) = (0, 0, String::new()); | ||
| 1401 | + let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); | ||
| 1402 | + let mut at = body; | ||
| 1403 | + while let Some((id, body, stop)) = ebml_element(file, at, end)? { | ||
| 1404 | + match id { | ||
| 1405 | + TRACK_NUMBER => number = ebml_uint(file, body, stop)?, | ||
| 1406 | + TRACK_TYPE => kind = ebml_uint(file, body, stop)?, | ||
| 1407 | + CODEC_ID => codec = string_of(file, body, stop)?, | ||
| 1408 | + CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?, | ||
| 1409 | + TRACK_LANGUAGE => language = string_of(file, body, stop)?, | ||
| 1410 | + TRACK_NAME => name = string_of(file, body, stop)?, | ||
| 1411 | + _ => {} | ||
| 1412 | + } | ||
| 1413 | + at = stop; | ||
| 1414 | + } | ||
| 1415 | + Ok((kind == SUBTITLE).then(|| MkvSubtitle { | ||
| 1416 | + number, | ||
| 1417 | + codec, | ||
| 1418 | + // What a `TrackEntry` without a `Language` element means, by spec. | ||
| 1419 | + language: if language.is_empty() { | ||
| 1420 | + "und".into() | ||
| 1421 | + } else { | ||
| 1422 | + language | ||
| 1423 | + }, | ||
| 1424 | + name, | ||
| 1425 | + private, | ||
| 1426 | + cues: Vec::new(), | ||
| 1427 | + })) | ||
| 1428 | +} | ||
| 1429 | + | ||
| 1430 | +/// Every block of the `wanted` tracks, appended to their entries in `tracks`. | ||
| 1431 | +/// | ||
| 1432 | +/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one | ||
| 1433 | +/// indexes *one* video track and reads no payloads, and a subtitle needs every | ||
| 1434 | +/// track at once, the bytes, and the `BlockDuration` beside them. | ||
| 1435 | +fn mkv_subtitle_blocks( | ||
| 1436 | + file: &mut File, | ||
| 1437 | + segment: (u64, u64), | ||
| 1438 | + timestamp_scale: u64, | ||
| 1439 | + wanted: &[u64], | ||
| 1440 | + tracks: &mut [MkvSubtitle], | ||
| 1441 | +) -> crate::Result<()> { | ||
| 1442 | + const BLOCK_DURATION: u32 = 0x9B; | ||
| 1443 | + // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is | ||
| 1444 | + // nanoseconds per tick and is a millisecond in every file anything writes. | ||
| 1445 | + let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; | ||
| 1446 | + let mut at = segment.0; | ||
| 1447 | + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | ||
| 1448 | + at = stop; | ||
| 1449 | + if id != CLUSTER { | ||
| 1450 | + continue; | ||
| 1451 | + } | ||
| 1452 | + let mut cluster_ts = 0i64; | ||
| 1453 | + let mut child = body; | ||
| 1454 | + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { | ||
| 1455 | + child = stop; | ||
| 1456 | + let (block, duration) = match id { | ||
| 1457 | + CLUSTER_TIMESTAMP => { | ||
| 1458 | + cluster_ts = ebml_uint(file, body, stop)? as i64; | ||
| 1459 | + continue; | ||
| 1460 | + } | ||
| 1461 | + SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None), | ||
| 1462 | + BLOCK_GROUP => { | ||
| 1463 | + let (mut found, mut duration) = (None, None); | ||
| 1464 | + let mut child = body; | ||
| 1465 | + while let Some(e) = ebml_element(file, child, stop)? { | ||
| 1466 | + match e.0 { | ||
| 1467 | + BLOCK => found = Some(mkv_block(file, e.1, e.2)?), | ||
| 1468 | + BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64), | ||
| 1469 | + _ => {} | ||
| 1470 | + } | ||
| 1471 | + child = e.2; | ||
| 1472 | + } | ||
| 1473 | + match found { | ||
| 1474 | + Some(block) => (block, duration), | ||
| 1475 | + None => continue, | ||
| 1476 | + } | ||
| 1477 | + } | ||
| 1478 | + _ => continue, | ||
| 1479 | + }; | ||
| 1480 | + if !wanted.contains(&block.number) { | ||
| 1481 | + continue; | ||
| 1482 | + } | ||
| 1483 | + // As for a video block: guessing at the boundaries inside a laced | ||
| 1484 | + // one is not something to do silently. No muxer laces subtitles. | ||
| 1485 | + if block.flags & 0x06 != 0 { | ||
| 1486 | + return Err("laced subtitle blocks are not supported".into()); | ||
| 1487 | + } | ||
| 1488 | + // A megabyte of *text* in one cue is a corrupt file, not a subtitle, | ||
| 1489 | + // and a crafted length may not reach an allocation through here. | ||
| 1490 | + if block.len > 1 << 20 { | ||
| 1491 | + return Err("a Matroska subtitle block larger than a megabyte".into()); | ||
| 1492 | + } | ||
| 1493 | + let mut payload = vec![0u8; block.len]; | ||
| 1494 | + read_exact_at(file, block.at, &mut payload)?; | ||
| 1495 | + let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else { | ||
| 1496 | + continue; | ||
| 1497 | + }; | ||
| 1498 | + track.cues.push(MkvCue { | ||
| 1499 | + start_us: us(cluster_ts + i64::from(block.rel)), | ||
| 1500 | + duration_us: duration.map(us), | ||
| 1501 | + payload, | ||
| 1502 | + }); | ||
| 1503 | + } | ||
| 1504 | + } | ||
| 1505 | + Ok(()) | ||
| 1506 | +} | ||
| 1507 | + | ||
| 1508 | +/// A string element, without the trailing NULs a `Name` may be padded with. | ||
| 1509 | +fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | ||
| 1510 | + let bytes = ebml_bytes(file, body, stop)?; | ||
| 1511 | + Ok(String::from_utf8_lossy(&bytes) | ||
| 1512 | + .trim_end_matches('\0') | ||
| 1513 | + .to_owned()) | ||
| 1514 | +} | ||
| 1515 | + | ||
| 1141 | #[cfg(test)] | 1516 | #[cfg(test)] |
| 1142 | mod tests { | 1517 | mod tests { |
| 1143 | use super::*; | 1518 | use super::*; |
| @@ -1195,6 +1570,37 @@ mod tests { | |||
| 1195 | assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); | 1570 | assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); |
| 1196 | } | 1571 | } |
| 1197 | 1572 | ||
| 1573 | + /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS | ||
| 1574 | + /// count is five bits of byte 5, the PPS count a byte of its own, and taking | ||
| 1575 | + /// the second for the first is the mistake this checks against. | ||
| 1576 | + #[test] | ||
| 1577 | + fn reads_parameter_sets_out_of_an_avcc_record() { | ||
| 1578 | + let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2]; | ||
| 1579 | + for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] { | ||
| 1580 | + rec.extend_from_slice(&2u16.to_be_bytes()); | ||
| 1581 | + rec.extend_from_slice(&[kind, nal]); | ||
| 1582 | + } | ||
| 1583 | + rec.push(1); // numOfPictureParameterSets | ||
| 1584 | + rec.extend_from_slice(&2u16.to_be_bytes()); | ||
| 1585 | + rec.extend_from_slice(&[8, 0xCC]); | ||
| 1586 | + | ||
| 1587 | + let (len, sets) = parse_avcc(&rec).unwrap(); | ||
| 1588 | + assert_eq!(len, 2, "lengthSizeMinusOne == 1"); | ||
| 1589 | + assert_eq!( | ||
| 1590 | + sets, | ||
| 1591 | + [ | ||
| 1592 | + 0, 0, 0, 1, 7, 0xAA, // SPS | ||
| 1593 | + 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses | ||
| 1594 | + 0, 0, 0, 1, 8, 0xCC, // PPS | ||
| 1595 | + ] | ||
| 1596 | + ); | ||
| 1597 | + // Nothing is read past the end of a truncated record, and a Matroska | ||
| 1598 | + // file with no `CodecPrivate` at all is refused rather than started. | ||
| 1599 | + assert!(parse_avcc(&rec[..5]).is_err()); | ||
| 1600 | + assert!(parse_avcc(&rec[..rec.len() - 1]).is_err()); | ||
| 1601 | + assert!(parse_avcc(&[]).is_err()); | ||
| 1602 | + } | ||
| 1603 | + | ||
| 1198 | /// EBML's variable-length integers, which every Matroska read starts with: | 1604 | /// EBML's variable-length integers, which every Matroska read starts with: |
| 1199 | /// the leading zeros of the first byte are the length, an *id* keeps its | 1605 | /// the leading zeros of the first byte are the length, an *id* keeps its |
| 1200 | /// marker bit and a *size* loses it, and an all-ones size is "unknown". | 1606 | /// marker bit and a *size* loses it, and an all-ones size is "unknown". |
| @@ -1226,8 +1632,9 @@ mod tests { | |||
| 1226 | } | 1632 | } |
| 1227 | 1633 | ||
| 1228 | /// The `av1C` record: four fixed bytes and then the sequence header OBU, | 1634 | /// The `av1C` record: four fixed bytes and then the sequence header OBU, |
| 1229 | - /// which is handed to the decoder as it stands. 10-bit is refused by name | 1635 | + /// which is handed to the decoder as it stands, and the depth beside it -- |
| 1230 | - /// exactly as HEVC Main 10 is, and for the same 8-bit read-back reason. | 1636 | + /// 10-bit reads as 10 (the P010 pool, exactly as HEVC Main 10), 12-bit is |
| 1637 | + /// refused by name. | ||
| 1231 | #[test] | 1638 | #[test] |
| 1232 | fn reads_the_sequence_header_out_of_an_av1c_record() { | 1639 | fn reads_the_sequence_header_out_of_an_av1c_record() { |
| 1233 | // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a | 1640 | // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a |
| @@ -1236,14 +1643,16 @@ mod tests { | |||
| 1236 | rec.extend_from_slice(&[ | 1643 | rec.extend_from_slice(&[ |
| 1237 | 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00, | 1644 | 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00, |
| 1238 | ]); | 1645 | ]); |
| 1239 | - let config = parse_av1c(&rec).unwrap(); | 1646 | + let (config, depth) = parse_av1c(&rec).unwrap(); |
| 1240 | assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs"); | 1647 | assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs"); |
| 1241 | assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header"); | 1648 | assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header"); |
| 1649 | + assert_eq!(depth, 8); | ||
| 1242 | 1650 | ||
| 1243 | let mut ten = rec.clone(); | 1651 | let mut ten = rec.clone(); |
| 1244 | ten[2] |= 0x40; // high_bitdepth | 1652 | ten[2] |= 0x40; // high_bitdepth |
| 1245 | - let refused = parse_av1c(&ten).unwrap_err().to_string(); | 1653 | + let (ten_config, ten_depth) = parse_av1c(&ten).unwrap(); |
| 1246 | - assert!(refused.contains("10-bit"), "{refused}"); | 1654 | + assert_eq!(ten_depth, 10, "what picks the P010 surface pool"); |
| 1655 | + assert_eq!(ten_config, config, "the OBUs are read the same either way"); | ||
| 1247 | let mut twelve = ten.clone(); | 1656 | let mut twelve = ten.clone(); |
| 1248 | twelve[2] |= 0x20; // twelve_bit | 1657 | twelve[2] |= 0x20; // twelve_bit |
| 1249 | assert!( | 1658 | assert!( |
| @@ -1252,10 +1661,15 @@ mod tests { | |||
| 1252 | .to_string() | 1661 | .to_string() |
| 1253 | .contains("12-bit") | 1662 | .contains("12-bit") |
| 1254 | ); | 1663 | ); |
| 1664 | + // `twelve_bit` without `high_bitdepth` says nothing, and an 8-bit | ||
| 1665 | + // record reads as one whatever that bit holds. | ||
| 1666 | + let mut stray = rec.clone(); | ||
| 1667 | + stray[2] |= 0x20; | ||
| 1668 | + assert_eq!(parse_av1c(&stray).unwrap().1, 8); | ||
| 1255 | 1669 | ||
| 1256 | // An encoder that repeats its sequence header in-band writes no record | 1670 | // An encoder that repeats its sequence header in-band writes no record |
| 1257 | // at all, which is not an error; a truncated one is. | 1671 | // at all, which is not an error; a truncated one is. |
| 1258 | - assert!(parse_av1c(&[]).unwrap().is_empty()); | 1672 | + assert!(parse_av1c(&[]).unwrap().0.is_empty()); |
| 1259 | assert!(parse_av1c(&[0x81, 0x05]).is_err()); | 1673 | assert!(parse_av1c(&[0x81, 0x05]).is_err()); |
| 1260 | } | 1674 | } |
| 1261 | 1675 | ||
crates/engine/src/edith.rsmodified+167 -24
| @@ -1,13 +1,15 @@ | |||
| 1 | //! The project file: a line of text per thing, and nothing else. | 1 | //! The project file: a line of text per thing, and nothing else. |
| 2 | //! | 2 | //! |
| 3 | //! ```text | 3 | //! ```text |
| 4 | -//! edith 9 | 4 | +//! edith 10 |
| 5 | //! playhead 90 | 5 | //! playhead 90 |
| 6 | //! resolution 1920 1080 | 6 | //! resolution 1920 1080 |
| 7 | //! fps 30.0 | 7 | //! fps 30.0 |
| 8 | //! limiter -1.0 on | 8 | //! limiter -1.0 on |
| 9 | //! source 0 test_av.mp4 | 9 | //! source 0 test_av.mp4 |
| 10 | //! source 1 /elsewhere/test_av2.mp4 | 10 | //! source 1 /elsewhere/test_av2.mp4 |
| 11 | +//! subtitle - subs.srt | ||
| 12 | +//! subtitle 3 test_av.mp4 | ||
| 11 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk | 13 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk |
| 12 | //! color 0.1:1.2:0.9:-0.3 | 14 | //! color 0.1:1.2:0.9:-0.3 |
| 13 | //! video 1 0 0 120 0 0 0 0 fit 1000 | 15 | //! video 1 0 0 120 0 0 0 0 fit 1000 |
| @@ -23,6 +25,15 @@ | |||
| 23 | //! is an answer only a project holding a video has | 25 | //! is an answer only a project holding a video has |
| 24 | //! ([`crate::PlaybackSession::open_project`]). | 26 | //! ([`crate::PlaybackSession::open_project`]). |
| 25 | //! | 27 | //! |
| 28 | +//! A `subtitle` line is `subtitle <track> <path>`: which track of that file the | ||
| 29 | +//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle | ||
| 30 | +//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the | ||
| 31 | +//! reason a source's is. Only the reference is written: the cues themselves are | ||
| 32 | +//! read back out of the file on the way in, exactly as a clip's pictures are, so | ||
| 33 | +//! a project file stays an edit list. A subtitle file that has gone missing | ||
| 34 | +//! since the save comes back listed and refused by name rather than dropped, | ||
| 35 | +//! which is what keeps a re-save from losing it. | ||
| 36 | +//! | ||
| 26 | //! The `limiter` line is the master limiter over the whole mix | 37 | //! The `limiter` line is the master limiter over the whole mix |
| 27 | //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, | 38 | //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, |
| 28 | //! spelled `on` or `off`. Left out when it is the default, which is off. | 39 | //! spelled `on` or `off`. Left out when it is the default, which is off. |
| @@ -79,7 +90,9 @@ | |||
| 79 | //! is the only way an empty lane could still be there on the way back. A lane | 90 | //! is the only way an empty lane could still be there on the way back. A lane |
| 80 | //! number may not skip one of its kind. | 91 | //! number may not skip one of its kind. |
| 81 | //! | 92 | //! |
| 82 | -//! **Version 8** was this without the `fps` and `limiter` lines and without | 93 | +//! **Version 9** was this without the `subtitle` lines: such a project shows no |
| 94 | +//! subtitles, which is all any project could do. | ||
| 95 | +//! **Version 8** was that without the `fps` and `limiter` lines and without | ||
| 83 | //! the `gain` ones: such a project mixes every lane at unity, limits nothing, | 96 | //! the `gain` ones: such a project mixes every lane at unity, limits nothing, |
| 84 | //! and comes back at the rate its scaffolding source runs at. | 97 | //! and comes back at the rate its scaffolding source runs at. |
| 85 | //! **Version 7** was that without the clip's speed field -- every clip of such | 98 | //! **Version 7** was that without the clip's speed field -- every clip of such |
| @@ -97,8 +110,8 @@ | |||
| 97 | //! cumulatively and copied onto both lanes as one group each, which is exactly | 110 | //! cumulatively and copied onto both lanes as one group each, which is exactly |
| 98 | //! what a v1 timeline meant, and an older file simply equalizes and grades | 111 | //! what a v1 timeline meant, and an older file simply equalizes and grades |
| 99 | //! nothing, and an older one plays everything at real time, and an older one | 112 | //! nothing, and an older one plays everything at real time, and an older one |
| 100 | -//! mixes flat -- and saving any of them writes v9. An older reader refuses a | 113 | +//! mixes flat, and an older one shows no subtitles -- and saving any of them |
| 101 | -//! newer file by name. | 114 | +//! writes v10. An older reader refuses a newer file by name. |
| 102 | //! | 115 | //! |
| 103 | //! Text because an edit list is a few integers and a path, and a path is | 116 | //! Text because an edit list is a few integers and a path, and a path is |
| 104 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. | 117 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. |
| @@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams}; | |||
| 129 | use crate::limiter::Limiter; | 142 | use crate::limiter::Limiter; |
| 130 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; | 143 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; |
| 131 | use crate::scale::FitPolicy; | 144 | use crate::scale::FitPolicy; |
| 145 | +use crate::subtitle::SubtitleTrack; | ||
| 132 | 146 | ||
| 133 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module | 147 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module |
| 134 | /// docs for what those dialects looked like. | 148 | /// docs for what those dialects looked like. |
| 135 | -const MAGIC: &[u8] = b"edith 9"; | 149 | +const MAGIC: &[u8] = b"edith 10"; |
| 150 | +const MAGIC_V9: &[u8] = b"edith 9"; | ||
| 136 | const MAGIC_V8: &[u8] = b"edith 8"; | 151 | const MAGIC_V8: &[u8] = b"edith 8"; |
| 137 | const MAGIC_V7: &[u8] = b"edith 7"; | 152 | const MAGIC_V7: &[u8] = b"edith 7"; |
| 138 | const MAGIC_V6: &[u8] = b"edith 6"; | 153 | const MAGIC_V6: &[u8] = b"edith 6"; |
| @@ -169,6 +184,11 @@ pub struct Document { | |||
| 169 | /// The master limiter. Off for every dialect before v9, and for a v9 file | 184 | /// The master limiter. Off for every dialect before v9, and for a v9 file |
| 170 | /// that leaves the line out. | 185 | /// that leaves the line out. |
| 171 | pub limiter: Limiter, | 186 | pub limiter: Limiter, |
| 187 | + /// The subtitle tracks, as the file names them: the path the cues are in | ||
| 188 | + /// and which track of it, which is what [`crate::subtitle::open`] takes. | ||
| 189 | + /// Reading them is the loader's business, not this module's -- a `.edith` | ||
| 190 | + /// holds no cues. Empty for every dialect before v10. | ||
| 191 | + pub subtitles: Vec<(PathBuf, Option<u64>)>, | ||
| 172 | /// The timeline's frame rate. `None` for every dialect before v9 and for a | 192 | /// The timeline's frame rate. `None` for every dialect before v9 and for a |
| 173 | /// v9 file that leaves it out, which both mean "whatever the scaffolding | 193 | /// v9 file that leaves it out, which both mean "whatever the scaffolding |
| 174 | /// source runs at" -- the inference a project of nothing but stills and | 194 | /// source runs at" -- the inference a project of nothing but stills and |
| @@ -188,6 +208,7 @@ pub fn save( | |||
| 188 | sources: &[Source], | 208 | sources: &[Source], |
| 189 | lanes: &[(LaneKind, Vec<Clip>)], | 209 | lanes: &[(LaneKind, Vec<Clip>)], |
| 190 | gains: &[f32], | 210 | gains: &[f32], |
| 211 | + subtitles: &[SubtitleTrack], | ||
| 191 | eq: &[EqParams], | 212 | eq: &[EqParams], |
| 192 | color: &[ColorParams], | 213 | color: &[ColorParams], |
| 193 | resolution: (u32, u32), | 214 | resolution: (u32, u32), |
| @@ -206,7 +227,8 @@ pub fn save( | |||
| 206 | let result = std::fs::File::create(&part) | 227 | let result = std::fs::File::create(&part) |
| 207 | .and_then(|mut f| { | 228 | .and_then(|mut f| { |
| 208 | f.write_all(&emit( | 229 | f.write_all(&emit( |
| 209 | - &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, | 230 | + &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter, |
| 231 | + playhead, | ||
| 210 | ))?; | 232 | ))?; |
| 211 | f.sync_all() | 233 | f.sync_all() |
| 212 | }) | 234 | }) |
| @@ -243,6 +265,7 @@ fn emit( | |||
| 243 | sources: &[Source], | 265 | sources: &[Source], |
| 244 | lanes: &[(LaneKind, Vec<Clip>)], | 266 | lanes: &[(LaneKind, Vec<Clip>)], |
| 245 | gains: &[f32], | 267 | gains: &[f32], |
| 268 | + subtitles: &[SubtitleTrack], | ||
| 246 | eq: &[EqParams], | 269 | eq: &[EqParams], |
| 247 | color: &[ColorParams], | 270 | color: &[ColorParams], |
| 248 | resolution: (u32, u32), | 271 | resolution: (u32, u32), |
| @@ -280,6 +303,16 @@ fn emit( | |||
| 280 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); | 303 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); |
| 281 | out.push(b'\n'); | 304 | out.push(b'\n'); |
| 282 | } | 305 | } |
| 306 | + // The subtitle tracks, by reference: which track of which file, and never | ||
| 307 | + // the cues (see the module docs). Beside the sources because that is what | ||
| 308 | + // they are -- a file this project reads from -- although nothing indexes | ||
| 309 | + // them and their order is only the order they were added in. | ||
| 310 | + for t in subtitles { | ||
| 311 | + let track = t.track.map_or("-".to_string(), |n| n.to_string()); | ||
| 312 | + out.extend_from_slice(format!("subtitle {track} ").as_bytes()); | ||
| 313 | + escape(t.path.strip_prefix(dir).unwrap_or(&t.path), &mut out); | ||
| 314 | + out.push(b'\n'); | ||
| 315 | + } | ||
| 283 | // Before the clips, for the reason the sources are: a clip names one by the | 316 | // Before the clips, for the reason the sources are: a clip names one by the |
| 284 | // position of its line, so the line has to be there first. | 317 | // position of its line, so the line has to be there first. |
| 285 | for params in eq { | 318 | for params in eq { |
| @@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 379 | // The dialects that wrote a source line without its stream field. Reading | 412 | // The dialects that wrote a source line without its stream field. Reading |
| 380 | // one is the whole of what "an old project still opens" means here. | 413 | // one is the whole of what "an old project still opens" means here. |
| 381 | let streamless = v1 || first == MAGIC_V2; | 414 | let streamless = v1 || first == MAGIC_V2; |
| 382 | - // The one that carries the mix -- lane volumes, the master limiter and the | 415 | + // The one that carries subtitle tracks... |
| 383 | - // rate the timeline was cut at... | 416 | + let v10 = first == MAGIC; |
| 384 | - let v9 = first == MAGIC; | 417 | + // ...the ones that carry the mix -- lane volumes, the master limiter and |
| 418 | + // the rate the timeline was cut at... | ||
| 419 | + let v9 = v10 || first == MAGIC_V9; | ||
| 385 | // ...the ones that carry a per-clip speed... | 420 | // ...the ones that carry a per-clip speed... |
| 386 | let v8 = v9 || first == MAGIC_V8; | 421 | let v8 = v9 || first == MAGIC_V8; |
| 387 | // ...the ones that carry a project resolution and per-clip fit policies... | 422 | // ...the ones that carry a project resolution and per-clip fit policies... |
| @@ -418,6 +453,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 418 | // ...and nothing before v9 carries a mix or a rate: every lane at unity, | 453 | // ...and nothing before v9 carries a mix or a rate: every lane at unity, |
| 419 | // no limiter, and the rate inferred from the scaffold as it always was. | 454 | // no limiter, and the rate inferred from the scaffold as it always was. |
| 420 | gains: Vec::new(), | 455 | gains: Vec::new(), |
| 456 | + // Nothing before v10 shows a subtitle. | ||
| 457 | + subtitles: Vec::new(), | ||
| 421 | limiter: Limiter::default(), | 458 | limiter: Limiter::default(), |
| 422 | fps: None, | 459 | fps: None, |
| 423 | playhead: 0, | 460 | playhead: 0, |
| @@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 528 | doc.gains.resize(doc.lanes.len(), 0.0); | 565 | doc.gains.resize(doc.lanes.len(), 0.0); |
| 529 | doc.gains[at] = float(f[2], n)?; | 566 | doc.gains[at] = float(f[2], n)?; |
| 530 | } | 567 | } |
| 568 | + // Beside the source lines and read the same way: fields first, the | ||
| 569 | + // path last, because a path runs to the end of the line. | ||
| 570 | + b"subtitle" if v10 => { | ||
| 571 | + let at = rest | ||
| 572 | + .iter() | ||
| 573 | + .position(|&b| b == b' ') | ||
| 574 | + .ok_or_else(|| format!("line {n}: subtitle without a path"))?; | ||
| 575 | + let track = match &rest[..at] { | ||
| 576 | + b"-" => None, | ||
| 577 | + field => Some(u64::from(number(field, n)?)), | ||
| 578 | + }; | ||
| 579 | + let path = unescape(&rest[at + 1..], n)?; | ||
| 580 | + if path.as_os_str().is_empty() { | ||
| 581 | + return Err(format!("line {n}: subtitle without a path").into()); | ||
| 582 | + } | ||
| 583 | + doc.subtitles.push(( | ||
| 584 | + // Relative to the project file, as a source path is. | ||
| 585 | + if path.is_absolute() { | ||
| 586 | + path | ||
| 587 | + } else { | ||
| 588 | + dir.join(path) | ||
| 589 | + }, | ||
| 590 | + track, | ||
| 591 | + )); | ||
| 592 | + } | ||
| 531 | b"source" => { | 593 | b"source" => { |
| 532 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { | 594 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { |
| 533 | return Err(format!("line {n}: source after a clip").into()); | 595 | return Err(format!("line {n}: source after a clip").into()); |
| @@ -963,6 +1025,7 @@ mod tests { | |||
| 963 | sources, | 1025 | sources, |
| 964 | lanes, | 1026 | lanes, |
| 965 | &[], | 1027 | &[], |
| 1028 | + &[], | ||
| 966 | eq, | 1029 | eq, |
| 967 | color, | 1030 | color, |
| 968 | resolution, | 1031 | resolution, |
| @@ -972,6 +1035,84 @@ mod tests { | |||
| 972 | ) | 1035 | ) |
| 973 | } | 1036 | } |
| 974 | 1037 | ||
| 1038 | + /// A subtitle track as a save hands one over: the cues are not written and | ||
| 1039 | + /// so are not here either. | ||
| 1040 | + fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack { | ||
| 1041 | + SubtitleTrack { | ||
| 1042 | + path: PathBuf::from(path), | ||
| 1043 | + track, | ||
| 1044 | + label: String::new(), | ||
| 1045 | + cues: Vec::new(), | ||
| 1046 | + refused: None, | ||
| 1047 | + } | ||
| 1048 | + } | ||
| 1049 | + | ||
| 1050 | + /// The v10 line: which track of which file, written beside the sources and | ||
| 1051 | + /// read back as the pair a load opens. And what a v9 file is -- one with no | ||
| 1052 | + /// subtitles at all, which still opens and re-saves as v10. | ||
| 1053 | + #[test] | ||
| 1054 | + fn subtitles_round_trip_as_references_and_a_v9_file_has_none() { | ||
| 1055 | + let dir = PathBuf::from("/proj"); | ||
| 1056 | + let (_, sources, lanes) = doc(); | ||
| 1057 | + let tracks = [ | ||
| 1058 | + subtitle("/proj/subs.srt", None), | ||
| 1059 | + subtitle("/proj/a.mp4", Some(3)), | ||
| 1060 | + subtitle("/elsewhere/od d name.ass", None), | ||
| 1061 | + ]; | ||
| 1062 | + let bytes = super::emit( | ||
| 1063 | + &dir, | ||
| 1064 | + &sources, | ||
| 1065 | + &lanes, | ||
| 1066 | + &[], | ||
| 1067 | + &tracks, | ||
| 1068 | + &[], | ||
| 1069 | + &[], | ||
| 1070 | + (1280, 720), | ||
| 1071 | + None, | ||
| 1072 | + Limiter::default(), | ||
| 1073 | + 0, | ||
| 1074 | + ); | ||
| 1075 | + let text = String::from_utf8_lossy(&bytes); | ||
| 1076 | + assert!( | ||
| 1077 | + text.contains( | ||
| 1078 | + "subtitle - subs.srt\n\ | ||
| 1079 | + subtitle 3 a.mp4\n\ | ||
| 1080 | + subtitle - /elsewhere/od d name.ass\n" | ||
| 1081 | + ), | ||
| 1082 | + "the path is relative where it can be, and runs to the end of its \ | ||
| 1083 | + line, spaces and all: {text}" | ||
| 1084 | + ); | ||
| 1085 | + let back = parse(&bytes, &dir).expect("v10 parses"); | ||
| 1086 | + assert_eq!( | ||
| 1087 | + back.subtitles, | ||
| 1088 | + vec![ | ||
| 1089 | + (PathBuf::from("/proj/subs.srt"), None), | ||
| 1090 | + (PathBuf::from("/proj/a.mp4"), Some(3)), | ||
| 1091 | + (PathBuf::from("/elsewhere/od d name.ass"), None), | ||
| 1092 | + ] | ||
| 1093 | + ); | ||
| 1094 | + | ||
| 1095 | + // A v9 file is a project with no subtitles, and re-saving it writes v10. | ||
| 1096 | + let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | ||
| 1097 | + video 1 0 0 30 0 - - - fit 1000\n"; | ||
| 1098 | + let old = parse(v9, &dir).expect("v9 still loads"); | ||
| 1099 | + assert_eq!(old.subtitles, Vec::new()); | ||
| 1100 | + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n")); | ||
| 1101 | + // ...and the line itself is not a v9 line: a dialect may not be mixed. | ||
| 1102 | + let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) | ||
| 1103 | + .unwrap_err() | ||
| 1104 | + .to_string(); | ||
| 1105 | + assert_eq!(mixed, "line 3: unknown keyword \"subtitle\""); | ||
| 1106 | + // A subtitle line with no path is refused, as a source with none is. | ||
| 1107 | + for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] { | ||
| 1108 | + let file = format!("edith 10\nsource 0 a.mp4\n{line}"); | ||
| 1109 | + assert!( | ||
| 1110 | + parse(file.as_bytes(), &dir).is_err(), | ||
| 1111 | + "{line:?} is not a subtitle line" | ||
| 1112 | + ); | ||
| 1113 | + } | ||
| 1114 | + } | ||
| 1115 | + | ||
| 975 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { | 1116 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { |
| 976 | Clip { | 1117 | Clip { |
| 977 | start, | 1118 | start, |
| @@ -1032,7 +1173,7 @@ mod tests { | |||
| 1032 | let bytes = flat(&dir, &sources, &lanes, 12); | 1173 | let bytes = flat(&dir, &sources, &lanes, 12); |
| 1033 | assert_eq!( | 1174 | assert_eq!( |
| 1034 | String::from_utf8_lossy(&bytes), | 1175 | String::from_utf8_lossy(&bytes), |
| 1035 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1176 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1036 | source 2 /elsewhere/b.mp4\n\ | 1177 | source 2 /elsewhere/b.mp4\n\ |
| 1037 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1178 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1038 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1179 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -1069,7 +1210,7 @@ mod tests { | |||
| 1069 | let bytes = flat(&dir, &sources, &lanes, 7); | 1210 | let bytes = flat(&dir, &sources, &lanes, 7); |
| 1070 | assert_eq!( | 1211 | assert_eq!( |
| 1071 | String::from_utf8_lossy(&bytes), | 1212 | String::from_utf8_lossy(&bytes), |
| 1072 | - "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ | 1213 | + "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1073 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ | 1214 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ |
| 1074 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", | 1215 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", |
| 1075 | "an empty lane is a line of its own; everything else is its clips" | 1216 | "an empty lane is a line of its own; everything else is its clips" |
| @@ -1177,7 +1318,7 @@ mod tests { | |||
| 1177 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); | 1318 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); |
| 1178 | assert_eq!( | 1319 | assert_eq!( |
| 1179 | String::from_utf8_lossy(&bytes), | 1320 | String::from_utf8_lossy(&bytes), |
| 1180 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1321 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1181 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 1322 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 1182 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ | 1323 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ |
| 1183 | eq\n\ | 1324 | eq\n\ |
| @@ -1281,7 +1422,7 @@ mod tests { | |||
| 1281 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); | 1422 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); |
| 1282 | assert_eq!( | 1423 | assert_eq!( |
| 1283 | String::from_utf8_lossy(&bytes), | 1424 | String::from_utf8_lossy(&bytes), |
| 1284 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1425 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1285 | color 0.1:1.2:0.9:-0.3\n\ | 1426 | color 0.1:1.2:0.9:-0.3\n\ |
| 1286 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ | 1427 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ |
| 1287 | color 0.0:1.0:1.0:0.0\n\ | 1428 | color 0.0:1.0:1.0:0.0\n\ |
| @@ -1346,7 +1487,7 @@ mod tests { | |||
| 1346 | (1280, 720), | 1487 | (1280, 720), |
| 1347 | old.playhead | 1488 | old.playhead |
| 1348 | )), | 1489 | )), |
| 1349 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1490 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1350 | eq 80.0:-3.0:0.707:ls\n\ | 1491 | eq 80.0:-3.0:0.707:ls\n\ |
| 1351 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1492 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1352 | ); | 1493 | ); |
| @@ -1384,7 +1525,7 @@ mod tests { | |||
| 1384 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); | 1525 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); |
| 1385 | assert_eq!( | 1526 | assert_eq!( |
| 1386 | String::from_utf8_lossy(&bytes), | 1527 | String::from_utf8_lossy(&bytes), |
| 1387 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1528 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1388 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ | 1529 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ |
| 1389 | audio 1 0 0 30 0 - - - fit 2000\n", | 1530 | audio 1 0 0 30 0 - - - fit 2000\n", |
| 1390 | "the rate is the clip line's last field, in thousandths" | 1531 | "the rate is the clip line's last field, in thousandths" |
| @@ -1413,7 +1554,7 @@ mod tests { | |||
| 1413 | (1280, 720), | 1554 | (1280, 720), |
| 1414 | old.playhead | 1555 | old.playhead |
| 1415 | )), | 1556 | )), |
| 1416 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1557 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1417 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1558 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1418 | ); | 1559 | ); |
| 1419 | // A rate outside what the editor can set is a corrupt line, by name. | 1560 | // A rate outside what the editor can set is a corrupt line, by name. |
| @@ -1450,6 +1591,7 @@ mod tests { | |||
| 1450 | &[0.0, 3.0, -6.5], | 1591 | &[0.0, 3.0, -6.5], |
| 1451 | &[], | 1592 | &[], |
| 1452 | &[], | 1593 | &[], |
| 1594 | + &[], | ||
| 1453 | (1280, 720), | 1595 | (1280, 720), |
| 1454 | Some(23.976023976023978), | 1596 | Some(23.976023976023978), |
| 1455 | limiter, | 1597 | limiter, |
| @@ -1457,7 +1599,7 @@ mod tests { | |||
| 1457 | ); | 1599 | ); |
| 1458 | assert_eq!( | 1600 | assert_eq!( |
| 1459 | String::from_utf8_lossy(&bytes), | 1601 | String::from_utf8_lossy(&bytes), |
| 1460 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ | 1602 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ |
| 1461 | limiter -1.5 on\nsource 0 a.mp4\n\ | 1603 | limiter -1.5 on\nsource 0 a.mp4\n\ |
| 1462 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ | 1604 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ |
| 1463 | audio 2 0 0 30 0 - - - fit 1000\n\ | 1605 | audio 2 0 0 30 0 - - - fit 1000\n\ |
| @@ -1489,7 +1631,7 @@ mod tests { | |||
| 1489 | (1280, 720), | 1631 | (1280, 720), |
| 1490 | old.playhead | 1632 | old.playhead |
| 1491 | )), | 1633 | )), |
| 1492 | - "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1634 | + "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1493 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | 1635 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" |
| 1494 | ); | 1636 | ); |
| 1495 | 1637 | ||
| @@ -1653,7 +1795,7 @@ mod tests { | |||
| 1653 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); | 1795 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); |
| 1654 | assert_eq!( | 1796 | assert_eq!( |
| 1655 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), | 1797 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), |
| 1656 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1798 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1657 | source 2 /elsewhere/b.mp4\n\ | 1799 | source 2 /elsewhere/b.mp4\n\ |
| 1658 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1800 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1659 | audio 1 0 0 30 0 0 - - fit 1000\n" | 1801 | audio 1 0 0 30 0 0 - - fit 1000\n" |
| @@ -1706,7 +1848,7 @@ mod tests { | |||
| 1706 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1848 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1707 | assert_eq!( | 1849 | assert_eq!( |
| 1708 | String::from_utf8_lossy(&v5), | 1850 | String::from_utf8_lossy(&v5), |
| 1709 | - "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1851 | + "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1710 | source 0 /elsewhere/b.mp4\n\ | 1852 | source 0 /elsewhere/b.mp4\n\ |
| 1711 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1853 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1712 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1854 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -1738,7 +1880,7 @@ mod tests { | |||
| 1738 | // Saved again it is the current version, which round-trips to the | 1880 | // Saved again it is the current version, which round-trips to the |
| 1739 | // same document. | 1881 | // same document. |
| 1740 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1882 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1741 | - assert!(v5.starts_with(b"edith 9\n")); | 1883 | + assert!(v5.starts_with(b"edith 10\n")); |
| 1742 | let again = parse(&v5, &dir).expect("v5 parses"); | 1884 | let again = parse(&v5, &dir).expect("v5 parses"); |
| 1743 | assert_eq!(again.lanes, back.lanes); | 1885 | assert_eq!(again.lanes, back.lanes); |
| 1744 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. | 1886 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. |
| @@ -1834,6 +1976,7 @@ mod tests { | |||
| 1834 | &[], | 1976 | &[], |
| 1835 | &[], | 1977 | &[], |
| 1836 | &[], | 1978 | &[], |
| 1979 | + &[], | ||
| 1837 | (1280, 720), | 1980 | (1280, 720), |
| 1838 | None, | 1981 | None, |
| 1839 | Limiter::default(), | 1982 | Limiter::default(), |
| @@ -1843,7 +1986,7 @@ mod tests { | |||
| 1843 | let bytes = std::fs::read(&path).expect("read back"); | 1986 | let bytes = std::fs::read(&path).expect("read back"); |
| 1844 | assert_eq!( | 1987 | assert_eq!( |
| 1845 | String::from_utf8_lossy(&bytes), | 1988 | String::from_utf8_lossy(&bytes), |
| 1846 | - "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ | 1989 | + "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ |
| 1847 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | 1990 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" |
| 1848 | ); | 1991 | ); |
| 1849 | // Loading rejoins the *given* directory, so the file is reached by the | 1992 | // Loading rejoins the *given* directory, so the file is reached by the |
| @@ -1888,10 +2031,10 @@ mod tests { | |||
| 1888 | #[test] | 2031 | #[test] |
| 1889 | fn a_wrong_first_line_is_refused_by_name() { | 2032 | fn a_wrong_first_line_is_refused_by_name() { |
| 1890 | let dir = PathBuf::from("/proj"); | 2033 | let dir = PathBuf::from("/proj"); |
| 1891 | - let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) | 2034 | + let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) |
| 1892 | .unwrap_err() | 2035 | .unwrap_err() |
| 1893 | .to_string(); | 2036 | .to_string(); |
| 1894 | - assert_eq!(err, "line 1: unsupported version 10"); | 2037 | + assert_eq!(err, "line 1: unsupported version 11"); |
| 1895 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { | 2038 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { |
| 1896 | assert_eq!( | 2039 | assert_eq!( |
| 1897 | parse(junk, &dir).unwrap_err().to_string(), | 2040 | parse(junk, &dir).unwrap_err().to_string(), |
crates/engine/src/lib.rsmodified+1 -0
| @@ -17,6 +17,7 @@ pub mod playback; | |||
| 17 | pub mod project; | 17 | pub mod project; |
| 18 | pub mod scale; | 18 | pub mod scale; |
| 19 | pub mod silence; | 19 | pub mod silence; |
| 20 | +pub mod subtitle; | ||
| 20 | pub mod waveform; | 21 | pub mod waveform; |
| 21 | 22 | ||
| 22 | pub use audio::{ | 23 | pub use audio::{ |
crates/engine/src/playback.rsmodified+118 -28
| @@ -673,8 +673,19 @@ impl PlaybackSession { | |||
| 673 | } | 673 | } |
| 674 | 674 | ||
| 675 | let playhead = doc.playhead; | 675 | let playhead = doc.playhead; |
| 676 | + // The subtitle files are read here rather than in the parser: a | ||
| 677 | + // `.edith` names them and holds no cues. One that has gone missing, or | ||
| 678 | + // whose track is a codec of pictures, comes back listed and refused by | ||
| 679 | + // name ([`crate::subtitle::open`]) -- a project does not stop opening | ||
| 680 | + // over a subtitle, and a re-save does not lose the row. | ||
| 681 | + let subtitles = doc | ||
| 682 | + .subtitles | ||
| 683 | + .iter() | ||
| 684 | + .map(|(path, track)| crate::subtitle::open(path, *track)) | ||
| 685 | + .collect(); | ||
| 676 | let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? | 686 | let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? |
| 677 | - .with_mix(&doc.gains, doc.limiter); | 687 | + .with_mix(&doc.gains, doc.limiter) |
| 688 | + .with_subtitles(subtitles); | ||
| 678 | let span = project.composite_span_at(0); | 689 | let span = project.composite_span_at(0); |
| 679 | // Last, because it is the one thing here that cannot be taken back: the | 690 | // Last, because it is the one thing here that cannot be taken back: the |
| 680 | // feeder thread outlives the `Audio` value (it holds its own clones) and | 691 | // feeder thread outlives the `Audio` value (it holds its own clones) and |
| @@ -762,6 +773,47 @@ impl PlaybackSession { | |||
| 762 | self.project.sources() | 773 | self.project.sources() |
| 763 | } | 774 | } |
| 764 | 775 | ||
| 776 | + /// The subtitle tracks on this timeline, in the order they were added: what | ||
| 777 | + /// a front-end lists and what [`save_project`](Self::save_project) writes. | ||
| 778 | + /// A track that could not be read is *in* this list, saying why | ||
| 779 | + /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not | ||
| 780 | + /// dropped. | ||
| 781 | + pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] { | ||
| 782 | + self.project.subtitles() | ||
| 783 | + } | ||
| 784 | + | ||
| 785 | + /// Adds subtitles from `path`: every subtitle track of a Matroska file, or | ||
| 786 | + /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many | ||
| 787 | + /// were added -- 0 for a file whose tracks are all on the timeline already, | ||
| 788 | + /// since importing the same file twice is the same subtitles. | ||
| 789 | + /// | ||
| 790 | + /// An error only when the file cannot be read *at all*; a track this cannot | ||
| 791 | + /// parse is added refused by name, for the reason | ||
| 792 | + /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves: | ||
| 793 | + /// subtitles are not clips and land on no lane. | ||
| 794 | + pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> { | ||
| 795 | + let tracks = match path.extension().is_some_and(|e| { | ||
| 796 | + let e = e.to_string_lossy().to_ascii_lowercase(); | ||
| 797 | + e == "mkv" || e == "webm" | ||
| 798 | + }) { | ||
| 799 | + true => crate::subtitle::of_matroska(path)?, | ||
| 800 | + false => vec![crate::subtitle::open(path, None)], | ||
| 801 | + }; | ||
| 802 | + // A standalone file that could not be parsed is a refusal here rather | ||
| 803 | + // than a row nobody asked for: the import is the moment to say so, and | ||
| 804 | + // the load is the moment to keep it. | ||
| 805 | + if let [one] = &tracks[..] | ||
| 806 | + && one.track.is_none() | ||
| 807 | + && let Some(why) = &one.refused | ||
| 808 | + { | ||
| 809 | + return Err(why.clone().into()); | ||
| 810 | + } | ||
| 811 | + Ok(tracks | ||
| 812 | + .into_iter() | ||
| 813 | + .filter(|t| self.project.add_subtitles(t)) | ||
| 814 | + .count()) | ||
| 815 | + } | ||
| 816 | + | ||
| 765 | /// Writes the timeline to `path` as a `.edith`, atomically (see | 817 | /// Writes the timeline to `path` as a `.edith`, atomically (see |
| 766 | /// [`crate::edith`]). Sources no clip plays from are left out, and the | 818 | /// [`crate::edith`]). Sources no clip plays from are left out, and the |
| 767 | /// playhead is saved with it so a reopened project resumes where it stood. | 819 | /// playhead is saved with it so a reopened project resumes where it stood. |
| @@ -787,6 +839,9 @@ impl PlaybackSession { | |||
| 787 | // project's, not this machine's (the monitoring volume is not | 839 | // project's, not this machine's (the monitoring volume is not |
| 788 | // written and never will be). | 840 | // written and never will be). |
| 789 | &self.project.lane_gains(), | 841 | &self.project.lane_gains(), |
| 842 | + // The subtitle tracks with them, by reference: which file the cues | ||
| 843 | + // are in, never the cues (see [`crate::edith`]). | ||
| 844 | + self.project.subtitles(), | ||
| 790 | &eq, | 845 | &eq, |
| 791 | &color, | 846 | &color, |
| 792 | (self.meta.width, self.meta.height), | 847 | (self.meta.width, self.meta.height), |
| @@ -1611,8 +1666,9 @@ impl PlaybackSession { | |||
| 1611 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take | 1666 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take |
| 1612 | /// back, and nothing reseeks. | 1667 | /// back, and nothing reseeks. |
| 1613 | /// | 1668 | /// |
| 1614 | - /// Refused unless it can join the timeline -- same codec, same audio | 1669 | + /// Refused unless it can join the timeline -- a decoder this machine can |
| 1615 | - /// parameters or both silent; the `Err` names the property that disagrees, | 1670 | + /// open, and audio parameters that agree or none at all; the `Err` names |
| 1671 | + /// the property that disagrees, | ||
| 1616 | /// for a caller to show. Nothing is changed by a refusal. A *resolution* of | 1672 | /// for a caller to show. Nothing is changed by a refusal. A *resolution* of |
| 1617 | /// its own is not a refusal: the clip is placed on the project canvas by its | 1673 | /// its own is not a refusal: the clip is placed on the project canvas by its |
| 1618 | /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame | 1674 | /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame |
| @@ -1739,6 +1795,25 @@ impl PlaybackSession { | |||
| 1739 | } | 1795 | } |
| 1740 | } | 1796 | } |
| 1741 | 1797 | ||
| 1798 | + /// Stops the transport where the timeline stops: the clock is paused and put | ||
| 1799 | + /// on the out point. | ||
| 1800 | + /// | ||
| 1801 | + /// Playing past the last frame is wall time counting on past the end of the | ||
| 1802 | + /// media -- there is no picture left to pace it -- so a session left at EOF | ||
| 1803 | + /// reports a `now()` that walks off the end of the timeline in real time, | ||
| 1804 | + /// and a caller that reads the playhead (a cut, a paste, an insert) then | ||
| 1805 | + /// acts at a position no clip is at. How far off depends only on how long | ||
| 1806 | + /// the window was left open, so no clamp in a caller is worth writing. | ||
| 1807 | + /// | ||
| 1808 | + /// End of stream is deliberately left set: the picture is still the last | ||
| 1809 | + /// frame and this is still the end. That is what makes it safe to call on | ||
| 1810 | + /// the crossing into it -- the state the transport shows does not change, | ||
| 1811 | + /// only the running clock stops. | ||
| 1812 | + pub fn halt_at_end(&mut self) { | ||
| 1813 | + self.pause(); | ||
| 1814 | + self.clock.seek_to(self.timeline_duration()); | ||
| 1815 | + } | ||
| 1816 | + | ||
| 1742 | /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: | 1817 | /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: |
| 1743 | /// one knob, because muting and turning it down are the same thing to the | 1818 | /// one knob, because muting and turning it down are the same thing to the |
| 1744 | /// device, and *which* the user meant is a question only the UI can answer | 1819 | /// device, and *which* the user meant is a question only the UI can answer |
| @@ -1951,8 +2026,9 @@ impl Drop for PlaybackSession { | |||
| 1951 | } | 2026 | } |
| 1952 | 2027 | ||
| 1953 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose | 2028 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose |
| 1954 | -/// parameters are `timeline` and whose audio probes as `first`: same codec, | 2029 | +/// parameters are `timeline` and whose audio probes as `first`: a decoder this |
| 1955 | -/// same audio parameters or both silent, and a frame rate that can be named | 2030 | +/// machine can open, audio parameters that agree (or no audio at all), and a |
| 2031 | +/// frame rate that can be named | ||
| 1956 | /// against the timeline's. The [`Rate`] it will be read at comes back with the | 2032 | /// against the timeline's. The [`Rate`] it will be read at comes back with the |
| 1957 | /// answer, so the number the check was decided on is the number it plays by. | 2033 | /// answer, so the number the check was decided on is the number it plays by. |
| 1958 | /// | 2034 | /// |
| @@ -1961,7 +2037,9 @@ impl Drop for PlaybackSession { | |||
| 1961 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a | 2037 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a |
| 1962 | /// letterboxed clip rather than a refusal, and so is a frame rate of its own: | 2038 | /// letterboxed clip rather than a refusal, and so is a frame rate of its own: |
| 1963 | /// the timeline keeps its own rate and the file is read at [`Rate`] against it | 2039 | /// the timeline keeps its own rate and the file is read at [`Rate`] against it |
| 1964 | -/// ([`PlaybackSession::import`] notes how long it is *here*). | 2040 | +/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same |
| 2041 | +/// codec: every clip opens its own decoder, so a mixed-codec timeline is a | ||
| 2042 | +/// decoder each rather than a refusal. | ||
| 1965 | /// | 2043 | /// |
| 1966 | /// The `Err` names the property that disagrees, and those strings are what a | 2044 | /// The `Err` names the property that disagrees, and those strings are what a |
| 1967 | /// front-end shows verbatim; [`PlaybackSession::import`] and | 2045 | /// front-end shows verbatim; [`PlaybackSession::import`] and |
| @@ -1973,18 +2051,22 @@ fn matches_timeline( | |||
| 1973 | timeline: &VideoMeta, | 2051 | timeline: &VideoMeta, |
| 1974 | first: &Option<crate::AudioProbe>, | 2052 | first: &Option<crate::AudioProbe>, |
| 1975 | ) -> crate::Result<Rate> { | 2053 | ) -> crate::Result<Rate> { |
| 1976 | - // Codec first: one timeline is one kind of source. Mixing them would decode | 2054 | + // The codec is *not* held to the timeline's -- every clip opens its own |
| 1977 | - // (every clip opens its own decoder) but on a machine without the VA-API | 2055 | + // decoder, so an H.264 take and an HEVC one play on one timeline. What the |
| 1978 | - // plugin the VP9 half would be black frames with the refusal only on | 2056 | + // codec gate was really protecting against stays, in the one place that can |
| 1979 | - // stderr, which is exactly what a front-end cannot show. | 2057 | + // actually answer it: on a machine without the VA-API plugin an HEVC or VP9 |
| 1980 | - if meta.codec != timeline.codec { | 2058 | + // clip would be black frames with the refusal on stderr alone, so the file |
| 1981 | - return Err(format!( | 2059 | + // is asked for a decoder *here*, at the door, where the `Err` is still |
| 1982 | - "{} does not match the timeline's {}", | 2060 | + // something a front-end can show. A zero-length range probes and starts no |
| 1983 | - meta.codec.name(), | 2061 | + // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`] |
| 1984 | - timeline.codec.name() | 2062 | + // only enters VA-API off that path. |
| 1985 | - ) | 2063 | + DecodeSession::open_worker( |
| 1986 | - .into()); | 2064 | + &source.path, |
| 1987 | - } | 2065 | + 0, |
| 2066 | + 0, | ||
| 2067 | + ColorParams::default(), | ||
| 2068 | + Composer::passthrough(), | ||
| 2069 | + )?; | ||
| 1988 | // The frame rate is *not* a refusal any more: a file shot at another rate is | 2070 | // The frame rate is *not* a refusal any more: a file shot at another rate is |
| 1989 | // placed for the seconds it lasts and read through [`Rate`] at the | 2071 | // placed for the seconds it lasts and read through [`Rate`] at the |
| 1990 | // decoder's door, so it plays at the speed it was shot at on a timeline | 2072 | // decoder's door, so it plays at the speed it was shot at on a timeline |
| @@ -2002,8 +2084,9 @@ fn matches_timeline( | |||
| 2002 | } | 2084 | } |
| 2003 | 2085 | ||
| 2004 | /// Whether a candidate's audio may join a timeline whose first source probes as | 2086 | /// Whether a candidate's audio may join a timeline whose first source probes as |
| 2005 | -/// `first`: same rate, same layout, or both silent. One output device and one | 2087 | +/// `first`: same rate, same layout -- or no audio of its own at all, which is |
| 2006 | -/// exported track is all there is, and no resampler. | 2088 | +/// silence over the clip's span and agrees with everything. One output device |
| 2089 | +/// and one exported track is all there is, and no resampler. | ||
| 2007 | /// | 2090 | /// |
| 2008 | /// The audio half of [`matches_timeline`], which a stream placed on its own | 2091 | /// The audio half of [`matches_timeline`], which a stream placed on its own |
| 2009 | /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it | 2092 | /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it |
| @@ -2021,9 +2104,9 @@ fn matches_timeline( | |||
| 2021 | /// `Ok(None)` for a timeline whose first such source is silent, and for one of | 2104 | /// `Ok(None)` for a timeline whose first such source is silent, and for one of |
| 2022 | /// nothing but stills. That is a silent timeline, and a file with sound is | 2105 | /// nothing but stills. That is a silent timeline, and a file with sound is |
| 2023 | /// still refused by [`audio_matches`] in the words it always used ("the file | 2106 | /// still refused by [`audio_matches`] in the words it always used ("the file |
| 2024 | -/// has audio, the timeline is silent") -- the same answer a silent *video* as | 2107 | +/// has audio, the timeline is silent") -- the device was opened on source 0's |
| 2025 | -/// source 0 has always given. This function widens which source is asked, not | 2108 | +/// track and there is none to open. This function widens which source is asked, |
| 2026 | -/// what the answer means. | 2109 | +/// not what the answer means. |
| 2027 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { | 2110 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { |
| 2028 | match audio_source_of(sources) { | 2111 | match audio_source_of(sources) { |
| 2029 | Some(first) => AudioSession::probe(&first.path, first.audio_stream), | 2112 | Some(first) => AudioSession::probe(&first.path, first.audio_stream), |
| @@ -2052,12 +2135,19 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R | |||
| 2052 | if probe == *first { | 2135 | if probe == *first { |
| 2053 | return Ok(()); | 2136 | return Ok(()); |
| 2054 | } | 2137 | } |
| 2055 | - Err(match (probe, first) { | 2138 | + // ...and a *silent* file joins whatever the timeline is: it contributes |
| 2056 | - (None, _) => "the file is silent, the timeline has audio".to_string(), | 2139 | + // silence over its span, which is the very thing both audio paths already |
| 2057 | - (_, None) => "the file has audio, the timeline is silent".to_string(), | 2140 | + // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays |
| 2058 | - (Some(a), Some(b)) => format!( | 2141 | + // it, `AudioSession::copy_multi_streams` writes it). There is no rate and |
| 2142 | + // no layout to disagree about, so there is nothing left to refuse. | ||
| 2143 | + let Some(probe) = probe else { | ||
| 2144 | + return Ok(()); | ||
| 2145 | + }; | ||
| 2146 | + Err(match first { | ||
| 2147 | + None => "the file has audio, the timeline is silent".to_string(), | ||
| 2148 | + Some(b) => format!( | ||
| 2059 | "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", | 2149 | "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", |
| 2060 | - a.sample_rate, a.channels, b.sample_rate, b.channels | 2150 | + probe.sample_rate, probe.channels, b.sample_rate, b.channels |
| 2061 | ), | 2151 | ), |
| 2062 | } | 2152 | } |
| 2063 | .into()) | 2153 | .into()) |
crates/engine/src/project.rsmodified+38 -0
| @@ -68,6 +68,7 @@ use crate::color::ColorParams; | |||
| 68 | use crate::eq::EqParams; | 68 | use crate::eq::EqParams; |
| 69 | use crate::limiter::{Limiter, db_to_linear}; | 69 | use crate::limiter::{Limiter, db_to_linear}; |
| 70 | use crate::scale::FitPolicy; | 70 | use crate::scale::FitPolicy; |
| 71 | +use crate::subtitle::SubtitleTrack; | ||
| 71 | 72 | ||
| 72 | /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). | 73 | /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). |
| 73 | /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix | 74 | /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix |
| @@ -618,6 +619,12 @@ pub struct Project { | |||
| 618 | /// Never rolled back by an undo: an id retired by an undone split must not | 619 | /// Never rolled back by an undo: an id retired by an undone split must not |
| 619 | /// come back and group two clips that were never together. | 620 | /// come back and group two clips that were never together. |
| 620 | next_link: u32, | 621 | next_link: u32, |
| 622 | + /// The subtitle tracks this timeline shows, in the order they were added. | ||
| 623 | + /// Not in the lane list and not in the history snapshots, for the reason | ||
| 624 | + /// the limiter is not: which subtitles a project carries is a setting on | ||
| 625 | + /// it, and it is saved as a *reference* to the file the cues came out of | ||
| 626 | + /// ([`crate::subtitle`]). | ||
| 627 | + subtitles: Vec<SubtitleTrack>, | ||
| 621 | /// The master limiter every lane's sound is summed *through* | 628 | /// The master limiter every lane's sound is summed *through* |
| 622 | /// ([`Project::limiter`]). Off by default, and not in the lane list, which | 629 | /// ([`Project::limiter`]). Off by default, and not in the lane list, which |
| 623 | /// is what the history snapshots hold: it is a setting on the mix, like the | 630 | /// is what the history snapshots hold: it is a setting on the mix, like the |
| @@ -652,6 +659,7 @@ impl Project { | |||
| 652 | color: Vec::new(), | 659 | color: Vec::new(), |
| 653 | history: Vec::new(), | 660 | history: Vec::new(), |
| 654 | next_link: 1, | 661 | next_link: 1, |
| 662 | + subtitles: Vec::new(), | ||
| 655 | limiter: Limiter::default(), | 663 | limiter: Limiter::default(), |
| 656 | } | 664 | } |
| 657 | } | 665 | } |
| @@ -760,6 +768,7 @@ impl Project { | |||
| 760 | color, | 768 | color, |
| 761 | history: Vec::new(), | 769 | history: Vec::new(), |
| 762 | next_link, | 770 | next_link, |
| 771 | + subtitles: Vec::new(), | ||
| 763 | limiter: Limiter::default(), | 772 | limiter: Limiter::default(), |
| 764 | }) | 773 | }) |
| 765 | } | 774 | } |
| @@ -1128,6 +1137,35 @@ impl Project { | |||
| 1128 | self | 1137 | self |
| 1129 | } | 1138 | } |
| 1130 | 1139 | ||
| 1140 | + /// The subtitle tracks a *load* puts back, in the order they were saved -- | ||
| 1141 | + /// the same door [`with_mix`](Project::with_mix) is, and no undo step for | ||
| 1142 | + /// the same reason. | ||
| 1143 | + pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self { | ||
| 1144 | + self.subtitles = tracks; | ||
| 1145 | + self | ||
| 1146 | + } | ||
| 1147 | + | ||
| 1148 | + /// What this timeline shows over the picture, in the order they were added: | ||
| 1149 | + /// what a front-end lists and what a save writes. | ||
| 1150 | + pub fn subtitles(&self) -> &[SubtitleTrack] { | ||
| 1151 | + &self.subtitles | ||
| 1152 | + } | ||
| 1153 | + | ||
| 1154 | + /// Adds a track, unless the very same one -- same file, same track number | ||
| 1155 | + /// inside it -- is already on the list. `false` for that repeat: importing | ||
| 1156 | + /// the same `.srt` twice is one subtitle track, not two identical ones. | ||
| 1157 | + pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool { | ||
| 1158 | + if self | ||
| 1159 | + .subtitles | ||
| 1160 | + .iter() | ||
| 1161 | + .any(|t| t.path == track.path && t.track == track.track) | ||
| 1162 | + { | ||
| 1163 | + return false; | ||
| 1164 | + } | ||
| 1165 | + self.subtitles.push(track.clone()); | ||
| 1166 | + true | ||
| 1167 | + } | ||
| 1168 | + | ||
| 1131 | /// What each of [`audio_segments_from`](Project::audio_segments_from)'s | 1169 | /// What each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 1132 | /// lanes is multiplied by on its way into the mix: the same lanes in the | 1170 | /// lanes is multiplied by on its way into the mix: the same lanes in the |
| 1133 | /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` | 1171 | /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` |
crates/engine/src/subtitle.rsadded+344 -0
| @@ -0,0 +1,344 @@ | |||
| 1 | +//! Subtitles: a list of cues with a time on them, out of a file beside the | ||
| 2 | +//! media (`.srt`, `.vtt`, `.ass`) or out of a track inside it. | ||
| 3 | +//! | ||
| 4 | +//! One model for both, because a timeline cannot care which it was: a | ||
| 5 | +//! [`SubtitleTrack`] is where it came from -- a path, and the Matroska track | ||
| 6 | +//! number when it is one of several inside that path -- plus the [`Cue`]s. That | ||
| 7 | +//! pair is also all a `.edith` writes ([`crate::edith`]): the cues are read | ||
| 8 | +//! back out of the file on the way in, exactly as a clip's *pictures* are, so a | ||
| 9 | +//! project file stays an edit list and not a copy of the subtitles. | ||
| 10 | +//! | ||
| 11 | +//! Parsing is `oxideav-subtitle` (SRT, WebVTT) and `oxideav-ass` (ASS/SSA) -- | ||
| 12 | +//! the markup, the override tags and the encoding quirks of a dozen dialects | ||
| 13 | +//! are not this project's to re-derive. What comes back here is plain text: the | ||
| 14 | +//! renderer is a later thing, and a cue nobody can draw yet is still a cue that | ||
| 15 | +//! has to be listed, timed and saved. | ||
| 16 | +//! | ||
| 17 | +//! What is *refused* is refused by name rather than by omission | ||
| 18 | +//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a | ||
| 19 | +//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of | ||
| 20 | +//! them opens with four rows that say so instead of opening with an empty list. | ||
| 21 | + | ||
| 22 | +use std::path::{Path, PathBuf}; | ||
| 23 | + | ||
| 24 | +use oxideav_subtitle::ir::plain_text; | ||
| 25 | + | ||
| 26 | +/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds | ||
| 27 | +/// from the start of the media, which is the unit every parser here speaks. | ||
| 28 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 29 | +pub struct Cue { | ||
| 30 | + pub start_us: i64, | ||
| 31 | + pub end_us: i64, | ||
| 32 | + /// Plain text, `\n` between the lines of a multi-line cue. The markup is | ||
| 33 | + /// resolved and dropped: `<i>` from an SRT, `{\an8}` and `\N` from an ASS. | ||
| 34 | + /// | ||
| 35 | + /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate | ||
| 36 | + /// and thrown away here, because nothing draws a cue yet. The upgrade path | ||
| 37 | + /// is to keep `oxideav_core::Segment` beside this string -- the parsers | ||
| 38 | + /// already hand it over -- and it belongs to whoever writes the renderer. | ||
| 39 | + pub text: String, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// A subtitle track: where it came from and what it says. | ||
| 43 | +#[derive(Clone, Debug)] | ||
| 44 | +pub struct SubtitleTrack { | ||
| 45 | + /// The file it was read out of: a standalone subtitle file, or the media | ||
| 46 | + /// file whose track number is below. | ||
| 47 | + pub path: PathBuf, | ||
| 48 | + /// Which track of `path`, for one embedded in a Matroska file. `None` when | ||
| 49 | + /// `path` *is* the subtitle file. | ||
| 50 | + pub track: Option<u64>, | ||
| 51 | + /// What a list shows: a language, a muxer's name for the track, or the | ||
| 52 | + /// file's own name for a standalone one. | ||
| 53 | + pub label: String, | ||
| 54 | + /// In start order. Empty when [`refused`](Self::refused) says why. | ||
| 55 | + pub cues: Vec<Cue>, | ||
| 56 | + /// Why this track has no cues, when it has none: a codec that is pictures | ||
| 57 | + /// rather than text, a file that has gone missing since the project was | ||
| 58 | + /// saved. `None` for one that parsed -- which a track with genuinely no | ||
| 59 | + /// cues in it also is. | ||
| 60 | + pub refused: Option<String>, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl SubtitleTrack { | ||
| 64 | + /// A track that is there and cannot be read, named and kept: a project | ||
| 65 | + /// re-saved after one of these still lists it, which is the difference | ||
| 66 | + /// between "your subtitles are missing" and losing them for good. | ||
| 67 | + fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self { | ||
| 68 | + Self { | ||
| 69 | + path: path.to_path_buf(), | ||
| 70 | + track, | ||
| 71 | + label, | ||
| 72 | + cues: Vec::new(), | ||
| 73 | + refused: Some(why), | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// The one door a saved subtitle line comes back in through: a standalone file | ||
| 79 | +/// (`track` is `None`) or track `n` of a Matroska file. | ||
| 80 | +/// | ||
| 81 | +/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is | ||
| 82 | +/// not there any more, a track number the file no longer has, a codec of | ||
| 83 | +/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name, | ||
| 84 | +/// because a project that opened yesterday has to open today -- a subtitle is | ||
| 85 | +/// not what a whole timeline should refuse over. | ||
| 86 | +pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack { | ||
| 87 | + let Some(number) = track else { | ||
| 88 | + return external(path); | ||
| 89 | + }; | ||
| 90 | + let label = format!("track {number}"); | ||
| 91 | + let mut tracks = match of_matroska(path) { | ||
| 92 | + Ok(tracks) => tracks, | ||
| 93 | + Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()), | ||
| 94 | + }; | ||
| 95 | + match tracks.iter().position(|t| t.track == Some(number)) { | ||
| 96 | + Some(i) => tracks.swap_remove(i), | ||
| 97 | + None => SubtitleTrack::refused( | ||
| 98 | + path, | ||
| 99 | + track, | ||
| 100 | + label, | ||
| 101 | + format!("no subtitle track {number} in {} any more", path.display()), | ||
| 102 | + ), | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// A standalone subtitle file, parsed by its extension. | ||
| 107 | +fn external(path: &Path) -> SubtitleTrack { | ||
| 108 | + let label = path | ||
| 109 | + .file_name() | ||
| 110 | + .map(|n| n.to_string_lossy().into_owned()) | ||
| 111 | + .unwrap_or_default(); | ||
| 112 | + match parse_file(path) { | ||
| 113 | + Ok(cues) => SubtitleTrack { | ||
| 114 | + path: path.to_path_buf(), | ||
| 115 | + track: None, | ||
| 116 | + label, | ||
| 117 | + cues, | ||
| 118 | + refused: None, | ||
| 119 | + }, | ||
| 120 | + Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()), | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Every subtitle track of a Matroska file, in file order -- the text ones with | ||
| 125 | +/// their cues, the bitmap ones refused by name (see the module docs). | ||
| 126 | +pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> { | ||
| 127 | + Ok(crate::demux::matroska_subtitles(path)? | ||
| 128 | + .into_iter() | ||
| 129 | + .map(|t| { | ||
| 130 | + let label = match (t.name.is_empty(), t.language.as_str()) { | ||
| 131 | + (true, lang) => lang.to_owned(), | ||
| 132 | + (false, "und") => t.name.clone(), | ||
| 133 | + (false, lang) => format!("{lang} — {}", t.name), | ||
| 134 | + }; | ||
| 135 | + match cues_of(&t) { | ||
| 136 | + Ok(cues) => SubtitleTrack { | ||
| 137 | + path: path.to_path_buf(), | ||
| 138 | + track: Some(t.number), | ||
| 139 | + label, | ||
| 140 | + cues, | ||
| 141 | + refused: None, | ||
| 142 | + }, | ||
| 143 | + Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why), | ||
| 144 | + } | ||
| 145 | + }) | ||
| 146 | + .collect()) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// The cues of one Matroska subtitle track, or why it has none. | ||
| 150 | +/// | ||
| 151 | +/// A Matroska text track carries the *timing* on the block and the *text* in | ||
| 152 | +/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is | ||
| 153 | +/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block | ||
| 154 | +/// with the `Start` and `End` fields cut out and the `[Script Info]` header | ||
| 155 | +/// filed away in `CodecPrivate`. Both are put back into the shape their parser | ||
| 156 | +/// reads -- rather than the markup being re-derived here -- which is also what | ||
| 157 | +/// makes an embedded track and the standalone file it was muxed from come back | ||
| 158 | +/// as the same cues. | ||
| 159 | +fn cues_of(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> { | ||
| 160 | + let cues = match track.codec.as_str() { | ||
| 161 | + "S_TEXT/UTF8" | "S_TEXT/ASCII" => track | ||
| 162 | + .cues | ||
| 163 | + .iter() | ||
| 164 | + .map(|c| Cue { | ||
| 165 | + start_us: c.start_us, | ||
| 166 | + end_us: end_of(track, c), | ||
| 167 | + text: srt_body(&String::from_utf8_lossy(&c.payload)), | ||
| 168 | + }) | ||
| 169 | + .collect(), | ||
| 170 | + "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?, | ||
| 171 | + codec => { | ||
| 172 | + return Err(format!( | ||
| 173 | + "{codec} subtitles are pictures, not text — this track is listed, not read" | ||
| 174 | + )); | ||
| 175 | + } | ||
| 176 | + }; | ||
| 177 | + Ok(cues) | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes | ||
| 181 | +/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last. | ||
| 182 | +fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 { | ||
| 183 | + /// How long a cue with nothing to say about it stays up: two seconds, a | ||
| 184 | + /// read of one line. | ||
| 185 | + const NO_DURATION_US: i64 = 2_000_000; | ||
| 186 | + match cue.duration_us { | ||
| 187 | + Some(d) => cue.start_us + d, | ||
| 188 | + None => track | ||
| 189 | + .cues | ||
| 190 | + .iter() | ||
| 191 | + .map(|c| c.start_us) | ||
| 192 | + .find(|&s| s > cue.start_us) | ||
| 193 | + .unwrap_or(cue.start_us + NO_DURATION_US), | ||
| 194 | + } | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the | ||
| 198 | +/// SRT parser, around a timing line this then throws away, because SRT markup | ||
| 199 | +/// is exactly what such a block holds and a second implementation of it here | ||
| 200 | +/// would be a second set of bugs. | ||
| 201 | +fn srt_body(text: &str) -> String { | ||
| 202 | + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); | ||
| 203 | + match oxideav_subtitle::srt::parse(doc.as_bytes()) { | ||
| 204 | + Ok(track) => track | ||
| 205 | + .cues | ||
| 206 | + .first() | ||
| 207 | + .map(|c| plain_text(&c.segments)) | ||
| 208 | + .unwrap_or_default(), | ||
| 209 | + // The parser refuses nothing an SRT body can hold; if it ever does, | ||
| 210 | + // the bytes themselves are a better answer than an empty cue. | ||
| 211 | + Err(_) => text.trim_end().to_owned(), | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate` | ||
| 216 | +/// with every block put back as a `Dialogue` line under it, parsed once as the | ||
| 217 | +/// `.ass` file it came from. | ||
| 218 | +fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> { | ||
| 219 | + let mut doc = String::from_utf8_lossy(&track.private).into_owned(); | ||
| 220 | + if !doc.ends_with('\n') { | ||
| 221 | + doc.push('\n'); | ||
| 222 | + } | ||
| 223 | + for cue in &track.cues { | ||
| 224 | + let fields = String::from_utf8_lossy(&cue.payload); | ||
| 225 | + // `ReadOrder,Layer,<the Format fields from Style on>`: the two the | ||
| 226 | + // block adds go, and the timing the block *is* takes their place. The | ||
| 227 | + // field order is the one the header's `Format:` line declares, which | ||
| 228 | + // is the order a demuxer strips them out of. | ||
| 229 | + let mut rest = fields.trim_end().splitn(3, ','); | ||
| 230 | + let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) { | ||
| 231 | + (Some(r), Some(l), Some(t)) => (r, l, t), | ||
| 232 | + _ => continue, | ||
| 233 | + }; | ||
| 234 | + doc.push_str(&format!( | ||
| 235 | + "Dialogue: {layer},{},{},{rest}\n", | ||
| 236 | + timestamp(cue.start_us), | ||
| 237 | + timestamp(end_of(track, cue)) | ||
| 238 | + )); | ||
| 239 | + } | ||
| 240 | + let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?; | ||
| 241 | + // The timings above are centiseconds, which is all an ASS line can say; | ||
| 242 | + // the blocks are microseconds. So the text comes from the parse and the | ||
| 243 | + // timing from the block -- unless a line was dropped as unparsable, when | ||
| 244 | + // the pairing is no longer sound and the parse answers for both. | ||
| 245 | + let exact = parsed.cues.len() == track.cues.len(); | ||
| 246 | + Ok(parsed | ||
| 247 | + .cues | ||
| 248 | + .iter() | ||
| 249 | + .enumerate() | ||
| 250 | + .map(|(i, c)| Cue { | ||
| 251 | + start_us: if exact { | ||
| 252 | + track.cues[i].start_us | ||
| 253 | + } else { | ||
| 254 | + c.start_us | ||
| 255 | + }, | ||
| 256 | + end_us: if exact { | ||
| 257 | + end_of(track, &track.cues[i]) | ||
| 258 | + } else { | ||
| 259 | + c.end_us | ||
| 260 | + }, | ||
| 261 | + text: plain_text(&c.segments), | ||
| 262 | + }) | ||
| 263 | + .collect()) | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +/// Microseconds as ASS writes a time: `H:MM:SS.cc`. | ||
| 267 | +fn timestamp(us: i64) -> String { | ||
| 268 | + let cs = (us.max(0) + 5_000) / 10_000; | ||
| 269 | + format!( | ||
| 270 | + "{}:{:02}:{:02}.{:02}", | ||
| 271 | + cs / 360_000, | ||
| 272 | + cs / 6_000 % 60, | ||
| 273 | + cs / 100 % 60, | ||
| 274 | + cs % 100 | ||
| 275 | + ) | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +/// A standalone subtitle file, by extension: the formats this engine reads at | ||
| 279 | +/// all. Anything else is refused by name, as an unknown media file is. | ||
| 280 | +fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> { | ||
| 281 | + let ext = path | ||
| 282 | + .extension() | ||
| 283 | + .map(|e| e.to_string_lossy().to_ascii_lowercase()) | ||
| 284 | + .unwrap_or_default(); | ||
| 285 | + // The extension before the read: a `.txt` is refused for what it is, not | ||
| 286 | + // for whether it happens to be there. | ||
| 287 | + type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>; | ||
| 288 | + let parse: Parse = match ext.as_str() { | ||
| 289 | + "srt" => oxideav_subtitle::srt::parse, | ||
| 290 | + "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse, | ||
| 291 | + "ass" | "ssa" => oxideav_ass::parse, | ||
| 292 | + other => { | ||
| 293 | + return Err(format!( | ||
| 294 | + "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are" | ||
| 295 | + ) | ||
| 296 | + .into()); | ||
| 297 | + } | ||
| 298 | + }; | ||
| 299 | + let track = parse(&std::fs::read(path)?); | ||
| 300 | + let track = track.map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 301 | + Ok(track | ||
| 302 | + .cues | ||
| 303 | + .iter() | ||
| 304 | + .map(|c| Cue { | ||
| 305 | + start_us: c.start_us, | ||
| 306 | + end_us: c.end_us, | ||
| 307 | + text: plain_text(&c.segments), | ||
| 308 | + }) | ||
| 309 | + .collect()) | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +#[cfg(test)] | ||
| 313 | +mod tests { | ||
| 314 | + use super::*; | ||
| 315 | + | ||
| 316 | + #[test] | ||
| 317 | + fn ass_timestamps_are_written_the_way_ass_reads_them() { | ||
| 318 | + assert_eq!(timestamp(0), "0:00:00.00"); | ||
| 319 | + assert_eq!(timestamp(500_000), "0:00:00.50"); | ||
| 320 | + assert_eq!(timestamp(3_250_000), "0:00:03.25"); | ||
| 321 | + // An hour, a minute and a second, and a negative time is not one. | ||
| 322 | + assert_eq!(timestamp(3_661_000_000), "1:01:01.00"); | ||
| 323 | + assert_eq!(timestamp(-1), "0:00:00.00"); | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + #[test] | ||
| 327 | + fn srt_markup_is_resolved_not_carried() { | ||
| 328 | + assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain"); | ||
| 329 | + assert_eq!(srt_body("two\nlines\n"), "two\nlines"); | ||
| 330 | + } | ||
| 331 | + | ||
| 332 | + #[test] | ||
| 333 | + fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() { | ||
| 334 | + let err = parse_file(Path::new("/nonexistent/notes.txt")) | ||
| 335 | + .unwrap_err() | ||
| 336 | + .to_string(); | ||
| 337 | + assert!(err.contains("txt"), "{err}"); | ||
| 338 | + // ...and a `.srt` that is not there comes back as a track that says so | ||
| 339 | + // rather than as no track at all, so a re-save does not lose it. | ||
| 340 | + let gone = external(Path::new("/nonexistent/subs.srt")); | ||
| 341 | + assert!(gone.refused.is_some()); | ||
| 342 | + assert_eq!(gone.label, "subs.srt"); | ||
| 343 | + } | ||
| 344 | +} | ||
crates/engine/src/waveform.rsmodified+39 -4
| @@ -15,10 +15,18 @@ use crate::AudioSession; | |||
| 15 | /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always | 15 | /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always |
| 16 | /// straddles zero, so silence draws as a flat line. | 16 | /// straddles zero, so silence draws as a flat line. |
| 17 | /// | 17 | /// |
| 18 | -/// Decoding the whole file runs at ~1700x realtime, but it is still linear in | 18 | +/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and |
| 19 | -/// source length: callers cache the result per source *and stream* — two | 19 | +/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but |
| 20 | -/// streams of one file are two different envelopes, and a cache keyed on the | 20 | +/// it is linear in source length either way: callers cache the result per source |
| 21 | -/// path alone would draw the first one under both. | 21 | +/// *and stream* — two streams of one file are two different envelopes, and a |
| 22 | +/// cache keyed on the path alone would draw the first one under both. Memory is | ||
| 23 | +/// flat in it, though: chunks are consumed as they arrive and only the buckets | ||
| 24 | +/// are kept (2 hours at 10/s is 70k pairs). | ||
| 25 | +/// | ||
| 26 | +/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film | ||
| 27 | +/// before its lane has a waveform. The upgrade path is decoding the source in | ||
| 28 | +/// segments on several threads — `open_multi_streams` already takes a window per | ||
| 29 | +/// call — and stitching the buckets, which the fold to one envelope makes safe. | ||
| 22 | pub fn peaks( | 30 | pub fn peaks( |
| 23 | path: impl AsRef<Path>, | 31 | path: impl AsRef<Path>, |
| 24 | stream: usize, | 32 | stream: usize, |
| @@ -141,6 +149,33 @@ mod tests { | |||
| 141 | assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); | 149 | assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); |
| 142 | } | 150 | } |
| 143 | 151 | ||
| 152 | + /// The shape the ask came from: a film in an mkv with a 5.1 AAC track, | ||
| 153 | + /// which no symphonia decoder takes (`aac: aac too complex`) and which | ||
| 154 | + /// therefore reaches the lane through `rusty_aac` and the stereo fold. A | ||
| 155 | + /// clip of one draws a waveform like any other -- an envelope that is not | ||
| 156 | + /// flat -- rather than the empty band a silent file makes. | ||
| 157 | + #[test] | ||
| 158 | + fn a_five_one_aac_mkv_draws_an_envelope() { | ||
| 159 | + let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS) | ||
| 160 | + .expect("the 5.1 AAC track decodes") | ||
| 161 | + .expect("test_hevc10.mkv has an audio track"); | ||
| 162 | + let want = 2 * BPS as usize; // 2 s of tones | ||
| 163 | + assert!( | ||
| 164 | + peaks.len().abs_diff(want) <= 2, | ||
| 165 | + "{} buckets, want {want} +/-2", | ||
| 166 | + peaks.len() | ||
| 167 | + ); | ||
| 168 | + // Six tones, one per channel, folded to stereo: every bucket carries | ||
| 169 | + // signal, and a decode that came out silent (or clipped to a rail) is | ||
| 170 | + // exactly what this refuses. | ||
| 171 | + for (i, &(lo, hi)) in peaks.iter().enumerate() { | ||
| 172 | + assert!( | ||
| 173 | + (0.02..2.0).contains(&(hi - lo)), | ||
| 174 | + "bucket {i} is ({lo}, {hi})" | ||
| 175 | + ); | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + | ||
| 144 | #[test] | 179 | #[test] |
| 145 | fn video_only_source_has_no_peaks() { | 180 | fn video_only_source_has_no_peaks() { |
| 146 | assert!( | 181 | assert!( |
crates/engine/tests/audio_decode.rsmodified+134 -0
| @@ -160,6 +160,103 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { | |||
| 160 | } | 160 | } |
| 161 | } | 161 | } |
| 162 | 162 | ||
| 163 | +/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and | ||
| 164 | +/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" | ||
| 165 | +/// refusal used to fire on -- both come out of the blocks, both arrive as the | ||
| 166 | +/// stereo the §7.8 downmix hands the timeline, and neither owes the session an | ||
| 167 | +/// excuse any more. | ||
| 168 | +#[test] | ||
| 169 | +fn matroska_ac3_and_eac3_decode_out_of_the_blocks() { | ||
| 170 | + for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] { | ||
| 171 | + let path = asset(name); | ||
| 172 | + let (meta, rx) = AudioSession::open(&path) | ||
| 173 | + .expect("open") | ||
| 174 | + .expect("Matroska AC-3 decodes now"); | ||
| 175 | + assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}"); | ||
| 176 | + let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 177 | + let secs = (samples.len() / 2) as f64 / 48000.0; | ||
| 178 | + assert!( | ||
| 179 | + (1.9..2.1).contains(&secs), | ||
| 180 | + "{name} is two seconds, decoded {secs:.3}s" | ||
| 181 | + ); | ||
| 182 | + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() | ||
| 183 | + / samples.len() as f64) | ||
| 184 | + .sqrt(); | ||
| 185 | + assert!( | ||
| 186 | + (0.005..0.75).contains(&rms), | ||
| 187 | + "{name}: RMS {rms:.6} is not a sine at a sane level" | ||
| 188 | + ); | ||
| 189 | + assert!( | ||
| 190 | + samples.iter().all(|s| s.abs() <= 1.0), | ||
| 191 | + "{name}: the decode must not leave the device's range" | ||
| 192 | + ); | ||
| 193 | + // The user-facing half: the session comes up with sound and no notice, | ||
| 194 | + // and the file's one audio stream is offered by the name it is in. | ||
| 195 | + let session = engine::PlaybackSession::open(&path).expect("open for playback"); | ||
| 196 | + assert_eq!( | ||
| 197 | + session.audio_disabled_reason(), | ||
| 198 | + None, | ||
| 199 | + "{name}: a track that decodes owes no excuse" | ||
| 200 | + ); | ||
| 201 | + let streams = AudioSession::probe_streams(&path).expect("streams"); | ||
| 202 | + assert_eq!(streams.len(), 1, "{name}: one audio track, one row"); | ||
| 203 | + assert_eq!(streams[0].codec, codec, "{name}"); | ||
| 204 | + assert!(streams[0].decodable, "{name}"); | ||
| 205 | + assert_eq!( | ||
| 206 | + AudioSession::unsupported(&path).expect("unsupported"), | ||
| 207 | + None, | ||
| 208 | + "{name}: nothing to excuse when it plays" | ||
| 209 | + ); | ||
| 210 | + } | ||
| 211 | + // The invariant, stated as an assert: the AAC track of a Matroska file is | ||
| 212 | + // still symphonia's, listed and decoded exactly as it was. | ||
| 213 | + let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams"); | ||
| 214 | + assert_eq!(streams.len(), 1); | ||
| 215 | + assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this"); | ||
| 216 | + assert!( | ||
| 217 | + AudioSession::open(asset("test_av1.mkv")) | ||
| 218 | + .expect("open") | ||
| 219 | + .is_some(), | ||
| 220 | + "AAC in an mkv still decodes" | ||
| 221 | + ); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block | ||
| 225 | +/// a decode starts on is found by the blocks' own timestamps -- and getting that | ||
| 226 | +/// wrong is a tail that is the wrong length or lands in the wrong place. It is | ||
| 227 | +/// the same check `audio_seek` makes of the mp4 path, on the container that has | ||
| 228 | +/// no sample table. | ||
| 229 | +#[test] | ||
| 230 | +fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() { | ||
| 231 | + let path = asset("test_eac3.mkv"); | ||
| 232 | + let full: Vec<f32> = AudioSession::open(&path) | ||
| 233 | + .expect("open") | ||
| 234 | + .expect("audio") | ||
| 235 | + .1 | ||
| 236 | + .into_iter() | ||
| 237 | + .flat_map(|c| c.samples) | ||
| 238 | + .collect(); | ||
| 239 | + let start = 48_000u64; // one second in, in frames per channel | ||
| 240 | + let mut next = start; | ||
| 241 | + let mut tail = Vec::new(); | ||
| 242 | + for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 { | ||
| 243 | + assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek"); | ||
| 244 | + next += (chunk.samples.len() / 2) as u64; | ||
| 245 | + tail.extend(chunk.samples); | ||
| 246 | + } | ||
| 247 | + let want = &full[start as usize * 2..]; | ||
| 248 | + assert_eq!(tail.len(), want.len(), "the seeked run is a different length"); | ||
| 249 | + let diff = tail | ||
| 250 | + .iter() | ||
| 251 | + .zip(want) | ||
| 252 | + .map(|(a, b)| (a - b).abs()) | ||
| 253 | + .fold(0.0f32, f32::max); | ||
| 254 | + // One syncframe of pre-roll is what the 256-sample overlap-add needs, so | ||
| 255 | + // this is exact in practice; the tolerance is for a decoder that carries | ||
| 256 | + // more state than the frame before, not for a wrong block. | ||
| 257 | + assert!(diff < 1e-3, "max abs diff {diff} after the seek"); | ||
| 258 | +} | ||
| 259 | + | ||
| 163 | /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the | 260 | /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the |
| 164 | /// *copy* path names it and hands the export on to the re-encode (which decodes | 261 | /// *copy* path names it and hands the export on to the re-encode (which decodes |
| 165 | /// this very source: the downmix above is what it encodes). Named either way -- | 262 | /// this very source: the downmix above is what it encodes). Named either way -- |
| @@ -175,3 +272,40 @@ fn an_ac3_source_refuses_an_mp4_audio_copy() { | |||
| 175 | "unhelpful refusal: {err}" | 272 | "unhelpful refusal: {err}" |
| 176 | ); | 273 | ); |
| 177 | } | 274 | } |
| 275 | + | ||
| 276 | +/// The two things a Matroska file with no *readable* sound can be, told apart: | ||
| 277 | +/// a file with no audio track is the silent source it says it is, and a file | ||
| 278 | +/// whose audio will not open at all is an error. They used to be the same | ||
| 279 | +/// answer -- silence -- so a broken track played and exported as a hole with | ||
| 280 | +/// nothing but an `eprintln` to say why. | ||
| 281 | +#[test] | ||
| 282 | +fn a_matroska_with_no_track_is_silent_and_a_broken_one_is_an_error() { | ||
| 283 | + // No audio track at all: a picture and two subtitle tracks. Silent, and the | ||
| 284 | + // stream picker offers nothing rather than refusing the file. | ||
| 285 | + let subs = asset("test_subs.mkv"); | ||
| 286 | + assert!( | ||
| 287 | + AudioSession::probe(&subs, 0) | ||
| 288 | + .expect("no audio is not an error") | ||
| 289 | + .is_none(), | ||
| 290 | + "an mkv with no audio track is a silent source" | ||
| 291 | + ); | ||
| 292 | + assert!(AudioSession::probe_streams(&subs).expect("list").is_empty()); | ||
| 293 | + assert!( | ||
| 294 | + AudioSession::open(&subs).expect("open").is_none(), | ||
| 295 | + "no sound" | ||
| 296 | + ); | ||
| 297 | + | ||
| 298 | + // ...and a file that will not parse at all, under the same extension: an | ||
| 299 | + // `Err` a front-end can show, not a silent import. | ||
| 300 | + let broken = std::env::temp_dir().join(format!("ve_broken_{}.mkv", std::process::id())); | ||
| 301 | + std::fs::write(&broken, b"\x1a\x45\xdf\xa3not a matroska file at all").expect("write"); | ||
| 302 | + let err = AudioSession::probe(&broken, 0) | ||
| 303 | + .expect_err("a broken file must not pass for a silent one") | ||
| 304 | + .to_string(); | ||
| 305 | + assert!(!err.is_empty(), "the refusal says something"); | ||
| 306 | + assert!( | ||
| 307 | + AudioSession::probe_streams(&broken).is_err(), | ||
| 308 | + "and so does the listing" | ||
| 309 | + ); | ||
| 310 | + std::fs::remove_file(&broken).unwrap(); | ||
| 311 | +} | ||
crates/engine/tests/audio_export.rsmodified+61 -0
| @@ -673,6 +673,67 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { | |||
| 673 | } | 673 | } |
| 674 | } | 674 | } |
| 675 | 675 | ||
| 676 | +/// The samples a silent take contributes: a clip of a file with no audio track | ||
| 677 | +/// is silence for exactly its span, between two clips that are heard. This is | ||
| 678 | +/// what makes `PlaybackSession::import` letting such a file in honest -- the | ||
| 679 | +/// export reads the same play list playback does, so a hole here is a hole in | ||
| 680 | +/// the ear too. | ||
| 681 | +#[test] | ||
| 682 | +fn a_silent_clip_exports_as_silence_over_its_own_span() { | ||
| 683 | + let clip = |start, source| Clip { | ||
| 684 | + start, | ||
| 685 | + in_frame: 0, | ||
| 686 | + out_frame: 30, | ||
| 687 | + source, | ||
| 688 | + link: None, | ||
| 689 | + eq: None, | ||
| 690 | + color: None, | ||
| 691 | + fit: FitPolicy::default(), | ||
| 692 | + speed: Speed::NORMAL, | ||
| 693 | + }; | ||
| 694 | + let project = Project::from_parts( | ||
| 695 | + vec![ | ||
| 696 | + Source::new(asset("test_av.mp4"), 0), | ||
| 697 | + // Video only, no audio track at all: the silent take. | ||
| 698 | + Source::new(asset("test_mismatch.mp4"), 0), | ||
| 699 | + ], | ||
| 700 | + vec![ | ||
| 701 | + (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]), | ||
| 702 | + (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]), | ||
| 703 | + ], | ||
| 704 | + Vec::new(), | ||
| 705 | + Vec::new(), | ||
| 706 | + ) | ||
| 707 | + .expect("a project whose middle take is silent"); | ||
| 708 | + | ||
| 709 | + let out = out_path("silent_clip", "wav"); | ||
| 710 | + let handle = engine::export::start( | ||
| 711 | + project, | ||
| 712 | + meta(), | ||
| 713 | + &out, | ||
| 714 | + &ExportSettings { | ||
| 715 | + format: Format::Wav, | ||
| 716 | + ..Default::default() | ||
| 717 | + }, | ||
| 718 | + ); | ||
| 719 | + wait(&handle, Duration::from_secs(60)).expect("wav export"); | ||
| 720 | + let (audio, samples) = decode(&out); | ||
| 721 | + let channels = usize::from(audio.channels); | ||
| 722 | + assert_eq!( | ||
| 723 | + samples.len(), | ||
| 724 | + (3.0 * f64::from(RATE)) as usize * channels, | ||
| 725 | + "three seconds of timeline, silent take included" | ||
| 726 | + ); | ||
| 727 | + let heard = rms(&samples, channels, 0.05, 0.95); | ||
| 728 | + let quiet = rms(&samples, channels, 1.0, 2.0); | ||
| 729 | + let again = rms(&samples, channels, 2.05, 2.95); | ||
| 730 | + println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}"); | ||
| 731 | + assert!(heard > 0.01, "the first take is audible"); | ||
| 732 | + assert!(again > 0.01, "the third take is audible"); | ||
| 733 | + assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall"); | ||
| 734 | + std::fs::remove_file(&out).unwrap(); | ||
| 735 | +} | ||
| 736 | + | ||
| 676 | /// A silent timeline cannot become an audio file, and says so rather than | 737 | /// A silent timeline cannot become an audio file, and says so rather than |
| 677 | /// writing zero samples that a user would take for a broken microphone. | 738 | /// writing zero samples that a user would take for a broken microphone. |
| 678 | #[test] | 739 | #[test] |
crates/engine/tests/audio_multi.rsmodified+67 -7
| @@ -250,18 +250,19 @@ fn the_join_carries_no_second_priming_packet() { | |||
| 250 | } | 250 | } |
| 251 | 251 | ||
| 252 | #[test] | 252 | #[test] |
| 253 | -fn a_source_without_the_timeline_audio_is_refused() { | 253 | +fn a_source_that_disagrees_on_rate_or_layout_is_refused() { |
| 254 | - // Import refuses these up front (same rate, same layout, or both silent); | 254 | + // Import refuses these up front (one output device, one set of parameters); |
| 255 | // the copy and the decode paths refuse them again rather than mislabel one | 255 | // the copy and the decode paths refuse them again rather than mislabel one |
| 256 | - // esds for two different tracks. | 256 | + // esds for two different tracks. Stream 1 of the multi-audio fixture is |
| 257 | - let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; | 257 | + // 22.05 kHz mono against the timeline's 44.1 kHz stereo. |
| 258 | + let mixed = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)]; | ||
| 258 | let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; | 259 | let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; |
| 259 | // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) | 260 | // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) |
| 260 | for e in [ | 261 | for e in [ |
| 261 | - AudioSession::copy_multi_segments(&mixed, &segs).err(), | 262 | + AudioSession::copy_multi_streams(&mixed, &segs).err(), |
| 262 | - AudioSession::open_multi_segments(&mixed, &segs).err(), | 263 | + AudioSession::open_multi_streams(&mixed, &segs).err(), |
| 263 | ] | 264 | ] |
| 264 | - .map(|e| e.expect("a source with no audio track must be refused")) | 265 | + .map(|e| e.expect("a source at another rate must be refused")) |
| 265 | { | 266 | { |
| 266 | let msg = e.to_string(); | 267 | let msg = e.to_string(); |
| 267 | assert!(msg.contains("source 1"), "{msg}"); | 268 | assert!(msg.contains("source 1"), "{msg}"); |
| @@ -270,3 +271,62 @@ fn a_source_without_the_timeline_audio_is_refused() { | |||
| 270 | assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); | 271 | assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); |
| 271 | assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); | 272 | assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); |
| 272 | } | 273 | } |
| 274 | + | ||
| 275 | +/// A source with **no** track is not a refusal at all: its segments are the | ||
| 276 | +/// same silence a gap is, in both paths. That is what a silent clip on an audio | ||
| 277 | +/// lane is -- a picture over a hole -- and the timeline lets one in | ||
| 278 | +/// (`PlaybackSession::import`) precisely because these two agree here. | ||
| 279 | +#[test] | ||
| 280 | +fn a_silent_source_is_silence_and_not_a_refusal() { | ||
| 281 | + let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; | ||
| 282 | + let segs = [ | ||
| 283 | + (Some(0), 0.0, 1.0), | ||
| 284 | + (Some(1), 0.0, 1.0), | ||
| 285 | + (Some(0), 0.0, 1.0), | ||
| 286 | + ]; | ||
| 287 | + | ||
| 288 | + // Decoded: three seconds, the middle one exact zero, and the chunks still | ||
| 289 | + // arrive contiguous (`drain` asserts that), so the clock is fed through it. | ||
| 290 | + let (_, rx) = AudioSession::open_multi_segments(&mixed, &segs) | ||
| 291 | + .expect("a silent source opens") | ||
| 292 | + .expect("the first source has an audio track"); | ||
| 293 | + let (samples, _, _) = drain(rx); | ||
| 294 | + let frames = samples.len() / CHANNELS; | ||
| 295 | + assert!( | ||
| 296 | + (frames as i64 - 3 * RATE as i64).unsigned_abs() < PACKET, | ||
| 297 | + "{frames} frames for three seconds" | ||
| 298 | + ); | ||
| 299 | + let second = |n: usize| { | ||
| 300 | + let at = |s: usize| (s * RATE as usize * CHANNELS).min(samples.len()); | ||
| 301 | + &samples[at(n)..at(n + 1)] | ||
| 302 | + }; | ||
| 303 | + assert!( | ||
| 304 | + second(0).iter().any(|s| *s != 0.0), | ||
| 305 | + "the first second plays" | ||
| 306 | + ); | ||
| 307 | + assert!( | ||
| 308 | + second(1).iter().all(|s| *s == 0.0), | ||
| 309 | + "the silent source is exact silence" | ||
| 310 | + ); | ||
| 311 | + assert!(second(2).iter().any(|s| *s != 0.0), "and it comes back"); | ||
| 312 | + | ||
| 313 | + // Copied: the same shape in packets, so an mp4 export of that timeline is | ||
| 314 | + // as long as the timeline and quiet where the silent clip is. | ||
| 315 | + let (params, packets) = AudioSession::copy_multi_segments(&mixed, &segs) | ||
| 316 | + .expect("a silent source copies") | ||
| 317 | + .expect("the timeline has an audible source"); | ||
| 318 | + let copied = packets.len() as u64 * PACKET; | ||
| 319 | + assert!( | ||
| 320 | + (copied as i64 - 3 * RATE as i64).unsigned_abs() < 2 * PACKET, | ||
| 321 | + "{copied} samples for three seconds, priming included" | ||
| 322 | + ); | ||
| 323 | + assert_eq!( | ||
| 324 | + params.sample_rate, RATE as u32, | ||
| 325 | + "the audible source's track" | ||
| 326 | + ); | ||
| 327 | + let silence: Vec<_> = packets[44..44 + 43].iter().map(|p| &p.bytes).collect(); | ||
| 328 | + assert!( | ||
| 329 | + silence.iter().all(|b| b.len() <= 7), | ||
| 330 | + "the hole is written as the hand-made silent packet, not as audio" | ||
| 331 | + ); | ||
| 332 | +} | ||
crates/engine/tests/av1.rsmodified+64 -6
| @@ -57,6 +57,23 @@ fn the_demuxer_reports_an_av1_track_in_matroska() { | |||
| 57 | assert_eq!(vp9.codec, Codec::Vp9); | 57 | assert_eq!(vp9.codec, Codec::Vp9); |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | +/// The depth, which is what picks the surface pool the plugin decodes into: an | ||
| 61 | +/// `av1C` with `high_bitdepth` set reads as 10 and takes the P010 pool HEVC Main | ||
| 62 | +/// 10 already goes through, and the 8-bit fixture beside it still reads as 8. | ||
| 63 | +/// It used to be an outright refusal at open ("10-bit AV1 is not supported"). | ||
| 64 | +#[test] | ||
| 65 | +fn a_ten_bit_av1_track_is_read_as_ten_bit() { | ||
| 66 | + let (meta, ten) = Demuxer::open(&asset("test_av1_10.mkv")).expect("open test_av1_10.mkv"); | ||
| 67 | + assert_eq!(meta.codec, Codec::Av1); | ||
| 68 | + assert_eq!((meta.width, meta.height), (1280, 720)); | ||
| 69 | + assert_eq!(meta.frame_count, FRAMES); | ||
| 70 | + assert_eq!(ten.bit_depth(), 10, "what picks the P010 surface pool"); | ||
| 71 | + | ||
| 72 | + // The invariant: the 8-bit file is untouched by any of it. | ||
| 73 | + let (_, eight) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); | ||
| 74 | + assert_eq!(eight.bit_depth(), 8); | ||
| 75 | +} | ||
| 76 | + | ||
| 60 | /// The delivered audio scope, as an assert: a Matroska file's AAC track is read | 77 | /// The delivered audio scope, as an assert: a Matroska file's AAC track is read |
| 61 | /// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its | 78 | /// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its |
| 62 | /// *picture* being AV1 changes nothing about it. | 79 | /// *picture* being AV1 changes nothing about it. |
| @@ -138,17 +155,27 @@ fn the_software_path_refuses_av1_by_name() { | |||
| 138 | assert!(refused.contains("plugin"), "{refused}"); | 155 | assert!(refused.contains("plugin"), "{refused}"); |
| 139 | } | 156 | } |
| 140 | 157 | ||
| 141 | -/// A timeline is refused a source coded differently, in the same words a | 158 | +/// A timeline is *not* refused a source coded differently -- every clip opens |
| 142 | -/// resolution mismatch is refused in: a front-end shows the string as it is. | 159 | +/// its own decoder. What survives is the reason the codec gate existed: on a |
| 160 | +/// machine that cannot decode AV1 the file is refused at the door, by the | ||
| 161 | +/// decoder's own name, rather than becoming a clip of black frames. | ||
| 143 | #[test] | 162 | #[test] |
| 144 | -fn a_timeline_refuses_the_other_codec() { | 163 | +fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { |
| 145 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); | 164 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); |
| 165 | + // The no-plugin machine, forced. | ||
| 166 | + // SAFETY: the suite is documented to run with --test-threads=1. | ||
| 167 | + unsafe { std::env::set_var("VE_SW", "1") }; | ||
| 146 | let refused = session | 168 | let refused = session |
| 147 | .import(&asset("test_av1.mkv")) | 169 | .import(&asset("test_av1.mkv")) |
| 148 | - .expect_err("AV1 must not join an H.264 timeline") | 170 | + .expect_err("no AV1 decoder means no AV1 clip") |
| 149 | .to_string(); | 171 | .to_string(); |
| 150 | - assert!(refused.contains("AV1"), "{refused}"); | 172 | + unsafe { std::env::remove_var("VE_SW") }; |
| 151 | - assert!(refused.contains("H.264"), "{refused}"); | 173 | + assert_eq!(refused, Codec::Av1.needs_plugin()); |
| 174 | + assert!( | ||
| 175 | + !refused.contains("H.264"), | ||
| 176 | + "the timeline's own codec is no longer a reason: {refused}" | ||
| 177 | + ); | ||
| 178 | + assert_eq!(session.sources().len(), 1, "a refusal left no row"); | ||
| 152 | } | 179 | } |
| 153 | 180 | ||
| 154 | /// The end-to-end user path: opening the file yields pictures, all of them, | 181 | /// The end-to-end user path: opening the file yields pictures, all of them, |
| @@ -181,6 +208,37 @@ fn the_plugin_decodes_every_av1_frame() { | |||
| 181 | ); | 208 | ); |
| 182 | } | 209 | } |
| 183 | 210 | ||
| 211 | +/// ...and the 10-bit file through the very call the window's open door makes: a | ||
| 212 | +/// user opens it and the timeline shows a picture, read back off the P010 pool | ||
| 213 | +/// to the same 8-bit BGRA every other frame arrives in. The whole point of the | ||
| 214 | +/// slice, and the half a container test cannot say anything about. | ||
| 215 | +#[test] | ||
| 216 | +#[ignore = "needs libengine_hw.so and a VA-API driver with 10-bit AV1 decode"] | ||
| 217 | +fn opening_a_ten_bit_av1_file_shows_frames() { | ||
| 218 | + let mut session = | ||
| 219 | + PlaybackSession::open(asset("test_av1_10.mkv")).expect("open the 10-bit file"); | ||
| 220 | + assert_eq!(session.meta().codec, Codec::Av1); | ||
| 221 | + assert_eq!(session.meta().frame_count, FRAMES); | ||
| 222 | + | ||
| 223 | + // The decoder is a thread behind the door, so a frame is waited for exactly | ||
| 224 | + // as the window's own pump waits for one. | ||
| 225 | + let deadline = Instant::now() + Duration::from_secs(60); | ||
| 226 | + let frame = loop { | ||
| 227 | + if let Some(frame) = session.try_frame() { | ||
| 228 | + break frame; | ||
| 229 | + } | ||
| 230 | + assert!(Instant::now() < deadline, "no frame in 60 s"); | ||
| 231 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 232 | + }; | ||
| 233 | + assert_eq!((frame.width, frame.height), (1280, 720)); | ||
| 234 | + // A picture, not a flat surface: a P010 surface read back through the NV12 | ||
| 235 | + // path would come out as noise or as nothing at all. | ||
| 236 | + assert!( | ||
| 237 | + frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]), | ||
| 238 | + "the first frame is a single colour -- no picture was decoded" | ||
| 239 | + ); | ||
| 240 | +} | ||
| 241 | + | ||
| 184 | /// A seek into the second GOP hands back that very frame, not the keyframe it | 242 | /// A seek into the second GOP hands back that very frame, not the keyframe it |
| 185 | /// had to restart from: the demuxer's sync index and the plugin's skip count | 243 | /// had to restart from: the demuxer's sync index and the plugin's skip count |
| 186 | /// have to agree, and Matroska is where both are this crate's own doing. | 244 | /// have to agree, and Matroska is where both are this crate's own doing. |
crates/engine/tests/data/test_subs.assadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +[Script Info] | ||
| 2 | +ScriptType: v4.00+ | ||
| 3 | +PlayResX: 384 | ||
| 4 | +PlayResY: 288 | ||
| 5 | + | ||
| 6 | +[V4+ Styles] | ||
| 7 | +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding | ||
| 8 | +Style: Default,Arial,16,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1 | ||
| 9 | + | ||
| 10 | +[Events] | ||
| 11 | +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text | ||
| 12 | +Dialogue: 0,0:00:00.50,0:00:01.50,Default,,0,0,0,,first line | ||
| 13 | +Dialogue: 0,0:00:02.00,0:00:03.25,Default,,0,0,0,,second line\Nwith a break | ||
| 14 | +Dialogue: 0,0:00:04.00,0:00:04.75,Default,,0,0,0,,{\i1}third{\i0} line | ||
crates/engine/tests/data/test_subs.srtadded+12 -0
| @@ -0,0 +1,12 @@ | |||
| 1 | +1 | ||
| 2 | +00:00:00,500 --> 00:00:01,500 | ||
| 3 | +first line | ||
| 4 | + | ||
| 5 | +2 | ||
| 6 | +00:00:02,000 --> 00:00:03,250 | ||
| 7 | +second line | ||
| 8 | +with a break | ||
| 9 | + | ||
| 10 | +3 | ||
| 11 | +00:00:04,000 --> 00:00:04,750 | ||
| 12 | +third line | ||
crates/engine/tests/h264_mkv.rsadded+149 -0
| @@ -0,0 +1,149 @@ | |||
| 1 | +//! H.264 in Matroska: the codec this project has always decoded, in the | ||
| 2 | +//! container that used to refuse it by name. Nothing new decodes here -- the | ||
| 3 | +//! demuxer reframes the `avcC`-prefixed blocks to Annex-B and hands them to the | ||
| 4 | +//! same dispatch an mp4's samples go to -- so the whole file runs with nothing | ||
| 5 | +//! installed, on `rusty_h264` if the plugin is absent. | ||
| 6 | +//! | ||
| 7 | +//! ```text | ||
| 8 | +//! cargo test -p engine --test h264_mkv | ||
| 9 | +//! ``` | ||
| 10 | + | ||
| 11 | +use std::path::PathBuf; | ||
| 12 | +use std::time::{Duration, Instant}; | ||
| 13 | + | ||
| 14 | +use engine::demux::{Codec, Demuxer}; | ||
| 15 | +use engine::{AudioSession, PlaybackSession}; | ||
| 16 | + | ||
| 17 | +/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`. | ||
| 18 | +const FRAMES: u32 = 60; | ||
| 19 | +const KEYFRAME: u32 = 30; | ||
| 20 | + | ||
| 21 | +fn asset(name: &str) -> PathBuf { | ||
| 22 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 23 | + .join("../../assets") | ||
| 24 | + .join(name) | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// The Annex-B NAL types of an access unit, in order: `nal_unit_type` is the low | ||
| 28 | +/// 5 bits of the byte after each start code. | ||
| 29 | +fn nal_types(au: &[u8]) -> Vec<u8> { | ||
| 30 | + au.windows(4) | ||
| 31 | + .enumerate() | ||
| 32 | + .filter(|(_, w)| *w == [0, 0, 0, 1]) | ||
| 33 | + .filter_map(|(i, _)| au.get(i + 4).map(|b| b & 0x1f)) | ||
| 34 | + .collect() | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// The container half, and the refusal this slice exists to delete: the file | ||
| 38 | +/// opens, and it says H.264 rather than "not supported". | ||
| 39 | +#[test] | ||
| 40 | +fn the_demuxer_reports_an_h264_track_in_matroska() { | ||
| 41 | + let (meta, _) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); | ||
| 42 | + assert_eq!(meta.codec, Codec::H264); | ||
| 43 | + assert_eq!((meta.width, meta.height), (1280, 720)); | ||
| 44 | + assert!( | ||
| 45 | + (meta.frame_rate - 30.0).abs() < 1e-6, | ||
| 46 | + "DefaultDuration must not truncate: {}", | ||
| 47 | + meta.frame_rate | ||
| 48 | + ); | ||
| 49 | + assert_eq!(meta.frame_count, FRAMES); | ||
| 50 | + | ||
| 51 | + // The invariant, stated as an assert: the other containers and codecs read | ||
| 52 | + // back exactly as they did before this arm existed. | ||
| 53 | + let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); | ||
| 54 | + assert_eq!(av1.codec, Codec::Av1); | ||
| 55 | + assert_eq!(av1.frame_count, FRAMES); | ||
| 56 | + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); | ||
| 57 | + assert_eq!(h264.codec, Codec::H264); | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// Matroska stores H.264 in `avcC` framing -- length prefixes, and the SPS/PPS | ||
| 61 | +/// out of band in `CodecPrivate` -- so an access unit is only decodable if both | ||
| 62 | +/// were handled: reframed to Annex-B, parameter sets ahead of every keyframe. | ||
| 63 | +#[test] | ||
| 64 | +fn keyframes_carry_the_parameter_sets_and_every_block_comes_back() { | ||
| 65 | + let (_, mut demuxer) = Demuxer::open(&asset("test_h264.mkv")).expect("open test_h264.mkv"); | ||
| 66 | + let first = demuxer | ||
| 67 | + .next_access_unit() | ||
| 68 | + .expect("read") | ||
| 69 | + .expect("a first access unit"); | ||
| 70 | + assert_eq!(first[..4], [0, 0, 0, 1], "Annex-B, not a length prefix"); | ||
| 71 | + let types = nal_types(&first); | ||
| 72 | + assert_eq!( | ||
| 73 | + &types[..2], | ||
| 74 | + &[7, 8], | ||
| 75 | + "the keyframe leads with SPS and PPS: {types:?}" | ||
| 76 | + ); | ||
| 77 | + assert!(types.contains(&5), "and then the IDR picture: {types:?}"); | ||
| 78 | + | ||
| 79 | + let second = demuxer.next_access_unit().expect("read").expect("a unit"); | ||
| 80 | + let types = nal_types(&second); | ||
| 81 | + assert!( | ||
| 82 | + !types.contains(&7) && types.contains(&1), | ||
| 83 | + "a non-keyframe is a plain slice: {types:?}" | ||
| 84 | + ); | ||
| 85 | + | ||
| 86 | + let mut count = 2; | ||
| 87 | + while demuxer.next_access_unit().expect("read").is_some() { | ||
| 88 | + count += 1; | ||
| 89 | + } | ||
| 90 | + assert_eq!(count, FRAMES, "every block came back out"); | ||
| 91 | + | ||
| 92 | + // Keyed every 30 frames, and a seek may only land on one. | ||
| 93 | + assert_eq!( | ||
| 94 | + demuxer.seek_to_sync_at_or_before(KEYFRAME + 15), | ||
| 95 | + i64::from(KEYFRAME) | ||
| 96 | + ); | ||
| 97 | + assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0); | ||
| 98 | + // The unit after a seek carries the parameter sets too: a decoder restarted | ||
| 99 | + // mid-file needs them exactly as much as one started at frame 0. | ||
| 100 | + let after = demuxer.next_access_unit().expect("read").expect("a unit"); | ||
| 101 | + assert_eq!(&nal_types(&after)[..2], &[7, 8]); | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// The user-facing end of it, through the very call the window's open door makes | ||
| 105 | +/// (`app/src/main.rs:2242`): the file becomes a timeline and that timeline shows | ||
| 106 | +/// a picture. No plugin is required -- H.264 is the one codec with a software | ||
| 107 | +/// decoder here -- so this is what says the reframed access units are really | ||
| 108 | +/// decodable and not just well-shaped. | ||
| 109 | +#[test] | ||
| 110 | +fn opening_an_h264_matroska_file_shows_frames() { | ||
| 111 | + let mut session = PlaybackSession::open(asset("test_h264.mkv")).expect("open test_h264.mkv"); | ||
| 112 | + assert_eq!(session.meta().codec, Codec::H264); | ||
| 113 | + assert_eq!(session.meta().frame_count, FRAMES); | ||
| 114 | + | ||
| 115 | + // The decoder is a thread behind the door, so a frame is waited for exactly | ||
| 116 | + // as the window's own pump waits for one. | ||
| 117 | + let deadline = Instant::now() + Duration::from_secs(60); | ||
| 118 | + let frame = loop { | ||
| 119 | + if let Some(frame) = session.try_frame() { | ||
| 120 | + break frame; | ||
| 121 | + } | ||
| 122 | + assert!(Instant::now() < deadline, "no frame in 60 s"); | ||
| 123 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 124 | + }; | ||
| 125 | + assert_eq!((frame.width, frame.height), (1280, 720)); | ||
| 126 | + // A picture, not a flat surface: a decoder handed garbage would satisfy | ||
| 127 | + // every count above. | ||
| 128 | + assert!( | ||
| 129 | + frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]), | ||
| 130 | + "the first frame is a single colour -- no picture was decoded" | ||
| 131 | + ); | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// The sound comes with it: a Matroska file's audio is read whatever its picture | ||
| 135 | +/// is coded with, so nothing is left for the "cannot be decoded" notice to name. | ||
| 136 | +#[test] | ||
| 137 | +fn the_matroska_audio_path_takes_this_file_too() { | ||
| 138 | + let stereo = AudioSession::probe(asset("test_h264.mkv"), 0) | ||
| 139 | + .expect("probe") | ||
| 140 | + .expect("the fixture has an AAC track"); | ||
| 141 | + assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2)); | ||
| 142 | + // ...and it really opens, which is what says the sound plays rather than | ||
| 143 | + // merely being described. | ||
| 144 | + assert!( | ||
| 145 | + AudioSession::open(asset("test_h264.mkv")) | ||
| 146 | + .expect("open") | ||
| 147 | + .is_some() | ||
| 148 | + ); | ||
| 149 | +} | ||
crates/engine/tests/hevc.rsmodified+83 -6
| @@ -112,17 +112,35 @@ fn the_software_path_refuses_hevc_by_name() { | |||
| 112 | assert!(h264, "software H.264 decode still opens"); | 112 | assert!(h264, "software H.264 decode still opens"); |
| 113 | } | 113 | } |
| 114 | 114 | ||
| 115 | -/// A timeline is refused a source coded differently, in the same words a | 115 | +/// A timeline is *not* refused a source coded differently -- every clip opens |
| 116 | -/// resolution mismatch is refused in: a front-end shows the string as it is. | 116 | +/// its own decoder, so H.264 and HEVC share one timeline. What survives is the |
| 117 | +/// reason the codec gate existed: on a machine that cannot decode HEVC the file | ||
| 118 | +/// is refused at the door, by the decoder's own name, rather than becoming a | ||
| 119 | +/// clip of black frames with the complaint on stderr. | ||
| 117 | #[test] | 120 | #[test] |
| 118 | -fn a_timeline_refuses_the_other_codec() { | 121 | +fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { |
| 119 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); | 122 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); |
| 123 | + // The no-plugin machine, forced: the refusal must still arrive, and it must | ||
| 124 | + // be the decoder's words and not the timeline's. | ||
| 125 | + // SAFETY: the suite is documented to run with --test-threads=1. | ||
| 126 | + unsafe { std::env::set_var("VE_SW", "1") }; | ||
| 120 | let refused = session | 127 | let refused = session |
| 121 | .import(&asset("test_hevc.mp4")) | 128 | .import(&asset("test_hevc.mp4")) |
| 122 | - .expect_err("HEVC must not join an H.264 timeline") | 129 | + .expect_err("no HEVC decoder means no HEVC clip") |
| 123 | .to_string(); | 130 | .to_string(); |
| 124 | - assert!(refused.contains("HEVC"), "{refused}"); | 131 | + unsafe { std::env::remove_var("VE_SW") }; |
| 125 | - assert!(refused.contains("H.264"), "{refused}"); | 132 | + assert_eq!(refused, Codec::Hevc.needs_plugin()); |
| 133 | + assert!( | ||
| 134 | + !refused.contains("H.264"), | ||
| 135 | + "the timeline's own codec is no longer a reason: {refused}" | ||
| 136 | + ); | ||
| 137 | + assert_eq!(session.sources().len(), 1, "a refusal left no row"); | ||
| 138 | + | ||
| 139 | + // ...and where a decoder exists, it simply joins. | ||
| 140 | + match session.import(&asset("test_hevc.mp4")) { | ||
| 141 | + Ok(_) => assert_eq!(session.sources().len(), 2, "HEVC beside H.264"), | ||
| 142 | + Err(e) => assert_eq!(e.to_string(), Codec::Hevc.needs_plugin()), | ||
| 143 | + } | ||
| 126 | } | 144 | } |
| 127 | 145 | ||
| 128 | /// The end-to-end user path: opening the file yields pictures, all of them, | 146 | /// The end-to-end user path: opening the file yields pictures, all of them, |
| @@ -155,6 +173,65 @@ fn the_plugin_decodes_every_hevc_frame() { | |||
| 155 | ); | 173 | ); |
| 156 | } | 174 | } |
| 157 | 175 | ||
| 176 | +/// The mixed-codec timeline, end to end: an H.264 take joins an HEVC one, both | ||
| 177 | +/// spans really decode (a decoder each, opened at the span), and the export -- | ||
| 178 | +/// which re-encodes -- writes every frame of both. The refusal that used to | ||
| 179 | +/// stand here would have made this whole timeline impossible. | ||
| 180 | +#[test] | ||
| 181 | +#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"] | ||
| 182 | +fn an_h264_take_plays_and_exports_on_an_hevc_timeline() { | ||
| 183 | + let hevc = asset("test_hevc.mp4"); | ||
| 184 | + let h264 = asset("test_av.mp4"); | ||
| 185 | + let mut session = PlaybackSession::open(&hevc).expect("open test_hevc.mp4"); | ||
| 186 | + session.set_gain(0.0); | ||
| 187 | + session.import(&h264).expect("H.264 joins an HEVC timeline"); | ||
| 188 | + let end = session.timeline_duration(); | ||
| 189 | + assert!( | ||
| 190 | + session | ||
| 191 | + .place_stream_at(end, &h264, 0, None) | ||
| 192 | + .expect("a file just imported is on this timeline"), | ||
| 193 | + "drag it onto the end" | ||
| 194 | + ); | ||
| 195 | + assert_eq!(session.clip_spans().len(), 2, "two takes, two codecs"); | ||
| 196 | + | ||
| 197 | + // One picture out of each span, which is one decoder each: the HEVC clip | ||
| 198 | + // through the plugin, the H.264 one through either backend. | ||
| 199 | + for (at, what) in [(1.0, "the HEVC take"), (end + 1.0, "the H.264 take")] { | ||
| 200 | + session.seek(at); | ||
| 201 | + let deadline = Instant::now() + Duration::from_secs(10); | ||
| 202 | + let frame = loop { | ||
| 203 | + if let Some(frame) = session.try_frame() { | ||
| 204 | + break frame; | ||
| 205 | + } | ||
| 206 | + assert!(Instant::now() < deadline, "no frame from {what}"); | ||
| 207 | + std::thread::sleep(Duration::from_millis(4)); | ||
| 208 | + }; | ||
| 209 | + assert_eq!( | ||
| 210 | + (frame.width, frame.height), | ||
| 211 | + session.resolution(), | ||
| 212 | + "{what} came out at the project size" | ||
| 213 | + ); | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + // ...and the export -- the one a front-end starts, off the session itself -- | ||
| 217 | + // re-encodes both to one H.264 track. | ||
| 218 | + let frames = | ||
| 219 | + (session.timeline_duration() * f64::from(session.meta().frame_rate as f32)).round() as u32; | ||
| 220 | + let out = std::env::temp_dir().join(format!("ve_export_mixed_{}.mp4", std::process::id())); | ||
| 221 | + let _ = std::fs::remove_file(&out); | ||
| 222 | + let handle = session.export_to_with(&out, &ExportSettings::default()); | ||
| 223 | + let started = Instant::now(); | ||
| 224 | + while !handle.is_finished() { | ||
| 225 | + assert!(started.elapsed() < Duration::from_secs(240), "export hung"); | ||
| 226 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 227 | + } | ||
| 228 | + handle.result().expect("outcome").expect("the mixed export"); | ||
| 229 | + let (written, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 230 | + assert_eq!(written.codec, Codec::H264, "exports are always H.264"); | ||
| 231 | + assert_eq!(written.frame_count, frames, "both takes were written"); | ||
| 232 | + let _ = std::fs::remove_file(&out); | ||
| 233 | +} | ||
| 234 | + | ||
| 158 | /// Export re-encodes to H.264 whatever the source was coded with: the packet | 235 | /// Export re-encodes to H.264 whatever the source was coded with: the packet |
| 159 | /// copy path is audio-only, so no HEVC byte can reach an `avc1` track. | 236 | /// copy path is audio-only, so no HEVC byte can reach an `avc1` track. |
| 160 | #[test] | 237 | #[test] |
crates/engine/tests/lanes.rsmodified+9 -4
| @@ -52,8 +52,13 @@ fn out_path(name: &str, ext: &str) -> PathBuf { | |||
| 52 | /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle | 52 | /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle |
| 53 | /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`. | 53 | /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`. |
| 54 | /// Exactly the file a user would write by hand, parsed by the real loader. | 54 | /// Exactly the file a user would write by hand, parsed by the real loader. |
| 55 | -fn three_lane_file() -> PathBuf { | 55 | +/// |
| 56 | - let path = out_path("project", "edith"); | 56 | +/// `name` is the caller's own, because [`out_path`] is unique per *run* and not |
| 57 | +/// per test: two tests sharing one name run in parallel over one file, and the | ||
| 58 | +/// first to finish deletes it out from under the second -- which then fails on | ||
| 59 | +/// a file that is simply not there any more. | ||
| 60 | +fn three_lane_file(name: &str) -> PathBuf { | ||
| 61 | + let path = out_path(name, "edith"); | ||
| 57 | // `source <audio stream> <path>`: the number is which audio track of the | 62 | // `source <audio stream> <path>`: the number is which audio track of the |
| 58 | // file plays, not the source index -- both of these are on their first. | 63 | // file plays, not the source index -- both of these are on their first. |
| 59 | let text = format!( | 64 | let text = format!( |
| @@ -143,7 +148,7 @@ fn frame_of(session: &mut PlaybackSession, timeline: u32) -> Vec<u8> { | |||
| 143 | #[test] | 148 | #[test] |
| 144 | fn playback_shows_the_topmost_video_lane() { | 149 | fn playback_shows_the_topmost_video_lane() { |
| 145 | pin_software(); | 150 | pin_software(); |
| 146 | - let project = three_lane_file(); | 151 | + let project = three_lane_file("playback"); |
| 147 | let mut session = PlaybackSession::open_project(&project).expect("open the project"); | 152 | let mut session = PlaybackSession::open_project(&project).expect("open the project"); |
| 148 | session.set_gain(0.0); | 153 | session.set_gain(0.0); |
| 149 | assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS); | 154 | assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS); |
| @@ -164,7 +169,7 @@ fn playback_shows_the_topmost_video_lane() { | |||
| 164 | #[test] | 169 | #[test] |
| 165 | fn export_writes_the_same_composite() { | 170 | fn export_writes_the_same_composite() { |
| 166 | pin_software(); | 171 | pin_software(); |
| 167 | - let file = three_lane_file(); | 172 | + let file = three_lane_file("export"); |
| 168 | let session = PlaybackSession::open_project(&file).expect("open the project"); | 173 | let session = PlaybackSession::open_project(&file).expect("open the project"); |
| 169 | let out = out_path("composite", "mp4"); | 174 | let out = out_path("composite", "mp4"); |
| 170 | 175 | ||
crates/engine/tests/playback.rsmodified+60 -25
| @@ -13,7 +13,7 @@ use std::time::{Duration, Instant}; | |||
| 13 | 13 | ||
| 14 | use engine::export::{ExportSettings, Format}; | 14 | use engine::export::{ExportSettings, Format}; |
| 15 | use engine::project::Lane; | 15 | use engine::project::Lane; |
| 16 | -use engine::{DecodeSession, Frame, PlaybackSession}; | 16 | +use engine::{Codec, DecodeSession, Frame, PlaybackSession}; |
| 17 | 17 | ||
| 18 | fn asset(name: &str) -> PathBuf { | 18 | fn asset(name: &str) -> PathBuf { |
| 19 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) | 19 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| @@ -788,30 +788,31 @@ fn the_first_import_opens_a_library_over_an_empty_timeline() { | |||
| 788 | assert_eq!(session.sources().len(), 1, "the row survives the undo"); | 788 | assert_eq!(session.sources().len(), 1, "the row survives the undo"); |
| 789 | } | 789 | } |
| 790 | 790 | ||
| 791 | -/// One timeline, one set of parameters: everything else is refused by name and | 791 | +/// One timeline, one frame rate and one set of audio parameters: what is left |
| 792 | -/// changes nothing. | 792 | +/// is refused by name and changes nothing. |
| 793 | #[test] | 793 | #[test] |
| 794 | fn import_refuses_what_does_not_match() { | 794 | fn import_refuses_what_does_not_match() { |
| 795 | let mut session = open(asset("test_av.mp4")); | 795 | let mut session = open(asset("test_av.mp4")); |
| 796 | 796 | ||
| 797 | - // A different *codec* cannot join: one timeline is one kind of source. | 797 | + // A different *codec* is not among them any more -- every clip opens its |
| 798 | - let err = session | 798 | + // own decoder. The only refusal left on that axis is a decoder this machine |
| 799 | - .import(&asset("test_vp9.mp4")) | 799 | + // cannot open, and it is the plugin's own words, not the timeline's. |
| 800 | - .expect_err("VP9 must be refused") | 800 | + match session.import(&asset("test_vp9.mp4")) { |
| 801 | - .to_string(); | 801 | + Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"), |
| 802 | - assert!(err.contains("VP9"), "refusal must name the codec: {err}"); | 802 | + Err(e) => assert_eq!( |
| 803 | + e.to_string(), | ||
| 804 | + Codec::Vp9.needs_plugin(), | ||
| 805 | + "the only codec refusal left is the missing decoder" | ||
| 806 | + ), | ||
| 807 | + } | ||
| 808 | + let rows = session.sources().len(); | ||
| 803 | 809 | ||
| 804 | // A different resolution is no longer among the refusals -- it is placed on | 810 | // A different resolution is no longer among the refusals -- it is placed on |
| 805 | - // the project canvas instead -- but this file is also silent, and that is. | 811 | + // the project canvas instead -- and neither is a file with no sound: it |
| 806 | - let err = session | 812 | + // contributes silence over its span. |
| 813 | + session | ||
| 807 | .import(&asset("test_mismatch.mp4")) | 814 | .import(&asset("test_mismatch.mp4")) |
| 808 | - .expect_err("a silent file must be refused") | 815 | + .expect("a silent 640x360 file joins a timeline with sound"); |
| 809 | - .to_string(); | ||
| 810 | - assert!(err.contains("audio"), "refusal must name the audio: {err}"); | ||
| 811 | - assert!( | ||
| 812 | - !err.contains("640x360"), | ||
| 813 | - "a resolution of its own is not a refusal any more: {err}" | ||
| 814 | - ); | ||
| 815 | 816 | ||
| 816 | // A frame rate of its own is no longer a refusal either: 25 fps joins a | 817 | // A frame rate of its own is no longer a refusal either: 25 fps joins a |
| 817 | // 30 fps timeline and is read at `Rate` against it -- see | 818 | // 30 fps timeline and is read at `Rate` against it -- see |
| @@ -823,22 +824,32 @@ fn import_refuses_what_does_not_match() { | |||
| 823 | .remove_source(&asset("test_25fps.mp4"), 0) | 824 | .remove_source(&asset("test_25fps.mp4"), 0) |
| 824 | .expect("...and the row it made comes back off"); | 825 | .expect("...and the row it made comes back off"); |
| 825 | 826 | ||
| 826 | - // Same size and rate, no audio track: the timeline has one. | 827 | + // What is still refused, and all that is: one output device means one rate |
| 828 | + // and one layout, and there is no resampler to make two into one. | ||
| 827 | let err = session | 829 | let err = session |
| 828 | - .import(&asset("test_baseline.mp4")) | 830 | + .import(&asset("test_ac3.mp4")) |
| 829 | - .expect_err("a silent file must be refused") | 831 | + .expect_err("a mono track cannot join a stereo timeline") |
| 830 | .to_string(); | 832 | .to_string(); |
| 831 | - assert!(err.contains("audio"), "refusal must name the audio: {err}"); | 833 | + assert_eq!( |
| 834 | + err, | ||
| 835 | + "audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch" | ||
| 836 | + ); | ||
| 832 | 837 | ||
| 833 | assert!( | 838 | assert!( |
| 834 | session.import(&asset("no_such_file.mp4")).is_err(), | 839 | session.import(&asset("no_such_file.mp4")).is_err(), |
| 835 | "a missing file is an error, not a panic" | 840 | "a missing file is an error, not a panic" |
| 836 | ); | 841 | ); |
| 837 | - assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing"); | 842 | + assert_eq!(session.clip_spans().len(), 1, "an import places nothing"); |
| 838 | - assert_eq!(session.sources().len(), 1, "a refusal left a library row"); | 843 | + assert_eq!( |
| 844 | + session.sources().len(), | ||
| 845 | + rows + 1, | ||
| 846 | + "only the silent file was taken in" | ||
| 847 | + ); | ||
| 839 | assert!((session.timeline_duration() - 5.0).abs() < 1e-9); | 848 | assert!((session.timeline_duration() - 5.0).abs() < 1e-9); |
| 840 | 849 | ||
| 841 | - // The mirror: audio into a silent timeline is refused just as loudly. | 850 | + // The mirror is still refused: the device was opened on source 0's track |
| 851 | + // and a silent timeline has none to open, so a file with sound cannot be | ||
| 852 | + // heard on one. | ||
| 842 | let mut silent = open(asset("test_baseline.mp4")); | 853 | let mut silent = open(asset("test_baseline.mp4")); |
| 843 | let err = silent | 854 | let err = silent |
| 844 | .import(&asset("test_av.mp4")) | 855 | .import(&asset("test_av.mp4")) |
| @@ -847,6 +858,30 @@ fn import_refuses_what_does_not_match() { | |||
| 847 | assert!(err.contains("audio"), "refusal must name the audio: {err}"); | 858 | assert!(err.contains("audio"), "refusal must name the audio: {err}"); |
| 848 | } | 859 | } |
| 849 | 860 | ||
| 861 | +/// The user path a silent take goes down: a file with no audio track lands on a | ||
| 862 | +/// timeline that has one, is placed as the grouped take every video file is, | ||
| 863 | +/// and plays -- pictures over its span, silence under them. The sound itself is | ||
| 864 | +/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is | ||
| 865 | +/// that nothing about the *timeline* is refused or lost. | ||
| 866 | +#[test] | ||
| 867 | +fn a_silent_file_joins_a_timeline_with_sound_and_plays() { | ||
| 868 | + let mut session = open(asset("test_av.mp4")); | ||
| 869 | + import_and_place(&mut session, &asset("test_mismatch.mp4")); | ||
| 870 | + // 150 frames of test_av, then 60 of the silent file, at 30 fps. | ||
| 871 | + assert_eq!(session.clip_spans().len(), 2, "the silent take landed"); | ||
| 872 | + assert!((session.timeline_duration() - 7.0).abs() < 1e-9); | ||
| 873 | + // Both lanes carry it: a silent file is a normal grouped take, and its | ||
| 874 | + // audio clip is the span the worker fills with silence. | ||
| 875 | + assert_eq!(session.lane_clips(Lane::V1).len(), 2); | ||
| 876 | + assert_eq!(session.lane_clips(Lane::A1).len(), 2); | ||
| 877 | + | ||
| 878 | + // ...and it decodes: a picture from inside the silent clip's span, at the | ||
| 879 | + // project's resolution like every other clip. | ||
| 880 | + session.seek(6.0); | ||
| 881 | + let frame = next_frame(&mut session, "the silent clip"); | ||
| 882 | + assert_eq!((frame.width, frame.height), session.resolution()); | ||
| 883 | +} | ||
| 884 | + | ||
| 850 | /// The user-facing point of a project resolution: media of two sizes on one | 885 | /// The user-facing point of a project resolution: media of two sizes on one |
| 851 | /// timeline, each composed onto the project's own canvas. | 886 | /// timeline, each composed onto the project's own canvas. |
| 852 | /// | 887 | /// |
crates/engine/tests/saveload.rsmodified+14 -11
| @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { | |||
| 209 | let v2 = dir.join("new.edith"); | 209 | let v2 = dir.join("new.edith"); |
| 210 | loaded.save_project(&v2).expect("save"); | 210 | loaded.save_project(&v2).expect("save"); |
| 211 | let text = std::fs::read_to_string(&v2).expect("read back"); | 211 | let text = std::fs::read_to_string(&v2).expect("read back"); |
| 212 | - assert!(text.starts_with("edith 9\n"), "{text}"); | 212 | + assert!(text.starts_with("edith 10\n"), "{text}"); |
| 213 | assert!( | 213 | assert!( |
| 214 | text.contains("\nresolution 1280 720\n"), | 214 | text.contains("\nresolution 1280 720\n"), |
| 215 | "a project with no resolution of its own is saved at source 0's: {text}" | 215 | "a project with no resolution of its own is saved at source 0's: {text}" |
| @@ -297,7 +297,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { | |||
| 297 | loaded.save_project(&again).expect("save"); | 297 | loaded.save_project(&again).expect("save"); |
| 298 | assert_eq!( | 298 | assert_eq!( |
| 299 | std::fs::read_to_string(&again).expect("read back"), | 299 | std::fs::read_to_string(&again).expect("read back"), |
| 300 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 300 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ | 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ |
| 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", | 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", |
| 303 | "a four-lane project is written as it was read, three versions on" | 303 | "a four-lane project is written as it was read, three versions on" |
| @@ -327,7 +327,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { | |||
| 327 | loaded.save_project(&again).expect("save"); | 327 | loaded.save_project(&again).expect("save"); |
| 328 | assert_eq!( | 328 | assert_eq!( |
| 329 | std::fs::read_to_string(&again).expect("read back"), | 329 | std::fs::read_to_string(&again).expect("read back"), |
| 330 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 330 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 332 | eq 12000.0:6.25:0.5:hs\n\ | 332 | eq 12000.0:6.25:0.5:hs\n\ |
| 333 | video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ | 333 | video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ |
| @@ -362,7 +362,7 @@ fn a_version_6_project_carries_per_clip_colours() { | |||
| 362 | loaded.save_project(&again).expect("save"); | 362 | loaded.save_project(&again).expect("save"); |
| 363 | assert_eq!( | 363 | assert_eq!( |
| 364 | std::fs::read_to_string(&again).expect("read back"), | 364 | std::fs::read_to_string(&again).expect("read back"), |
| 365 | - "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 365 | + "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 366 | eq 80.0:-3.0:0.707:ls\n\ | 366 | eq 80.0:-3.0:0.707:ls\n\ |
| 367 | color 0.1:1.2:0.9:-0.3\n\ | 367 | color 0.1:1.2:0.9:-0.3\n\ |
| 368 | color -0.25:1.0:0.0:0.5\n\ | 368 | color -0.25:1.0:0.0:0.5\n\ |
| @@ -412,7 +412,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { | |||
| 412 | loaded.save_project(&again).expect("save"); | 412 | loaded.save_project(&again).expect("save"); |
| 413 | assert_eq!( | 413 | assert_eq!( |
| 414 | std::fs::read_to_string(&again).expect("read back"), | 414 | std::fs::read_to_string(&again).expect("read back"), |
| 415 | - "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ | 415 | + "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ | 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ |
| 417 | audio 1 0 0 60 0 - - - fit 1000\n", | 417 | audio 1 0 0 60 0 - - - fit 1000\n", |
| 418 | "a v7 project is written back as the v8 it now is: the same clips, each \ | 418 | "a v7 project is written back as the v8 it now is: the same clips, each \ |
| @@ -670,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { | |||
| 670 | 670 | ||
| 671 | for (text, want) in [ | 671 | for (text, want) in [ |
| 672 | ( | 672 | ( |
| 673 | - "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", | 673 | + "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", |
| 674 | "line 1", | 674 | "line 1", |
| 675 | ), | 675 | ), |
| 676 | // An eq index the table does not hold, and a band shape there is none. | 676 | // An eq index the table does not hold, and a band shape there is none. |
| @@ -733,7 +733,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { | |||
| 733 | fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { | 733 | fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { |
| 734 | let dir = scratch("mismatch"); | 734 | let dir = scratch("mismatch"); |
| 735 | copy_in(&dir, "test_av.mp4"); | 735 | copy_in(&dir, "test_av.mp4"); |
| 736 | - std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute"); | 736 | + std::fs::copy(asset("test_ac3.mp4"), dir.join("test_av2.mp4")).expect("substitute"); |
| 737 | let path = dir.join("swapped.edith"); | 737 | let path = dir.join("swapped.edith"); |
| 738 | std::fs::write( | 738 | std::fs::write( |
| 739 | &path, | 739 | &path, |
| @@ -745,12 +745,15 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { | |||
| 745 | .expect("a source that stopped matching must not open") | 745 | .expect("a source that stopped matching must not open") |
| 746 | .to_string(); | 746 | .to_string(); |
| 747 | // The suffix is `import`'s own refusal, word for word. The substitute is | 747 | // The suffix is `import`'s own refusal, word for word. The substitute is |
| 748 | - // 640x360 *and* silent; only the second of those is a refusal now -- a | 748 | + // mono, which is the shape of what is left: one output device means one |
| 749 | - // resolution of its own is placed on the project canvas. | 749 | + // rate and one layout. A resolution of its own is placed on the project |
| 750 | + // canvas, a rate of its own is read through `Rate`, a codec of its own | ||
| 751 | + // opens its own decoder and a file with no sound plays silence -- none of | ||
| 752 | + // those is a refusal any more. | ||
| 750 | assert_eq!( | 753 | assert_eq!( |
| 751 | err, | 754 | err, |
| 752 | format!( | 755 | format!( |
| 753 | - "source {}: the file is silent, the timeline has audio", | 756 | + "source {}: audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch", |
| 754 | dir.join("test_av2.mp4").display() | 757 | dir.join("test_av2.mp4").display() |
| 755 | ) | 758 | ) |
| 756 | ); | 759 | ); |
| @@ -806,7 +809,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() { | |||
| 806 | let path = dir.join("song.edith"); | 809 | let path = dir.join("song.edith"); |
| 807 | std::fs::write( | 810 | std::fs::write( |
| 808 | &path, | 811 | &path, |
| 809 | - "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ | 812 | + "edith 10\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ |
| 810 | video 1\naudio 1 0 0 24 0 - - - fit 1000\n", | 813 | video 1\naudio 1 0 0 24 0 - - - fit 1000\n", |
| 811 | ) | 814 | ) |
| 812 | .expect("write a v9 song project"); | 815 | .expect("write a v9 song project"); |
crates/engine/tests/silence.rsmodified+2 -1
| @@ -365,6 +365,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { | |||
| 365 | &sources, | 365 | &sources, |
| 366 | &lanes, | 366 | &lanes, |
| 367 | &p.lane_gains(), | 367 | &p.lane_gains(), |
| 368 | + p.subtitles(), | ||
| 368 | &eq, | 369 | &eq, |
| 369 | &color, | 370 | &color, |
| 370 | (1920, 1080), | 371 | (1920, 1080), |
| @@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() { | |||
| 375 | .expect("save"); | 376 | .expect("save"); |
| 376 | let text = std::fs::read_to_string(&file).expect("read it back"); | 377 | let text = std::fs::read_to_string(&file).expect("read it back"); |
| 377 | assert!( | 378 | assert!( |
| 378 | - text.starts_with("edith 9"), | 379 | + text.starts_with("edith 10"), |
| 379 | "{:?}", | 380 | "{:?}", |
| 380 | &text[..16.min(text.len())] | 381 | &text[..16.min(text.len())] |
| 381 | ); | 382 | ); |
crates/engine/tests/subtitles.rsadded+237 -0
| @@ -0,0 +1,237 @@ | |||
| 1 | +//! Subtitles: the cues of a file beside the media and of a track inside it are | ||
| 2 | +//! the same cues, a project keeps them across a save, and the formats that are | ||
| 3 | +//! pictures rather than text are listed and skipped by name rather than | ||
| 4 | +//! silently dropped. | ||
| 5 | +//! | ||
| 6 | +//! ```text | ||
| 7 | +//! cargo test -p engine --release --test subtitles -- --nocapture | ||
| 8 | +//! ``` | ||
| 9 | + | ||
| 10 | +use std::path::PathBuf; | ||
| 11 | + | ||
| 12 | +use engine::subtitle::{self, Cue}; | ||
| 13 | + | ||
| 14 | +fn asset(name: &str) -> PathBuf { | ||
| 15 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 16 | + .join("../../assets") | ||
| 17 | + .join(name) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +fn data(name: &str) -> PathBuf { | ||
| 21 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 22 | + .join("tests/data") | ||
| 23 | + .join(name) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +fn scratch(name: &str) -> PathBuf { | ||
| 27 | + let dir = std::env::temp_dir().join(format!("ve_subs_{name}_{}", std::process::id())); | ||
| 28 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 29 | + std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 30 | + std::fs::canonicalize(&dir).expect("canonical scratch dir") | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// The three cues both hand-written fixtures hold, with the markup resolved: | ||
| 34 | +/// the italics of the `.ass` third line are not text, and the `\N` of its | ||
| 35 | +/// second one is a line break like the `.srt`'s. | ||
| 36 | +fn expected() -> Vec<Cue> { | ||
| 37 | + vec![ | ||
| 38 | + Cue { | ||
| 39 | + start_us: 500_000, | ||
| 40 | + end_us: 1_500_000, | ||
| 41 | + text: "first line".into(), | ||
| 42 | + }, | ||
| 43 | + Cue { | ||
| 44 | + start_us: 2_000_000, | ||
| 45 | + end_us: 3_250_000, | ||
| 46 | + text: "second line\nwith a break".into(), | ||
| 47 | + }, | ||
| 48 | + Cue { | ||
| 49 | + start_us: 4_000_000, | ||
| 50 | + end_us: 4_750_000, | ||
| 51 | + text: "third line".into(), | ||
| 52 | + }, | ||
| 53 | + ] | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// The whole of the parse half: four routes to the same three cues -- an | ||
| 57 | +/// `.srt`, an `.ass` with override tags in it, and the two tracks of the | ||
| 58 | +/// Matroska file both were muxed into, whose timing lives on the block and | ||
| 59 | +/// whose text lives in it. | ||
| 60 | +#[test] | ||
| 61 | +fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { | ||
| 62 | + let srt = subtitle::open(&data("test_subs.srt"), None); | ||
| 63 | + assert_eq!(srt.refused, None, "the .srt parses"); | ||
| 64 | + assert_eq!(srt.cues, expected()); | ||
| 65 | + assert_eq!(srt.label, "test_subs.srt"); | ||
| 66 | + | ||
| 67 | + let ass = subtitle::open(&data("test_subs.ass"), None); | ||
| 68 | + assert_eq!(ass.refused, None, "the .ass parses"); | ||
| 69 | + assert_eq!(ass.cues, expected(), "the override tags are resolved"); | ||
| 70 | + | ||
| 71 | + let embedded = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked"); | ||
| 72 | + let text: Vec<_> = embedded.iter().map(|t| (&t.label, &t.cues)).collect(); | ||
| 73 | + assert_eq!(embedded.len(), 2, "two subtitle tracks: {text:?}"); | ||
| 74 | + for track in &embedded { | ||
| 75 | + assert_eq!(track.refused, None, "{} parses", track.label); | ||
| 76 | + assert_eq!( | ||
| 77 | + track.cues, | ||
| 78 | + expected(), | ||
| 79 | + "{} holds the same cues", | ||
| 80 | + track.label | ||
| 81 | + ); | ||
| 82 | + } | ||
| 83 | + // ...and each is named by what the file says about it, so a list has | ||
| 84 | + // something to show but the track number. | ||
| 85 | + assert_eq!(embedded[0].label, "eng"); | ||
| 86 | + assert_eq!(embedded[1].label, "fra — Signs"); | ||
| 87 | + assert_eq!(embedded[0].track, Some(2)); | ||
| 88 | + assert_eq!(embedded[1].track, Some(3)); | ||
| 89 | + | ||
| 90 | + // The one door a saved line comes back through reaches the same track. | ||
| 91 | + let one = subtitle::open(&asset("test_subs.mkv"), Some(3)); | ||
| 92 | + assert_eq!(one.cues, expected()); | ||
| 93 | + // A track number the file does not have is refused by name, not an error: | ||
| 94 | + // the project it was saved in still opens. | ||
| 95 | + let gone = subtitle::open(&asset("test_subs.mkv"), Some(9)); | ||
| 96 | + assert!( | ||
| 97 | + gone.refused.as_deref().unwrap_or_default().contains("9"), | ||
| 98 | + "{:?}", | ||
| 99 | + gone.refused | ||
| 100 | + ); | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// A subtitle track this cannot read is a row that says why -- never an error | ||
| 104 | +/// that takes the whole file down with it. The repro is a BluRay remux | ||
| 105 | +/// carrying four PGS tracks: opening it lists four subtitles it cannot draw, | ||
| 106 | +/// and the picture and the sound come up regardless. | ||
| 107 | +/// | ||
| 108 | +/// Written here rather than muxed by the fixture script because ffmpeg cannot | ||
| 109 | +/// encode text subtitles into pictures; the bytes below are the `Tracks` | ||
| 110 | +/// element of such a file and nothing else. | ||
| 111 | +#[test] | ||
| 112 | +fn bitmap_subtitles_are_listed_and_skipped_by_name() { | ||
| 113 | + let dir = scratch("pgs"); | ||
| 114 | + let file = dir.join("remux.mkv"); | ||
| 115 | + std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv"); | ||
| 116 | + | ||
| 117 | + let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them"); | ||
| 118 | + assert_eq!(tracks.len(), 4, "every PGS track is listed"); | ||
| 119 | + for (i, track) in tracks.iter().enumerate() { | ||
| 120 | + assert_eq!(track.track, Some(i as u64 + 1)); | ||
| 121 | + assert_eq!(track.cues, Vec::new(), "no cues to have"); | ||
| 122 | + let why = track.refused.clone().unwrap_or_default(); | ||
| 123 | + assert!( | ||
| 124 | + why.contains("S_HDMV/PGS") && why.contains("pictures"), | ||
| 125 | + "the refusal names the codec: {why:?}" | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + // The language is what a list shows, and `und` is what the spec says a | ||
| 129 | + // track that names none is. | ||
| 130 | + assert_eq!(tracks[0].label, "eng"); | ||
| 131 | + assert_eq!(tracks[3].label, "und"); | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// A saved project comes back with its subtitles: the `.edith` names the file | ||
| 135 | +/// and the track, and the cues are read out of them again on the way in. The | ||
| 136 | +/// engine's own door for both halves -- import, save, open -- since that is | ||
| 137 | +/// what a front-end will drive. | ||
| 138 | +#[test] | ||
| 139 | +fn a_project_keeps_its_subtitles_across_a_save() { | ||
| 140 | + let dir = scratch("save"); | ||
| 141 | + let media = dir.join("test_av.mp4"); | ||
| 142 | + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); | ||
| 143 | + // Beside the media, which is where a subtitle file lives: the project then | ||
| 144 | + // writes it relative, and the whole folder stays movable. | ||
| 145 | + let subs = dir.join("test_subs.srt"); | ||
| 146 | + std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture"); | ||
| 147 | + | ||
| 148 | + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); | ||
| 149 | + session.set_gain(0.0); // silent like the rest of the suites | ||
| 150 | + assert_eq!(session.subtitles().len(), 0, "nothing to start with"); | ||
| 151 | + assert_eq!( | ||
| 152 | + session.import_subtitles(&subs).expect("the .srt imports"), | ||
| 153 | + 1 | ||
| 154 | + ); | ||
| 155 | + // The same file twice is the same subtitles, not two rows of them. | ||
| 156 | + assert_eq!(session.import_subtitles(&subs).expect("no error"), 0); | ||
| 157 | + assert_eq!(session.subtitles()[0].cues, expected()); | ||
| 158 | + | ||
| 159 | + let project = dir.join("cut.edith"); | ||
| 160 | + session.save_project(&project).expect("save"); | ||
| 161 | + let text = std::fs::read_to_string(&project).expect("read the project back"); | ||
| 162 | + assert!(text.starts_with("edith 10\n"), "{text}"); | ||
| 163 | + assert!( | ||
| 164 | + text.contains("\nsubtitle - test_subs.srt\n"), | ||
| 165 | + "the reference is written relative, and no cue is: {text}" | ||
| 166 | + ); | ||
| 167 | + | ||
| 168 | + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); | ||
| 169 | + assert_eq!(back.subtitles().len(), 1); | ||
| 170 | + assert_eq!(back.subtitles()[0].cues, expected()); | ||
| 171 | + assert_eq!(back.subtitles()[0].track, None); | ||
| 172 | + drop(back); | ||
| 173 | + | ||
| 174 | + // A subtitle file that has gone missing is listed, refused by name, and | ||
| 175 | + // written out again: the project still opens and the row is not lost. | ||
| 176 | + std::fs::remove_file(&subs).expect("take the subtitles away"); | ||
| 177 | + let gone = engine::PlaybackSession::open_project(&project).expect("the project still opens"); | ||
| 178 | + assert_eq!(gone.subtitles().len(), 1); | ||
| 179 | + assert!(gone.subtitles()[0].refused.is_some()); | ||
| 180 | + let again = dir.join("cut2.edith"); | ||
| 181 | + gone.save_project(&again).expect("save again"); | ||
| 182 | + assert!( | ||
| 183 | + std::fs::read_to_string(&again) | ||
| 184 | + .expect("read") | ||
| 185 | + .contains("\nsubtitle - test_subs.srt\n"), | ||
| 186 | + "a re-save keeps the row" | ||
| 187 | + ); | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// A refusal a front-end shows at the moment of the import, rather than a row | ||
| 191 | +/// nobody asked for: a file that is not a subtitle format at all. | ||
| 192 | +#[test] | ||
| 193 | +fn importing_something_that_is_not_a_subtitle_says_so() { | ||
| 194 | + let dir = scratch("refuse"); | ||
| 195 | + let media = dir.join("test_av.mp4"); | ||
| 196 | + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); | ||
| 197 | + let notes = dir.join("notes.txt"); | ||
| 198 | + std::fs::write(¬es, "not a subtitle").expect("write"); | ||
| 199 | + | ||
| 200 | + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); | ||
| 201 | + session.set_gain(0.0); | ||
| 202 | + let err = session | ||
| 203 | + .import_subtitles(¬es) | ||
| 204 | + .expect_err("a .txt is not a subtitle") | ||
| 205 | + .to_string(); | ||
| 206 | + assert!(err.contains("txt"), "{err}"); | ||
| 207 | + assert_eq!(session.subtitles().len(), 0, "and nothing was added"); | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// The `Tracks` element of a Matroska file carrying four PGS subtitle tracks | ||
| 211 | +/// and nothing else -- enough for the walk, which stops at the first `Cluster` | ||
| 212 | +/// and there is none. | ||
| 213 | +fn pgs_matroska() -> Vec<u8> { | ||
| 214 | + /// An EBML element: its id as it is written in the file, then an 8-byte | ||
| 215 | + /// length, which is always a legal encoding of one. | ||
| 216 | + fn element(id: &[u8], body: &[u8]) -> Vec<u8> { | ||
| 217 | + let mut out = id.to_vec(); | ||
| 218 | + let mut len = (body.len() as u64).to_be_bytes(); | ||
| 219 | + len[0] |= 0x01; // the 8-byte length marker | ||
| 220 | + out.extend_from_slice(&len); | ||
| 221 | + out.extend_from_slice(body); | ||
| 222 | + out | ||
| 223 | + } | ||
| 224 | + let mut tracks = Vec::new(); | ||
| 225 | + for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { | ||
| 226 | + let mut entry = Vec::new(); | ||
| 227 | + entry.extend(element(&[0xD7], &[number])); // TrackNumber | ||
| 228 | + entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle | ||
| 229 | + entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID | ||
| 230 | + if !language.is_empty() { | ||
| 231 | + entry.extend(element(&[0x22, 0xB5, 0x9C], language.as_bytes())); | ||
| 232 | + } | ||
| 233 | + tracks.extend(element(&[0xAE], &entry)); // TrackEntry | ||
| 234 | + } | ||
| 235 | + let segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks | ||
| 236 | + element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment | ||
| 237 | +} | ||
crates/engine/tests/vp9.rsmodified+22 -6
| @@ -76,17 +76,33 @@ fn the_software_path_refuses_vp9_by_name() { | |||
| 76 | assert!(h264, "software H.264 decode still opens"); | 76 | assert!(h264, "software H.264 decode still opens"); |
| 77 | } | 77 | } |
| 78 | 78 | ||
| 79 | -/// A VP9 timeline is refused a source coded differently, in the same words a | 79 | +/// A timeline is *not* refused a source coded differently -- every clip opens |
| 80 | -/// resolution mismatch is refused in: a front-end shows the string as it is. | 80 | +/// its own decoder. What survives is the reason the codec gate existed: on a |
| 81 | +/// machine that cannot decode VP9 the file is refused at the door, by the | ||
| 82 | +/// decoder's own name, rather than becoming a clip of black frames. | ||
| 81 | #[test] | 83 | #[test] |
| 82 | -fn a_timeline_refuses_the_other_codec() { | 84 | +fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { |
| 83 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); | 85 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); |
| 86 | + // The no-plugin machine, forced. | ||
| 87 | + // SAFETY: the suite is documented to run with --test-threads=1. | ||
| 88 | + unsafe { std::env::set_var("VE_SW", "1") }; | ||
| 84 | let refused = session | 89 | let refused = session |
| 85 | .import(&asset("test_vp9.mp4")) | 90 | .import(&asset("test_vp9.mp4")) |
| 86 | - .expect_err("VP9 must not join an H.264 timeline") | 91 | + .expect_err("no VP9 decoder means no VP9 clip") |
| 87 | .to_string(); | 92 | .to_string(); |
| 88 | - assert!(refused.contains("VP9"), "{refused}"); | 93 | + unsafe { std::env::remove_var("VE_SW") }; |
| 89 | - assert!(refused.contains("H.264"), "{refused}"); | 94 | + assert_eq!(refused, Codec::Vp9.needs_plugin()); |
| 95 | + assert!( | ||
| 96 | + !refused.contains("H.264"), | ||
| 97 | + "the timeline's own codec is no longer a reason: {refused}" | ||
| 98 | + ); | ||
| 99 | + assert_eq!(session.sources().len(), 1, "a refusal left no row"); | ||
| 100 | + | ||
| 101 | + // ...and where a decoder exists, it simply joins. | ||
| 102 | + match session.import(&asset("test_vp9.mp4")) { | ||
| 103 | + Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 beside H.264"), | ||
| 104 | + Err(e) => assert_eq!(e.to_string(), Codec::Vp9.needs_plugin()), | ||
| 105 | + } | ||
| 90 | } | 106 | } |
| 91 | 107 | ||
| 92 | /// The end-to-end user path: opening the file yields pictures, all of them, | 108 | /// The end-to-end user path: opening the file yields pictures, all of them, |
scripts/gen_fixtures.shmodified+60 -4
| @@ -103,16 +103,54 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 103 | # at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as | 103 | # at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as |
| 104 | # the others so the tests measure the codec and nothing else -- but `-g 30` is | 104 | # the others so the tests measure the codec and nothing else -- but `-g 30` is |
| 105 | # not a preference: it puts a second keyframe at frame 30, which is what the | 105 | # not a preference: it puts a second keyframe at frame 30, which is what the |
| 106 | -# sync index and the seek test are checked against. 8-bit Main profile, because | 106 | +# sync index and the seek test are checked against. 8-bit Main profile here; the |
| 107 | -# the plugin's NV12 read-back cannot carry 10-bit. Its AAC track is deliberate | 107 | +# 10-bit twin is below. Its AAC track is deliberate too: it is the AAC a Matroska |
| 108 | -# too: Matroska audio is not wired to the decoder yet, and the notice that says | 108 | +# file's sound is read out of through symphonia, beside the AC-3 fixtures further |
| 109 | -# so needs a track to name. | 109 | +# down that no symphonia version decodes. |
| 110 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | 110 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ |
| 111 | -f lavfi -i "sine=frequency=440:duration=2" \ | 111 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 112 | -f lavfi -i "sine=frequency=880:duration=2" \ | 112 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| 113 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 113 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 114 | -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ | 114 | -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ |
| 115 | -c:a aac -b:a 128k assets/test_av1.mkv | 115 | -c:a aac -b:a 128k assets/test_av1.mkv |
| 116 | +# ...and the same file 10-bit, which is what an `av1C` with `high_bitdepth` set | ||
| 117 | +# reads as and what the P010 surface pool is picked by -- the AV1 seat of the | ||
| 118 | +# pair test_hevc.mkv/test_hevc10.mkv already make for HEVC. libaom rather than | ||
| 119 | +# SVT-AV1 because it is the encoder that writes a 10-bit `av1C` here. | ||
| 120 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 121 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 122 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 123 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | ||
| 124 | + -map 0:v -map "[a]" -c:v libaom-av1 -cpu-used 8 -row-mt 1 -g 30 -pix_fmt yuv420p10le \ | ||
| 125 | + -c:a aac -b:a 128k assets/test_av1_10.mkv | ||
| 126 | +# H.264 in Matroska: the same stream the mp4 fixtures carry, in the container | ||
| 127 | +# that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing | ||
| 128 | +# installed, `-g 30` for the second keyframe the sync index is checked against, | ||
| 129 | +# and the AAC track for the sound an mkv's audio path reads back. | ||
| 130 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 131 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 132 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 133 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | ||
| 134 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 135 | + -c:a aac -b:a 128k assets/test_h264.mkv | ||
| 136 | +# Subtitles in Matroska: the two text codecs a film carries, muxed out of the | ||
| 137 | +# hand-written files the tests also parse standalone | ||
| 138 | +# (`crates/engine/tests/data/`), so the embedded cues and the external ones can | ||
| 139 | +# be compared to each other and both to the source. Track 2 is S_TEXT/UTF8 and | ||
| 140 | +# track 3 is S_TEXT/ASS -- the same three cues, one of them with markup, which | ||
| 141 | +# is what makes "the markup is resolved, not carried" measurable. | ||
| 142 | +# | ||
| 143 | +# No bitmap track here: ffmpeg cannot encode text subtitles into pictures, so | ||
| 144 | +# the PGS refusal is checked against a Matroska file the test writes itself | ||
| 145 | +# (`crates/engine/tests/subtitles.rs`). | ||
| 146 | +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=5 \ | ||
| 147 | + -i crates/engine/tests/data/test_subs.srt \ | ||
| 148 | + -i crates/engine/tests/data/test_subs.ass \ | ||
| 149 | + -map 0:v -map 1:0 -map 2:0 \ | ||
| 150 | + -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ | ||
| 151 | + -c:s:0 srt -metadata:s:s:0 language=eng \ | ||
| 152 | + -c:s:1 ass -metadata:s:s:1 language=fra -metadata:s:s:1 title=Signs \ | ||
| 153 | + assets/test_subs.mkv | ||
| 116 | # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as | 154 | # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as |
| 117 | # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for | 155 | # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for |
| 118 | # the same reason test_av1.mkv has it (a second keyframe to seek to), and the | 156 | # the same reason test_av1.mkv has it (a second keyframe to seek to), and the |
| @@ -139,6 +177,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 139 | -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ | 177 | -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ |
| 140 | -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ | 178 | -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ |
| 141 | -c:a aac -b:a 384k assets/test_hevc10.mkv | 179 | -c:a aac -b:a 384k assets/test_hevc10.mkv |
| 180 | +# Matroska sound: the two Dolby codecs that arrive in one and are read straight | ||
| 181 | +# out of its blocks (`demux::MkvAudio`). Stereo AC-3 for the plain syntax and | ||
| 182 | +# **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must | ||
| 183 | +# come down to stereo through the same A/52 7.8 downmix the mp4 path uses. | ||
| 184 | +# 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small | ||
| 185 | +# H.264 picture on purpose: these two are about the sound, and the software | ||
| 186 | +# decoder reads that one, so an audio test needs no VA-API plugin to open a | ||
| 187 | +# session on them. | ||
| 188 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 189 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 190 | + -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ | ||
| 191 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \ | ||
| 192 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 193 | + -c:a ac3 -b:a 192k assets/test_ac3.mkv | ||
| 194 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 195 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 196 | + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 197 | + -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv | ||
| 142 | # Sync fixture: one flash and one beep, at the same instant. Black picture with | 198 | # Sync fixture: one flash and one beep, at the same instant. Black picture with |
| 143 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that | 199 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that |
| 144 | # stretch — so a test can find each of them and say how far apart they came out. | 200 | # stretch — so a test can find each of them and say how far apart they came out. |
vendor/rusty_aac/src/dsp.rsmodified+87 -49
| @@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> { | |||
| 35 | if n == 0 { | 35 | if n == 0 { |
| 36 | return Vec::new(); | 36 | return Vec::new(); |
| 37 | } | 37 | } |
| 38 | - // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below -- | 38 | + // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 + |
| 39 | - // the same numbers, looked up instead of called for. | 39 | + // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i + |
| 40 | - if let Some(matrix) = imdct_matrix(n) { | 40 | + // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT -- |
| 41 | - let mut out = vec![0f32; n]; | 41 | + // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is |
| 42 | - for (i, o) in out.iter_mut().enumerate() { | 42 | + // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L). |
| 43 | - let row = &matrix[i * half..(i + 1) * half]; | 43 | + if half >= 2 && half.is_power_of_two() { |
| 44 | - let mut acc = 0f32; | 44 | + let owned; |
| 45 | - for (k, &s) in spec.iter().enumerate() { | 45 | + let tw = match mdct_twiddles(n) { |
| 46 | - acc += s * row[k]; | 46 | + Some(t) => t, |
| 47 | + None => { | ||
| 48 | + owned = MdctTwiddles::build(n); | ||
| 49 | + &owned | ||
| 47 | } | 50 | } |
| 48 | - *o = acc; | 51 | + }; |
| 49 | - } | 52 | + let d = dct4(half, |k| spec[k] as f64, tw); |
| 50 | - return out; | 53 | + let scale = 2.0 / n as f64; |
| 54 | + let (l, l2) = (half, half / 2); | ||
| 55 | + return (0..n) | ||
| 56 | + .map(|i| { | ||
| 57 | + let j = i + l2; | ||
| 58 | + let v = if j < l { | ||
| 59 | + d[j] | ||
| 60 | + } else if j < 2 * l { | ||
| 61 | + -d[2 * l - 1 - j] | ||
| 62 | + } else { | ||
| 63 | + -d[j - 2 * l] | ||
| 64 | + }; | ||
| 65 | + (scale * v) as f32 | ||
| 66 | + }) | ||
| 67 | + .collect(); | ||
| 51 | } | 68 | } |
| 69 | + imdct_direct(spec) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its | ||
| 73 | +/// test measures against and as the path for sizes the fast one does not take. | ||
| 74 | +fn imdct_direct(spec: &[f32]) -> Vec<f32> { | ||
| 75 | + let half = spec.len(); | ||
| 76 | + let n = half * 2; | ||
| 52 | let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2 | 77 | let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2 |
| 53 | let scale = 2.0 / n as f64; | 78 | let scale = 2.0 / n as f64; |
| 54 | let w = 2.0 * PI / n as f64; | 79 | let w = 2.0 * PI / n as f64; |
| @@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> { | |||
| 64 | out | 89 | out |
| 65 | } | 90 | } |
| 66 | 91 | ||
| 67 | -/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block | ||
| 68 | -/// size, built once. The direct transform above spends its whole time in `cos` | ||
| 69 | -/// -- ~63 ms for one 1024-coefficient channel, three times slower than real | ||
| 70 | -/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the | ||
| 71 | -/// long block and 128 kB for the short one, and each output sample becomes a | ||
| 72 | -/// dot product a compiler can vectorise. | ||
| 73 | -fn imdct_matrix(n: usize) -> Option<&'static [f32]> { | ||
| 74 | - static LONG: OnceLock<Vec<f32>> = OnceLock::new(); | ||
| 75 | - static SHORT: OnceLock<Vec<f32>> = OnceLock::new(); | ||
| 76 | - fn build(n: usize) -> Vec<f32> { | ||
| 77 | - let half = n / 2; | ||
| 78 | - let n0 = (n / 2 + 1) as f64 / 2.0; | ||
| 79 | - let scale = 2.0 / n as f64; | ||
| 80 | - let w = 2.0 * PI / n as f64; | ||
| 81 | - let mut m = vec![0f32; n * half]; | ||
| 82 | - for i in 0..n { | ||
| 83 | - let a = w * (i as f64 + n0); | ||
| 84 | - for k in 0..half { | ||
| 85 | - m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32; | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - m | ||
| 89 | - } | ||
| 90 | - match n { | ||
| 91 | - 2048 => Some(LONG.get_or_init(|| build(2048))), | ||
| 92 | - 256 => Some(SHORT.get_or_init(|| build(256))), | ||
| 93 | - _ => None, | ||
| 94 | - } | ||
| 95 | -} | ||
| 96 | - | ||
| 97 | /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate | 92 | /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate |
| 98 | /// the IMDCT via perfect reconstruction (and useful for an eventual encoder). | 93 | /// the IMDCT via perfect reconstruction (and useful for an eventual encoder). |
| 99 | /// `N` time samples → `N/2` coefficients. | 94 | /// `N` time samples → `N/2` coefficients. |
| @@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> { | |||
| 236 | if n < 4 { | 231 | if n < 4 { |
| 237 | return mdct(x); // tiny sizes: fall back to the direct oracle | 232 | return mdct(x); // tiny sizes: fall back to the direct oracle |
| 238 | } | 233 | } |
| 239 | - let (l, m) = (n / 2, n / 4); | 234 | + let l = n / 2; |
| 240 | let owned; | 235 | let owned; |
| 241 | let tw = match mdct_twiddles(n) { | 236 | let tw = match mdct_twiddles(n) { |
| 242 | Some(t) => t, | 237 | Some(t) => t, |
| @@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> { | |||
| 254 | (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64) | 249 | (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64) |
| 255 | } | 250 | } |
| 256 | }; | 251 | }; |
| 257 | - // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}. | 252 | + // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's. |
| 253 | + dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect() | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one | ||
| 257 | +/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p]) | ||
| 258 | +/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read | ||
| 259 | +/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`. | ||
| 260 | +/// | ||
| 261 | +/// `y` is a closure because the forward MDCT folds its input on the fly and the | ||
| 262 | +/// inverse reads a spectrum straight out; `tw` is the block-size table both | ||
| 263 | +/// directions share ([`MdctTwiddles`], built for `N = 2L`). | ||
| 264 | +fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec<f64> { | ||
| 265 | + let m = l / 2; | ||
| 258 | let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]); | 266 | let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]); |
| 259 | for p in 0..m { | 267 | for p in 0..m { |
| 260 | - let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p)); | 268 | + let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p)); |
| 261 | re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p]; | 269 | re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p]; |
| 262 | im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p]; | 270 | im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p]; |
| 263 | } | 271 | } |
| 264 | fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s); | 272 | fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s); |
| 265 | - // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2. | 273 | + let mut out = vec![0f64; l]; |
| 266 | - let mut out = vec![0f32; l]; | ||
| 267 | for p in 0..m { | 274 | for p in 0..m { |
| 268 | let (vr, vi) = (re[p], im[p]); | 275 | let (vr, vi) = (re[p], im[p]); |
| 269 | - out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32; | 276 | + out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p]; |
| 270 | - out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32; | 277 | + out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p]; |
| 271 | } | 278 | } |
| 272 | out | 279 | out |
| 273 | } | 280 | } |
| @@ -346,6 +353,37 @@ mod tests { | |||
| 346 | } | 353 | } |
| 347 | } | 354 | } |
| 348 | 355 | ||
| 356 | + /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both | ||
| 357 | + /// AAC block sizes plus one the twiddle cache does not hold (512, built on | ||
| 358 | + /// the spot) and one the fast path declines (a 3-coefficient spectrum), on | ||
| 359 | + /// raw and decoder-scale (×32768) input. Every output sample, because the | ||
| 360 | + /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a | ||
| 361 | + /// mirror off by one is silent in the first half and audible in the second. | ||
| 362 | + #[test] | ||
| 363 | + fn imdct_matches_direct() { | ||
| 364 | + for &half in &[3usize, 128, 256, 1024] { | ||
| 365 | + for &scale in &[1.0f32, 32768.0] { | ||
| 366 | + let spec: Vec<f32> = (0..half) | ||
| 367 | + .map(|k| { | ||
| 368 | + scale | ||
| 369 | + * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos()) | ||
| 370 | + as f32 | ||
| 371 | + }) | ||
| 372 | + .collect(); | ||
| 373 | + let (a, b) = (imdct_direct(&spec), imdct(&spec)); | ||
| 374 | + let tol = 2e-4 * scale.max(1.0); | ||
| 375 | + for i in 0..half * 2 { | ||
| 376 | + assert!( | ||
| 377 | + (a[i] - b[i]).abs() < tol, | ||
| 378 | + "half={half} scale={scale} i={i}: {} vs {}", | ||
| 379 | + a[i], | ||
| 380 | + b[i] | ||
| 381 | + ); | ||
| 382 | + } | ||
| 383 | + } | ||
| 384 | + } | ||
| 385 | + } | ||
| 386 | + | ||
| 349 | #[test] | 387 | #[test] |
| 350 | fn dequant_matches_spec_curve() { | 388 | fn dequant_matches_spec_curve() { |
| 351 | assert_eq!(dequant(0), 0.0); | 389 | assert_eq!(dequant(0), 0.0); |