forge
Explore
Log in

Don't you dare go Hollow

Merge remote-tracking branch 'origin/main' into worktree-agent-a35b9e46cf4faf7cc

Browse files at this commit

7354892eeab934ffb5d7de6e52a92ffcf884e1dcAhmet Kaan GümüşParent: b640c4eedf0cd9
# Conflicts:
#	crates/app/src/main.rs

30 changed files +5606 -981

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 per23 # 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 not25 # which is 4x slower than real time for 5.1 and therefore not
26-# playable at all; the patch caches the cosine matrix26+# 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` and30 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
28 # refuses any dimension that is not a multiple of the 16-sample31 # refuses any dimension that is not a multiple of the 16-sample
29 # CTB, so 1920x1080 could not be written at all; the patch adds32 # 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 and86 /// 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::AddVideoLane269 | ActionId::AddVideoLane
266 | ActionId::AddAudioLane270 | ActionId::AddAudioLane
267 | ActionId::RemoveVideoLane271 | 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::ToggleMute276 ActionId::ToggleMute
270 | ActionId::VolumeUp277 | 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; 21] = [336+pub const FIXED: [Fixed; 26] = [
330 // Not a chord at all but a way of pressing one, and the only place the337 // 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, and338 // 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.
@@ -394,7 +401,7 @@ pub const FIXED: [Fixed; 21] = [
394 // its own: a band nothing but a drag can reach is a band half the users of401 // its own: a band nothing but a drag can reach is a band half the users of
395 // this editor cannot move at all. Card-local, so none of them is bindable.402 // this editor cannot move at all. Card-local, so none of them is bindable.
396 Fixed {403 Fixed {
397- chord: "1–5",404+ chord: "1–9, 0",
398 label: "Pick an equalizer band",405 label: "Pick an equalizer band",
399 category: Category::Audio,406 category: Category::Audio,
400 },407 },
@@ -408,6 +415,31 @@ pub const FIXED: [Fixed; 21] = [
408 label: "Lower the picked band 1 dB",415 label: "Lower the picked band 1 dB",
409 category: Category::Audio,416 category: Category::Audio,
410 },417 },
418+ Fixed {
419+ chord: "← / →",
420+ label: "Move the picked band down or up in frequency",
421+ category: Category::Audio,
422+ },
423+ Fixed {
424+ chord: "shift ← / →",
425+ label: "Widen or narrow the picked band (its Q)",
426+ category: Category::Audio,
427+ },
428+ Fixed {
429+ chord: "a",
430+ label: "Add an equalizer band beside the picked one",
431+ category: Category::Audio,
432+ },
433+ Fixed {
434+ chord: "x",
435+ label: "Remove the picked equalizer band",
436+ category: Category::Audio,
437+ },
438+ Fixed {
439+ chord: "f",
440+ label: "Flatten the picked band (double-click does the same)",
441+ category: Category::Audio,
442+ },
411 Fixed {443 Fixed {
412 chord: "r",444 chord: "r",
413 label: "Flatten every band",445 label: "Flatten every band",
@@ -645,6 +677,9 @@ impl Keymap {
645 // machine's volume and not the project's -- two things one key677 // machine's volume and not the project's -- two things one key
646 // must not mean.678 // must not mean.
647 b(ActionId::Mix, "f", false),679 b(ActionId::Mix, "f", false),
680+ // The snap takes "n", which is what every other editor toggles
681+ // it with: free here, and nowhere near the two keys that delete.
682+ b(ActionId::ToggleSnap, "n", false),
648 b(ActionId::CancelExport, "escape", false),683 b(ActionId::CancelExport, "escape", false),
649 ],684 ],
650 }685 }
@@ -907,7 +942,7 @@ mod tests {
907 #[test]942 #[test]
908 fn every_default_stroke_reaches_its_action() {943 fn every_default_stroke_reaches_its_action() {
909 let k = Keymap::defaults();944 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);945+ assert_eq!(k.entries().len(), 42);
911 assert_eq!(k.lookup("space", false), Some(ActionId::Play));946 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two947 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913 // ends of the timeline.948 // ends of the timeline.
@@ -1141,7 +1176,8 @@ mod tests {
1141 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1176 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1142 // The label is the editor's column, and never the file's word for it.1177 // The label is the editor's column, and never the file's word for it.
1143 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1178 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1144- assert_eq!(ActionId::ALL.len(), 39);1179+ assert_eq!(ActionId::ALL.len(), 40);
1180+ assert_eq!(k.display(ActionId::ToggleSnap), "n");
1145 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");1181 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1146 }1182 }
1147 1183
crates/app/src/main.rsmodified+2836 -662

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 the29 /// 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 px95 /// 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 frame300 /// A clip edge being dragged: which end of which clip, and the timeline frame
@@ -335,6 +353,38 @@ 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+}
374+
375+/// One value a list offers, carrying everything picking it needs -- so a click
376+/// goes straight to the value rather than to a position in a list that was
377+/// built somewhere else.
378+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
379+enum Choice {
380+ Size(u32, u32),
381+ Fit(Lane, usize, FitPolicy),
382+}
383+
384+/// One row of an open list: the value, its name, the small print beside it, and
385+/// whether it is the one in force.
386+type ChoiceRow = (Choice, SharedString, SharedString, bool);
387+
338 /// What a library row's menu offers, in the order it lists them. Unlike the clip388 /// 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 --389 /// 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.390 /// so the label and the hint are written here rather than read off the keymap.
@@ -402,6 +452,47 @@ const MENU_ITEMS: [ActionId; 14] = [
402 ActionId::ToggleMute,452 ActionId::ToggleMute,
403 ];453 ];
404 454
455+/// One row of the actions card, in the order it lists them: a heading, then
456+/// every action the registry files under it, then the strokes the modal cards
457+/// answer themselves.
458+///
459+/// A list rather than a loop inside the render, so the card and
460+/// `every_action_is_on_the_actions_card` read the *same* order: an action that
461+/// reaches no row fails a test instead of quietly becoming pointer-unreachable.
462+enum KeyRow {
463+ Head(keymap::Category),
464+ /// Click its label to do it, click its stroke to change that stroke.
465+ Act(ActionId),
466+ /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may
467+ /// unbind the way out of a card.
468+ Fixed(usize),
469+}
470+
471+/// Every action, under its heading, and the card-local strokes beside them.
472+/// Generated from the registry -- [`ActionId::ALL`] in its own order, under
473+/// [`keymap::Category::ALL`] -- so an action added there is on the card the
474+/// moment it exists and there is no second list here to forget.
475+fn keys_rows() -> Vec<KeyRow> {
476+ let mut rows = Vec::new();
477+ for category in keymap::Category::ALL {
478+ rows.push(KeyRow::Head(category));
479+ rows.extend(
480+ ActionId::ALL
481+ .into_iter()
482+ .filter(|a| a.category() == category)
483+ .map(KeyRow::Act),
484+ );
485+ rows.extend(
486+ keymap::FIXED
487+ .iter()
488+ .enumerate()
489+ .filter(|(_, f)| f.category == category)
490+ .map(|(i, _)| KeyRow::Fixed(i)),
491+ );
492+ }
493+ rows
494+}
495+
405 /// The project resolutions [`Player::cycle_resolution`] offers, largest first.496 /// 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 beside497 /// 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.498 /// them, which is what makes the trip round come back to where it started.
@@ -524,6 +615,36 @@ const EQ_FREQ_HIGH: f32 = 20_000.;
524 /// and short enough that the card still fits a 360 px window.615 /// and short enough that the card still fits a 360 px window.
525 const EQ_GRAPH_H: f32 = 132.;616 const EQ_GRAPH_H: f32 = 132.;
526 617
618+/// How wide the equalizer card is allowed to get. It is the one card that is a
619+/// *graph*: every pixel across is frequency resolution, and at the 320 px the
620+/// other cards use, a third of an octave was a couple of pixels. Past this the
621+/// curve stops gaining anything and the card starts reading as a wall.
622+const EQ_W_MAX: f32 = 720.;
623+
624+/// The gap the card leaves either side of it, so it reads as a card on a scrim
625+/// rather than as a second window: it takes the width it can get inside that.
626+const EQ_W_MARGIN: f32 = 32.;
627+
628+/// How many bands one clip's equalizer may carry from this card. Ten because
629+/// the keyboard picks a band with a digit and a keyboard has ten of them --
630+/// past that a band would be reachable by pointer only. The engine itself caps
631+/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more
632+/// and this card will draw and edit every one it finds.
633+const EQ_BANDS_MAX: usize = 10;
634+
635+/// One press of the frequency keys, as a factor: a sixth of an octave, so a
636+/// band walks the whole axis in about sixty presses and still lands close
637+/// enough to a named frequency to aim at one.
638+const EQ_FREQ_STEP: f32 = 1.122_462;
639+
640+/// One press of the Q keys, as a factor, and the range they move in. Below the
641+/// bottom a peak is barely a peak any more; above the top it is a whistle on
642+/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
643+/// them, so nothing a file carries has to be dragged into range first.
644+const EQ_Q_STEP: f32 = 1.25;
645+const EQ_Q_LOW: f32 = 0.3;
646+const EQ_Q_HIGH: f32 = 12.;
647+
527 /// How many points the curve is drawn from. One per ~3 px across the card:648 /// 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.649 /// past that the line is smooth and the extra biquad evaluations are wasted.
529 const EQ_CURVE_STEPS: usize = 96;650 const EQ_CURVE_STEPS: usize = 96;
@@ -572,6 +693,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.693 /// its weight: it is what makes a boost read as a hill rather than as a wire.
573 const EQ_FILL_INK: u32 = 0x4a9eff26;694 const EQ_FILL_INK: u32 = 0x4a9eff26;
574 695
696+/// One band's own response, drawn under the sum: a dim thread per band, so a
697+/// boost pushed against a cut can be *seen* as two bands rather than as the
698+/// flat line their total makes.
699+const EQ_BELL_INK: u32 = 0x4a9eff66;
700+
575 /// The colour card's four controls, in the order it lists them: what each is701 /// 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 is702 /// called and the range it moves in. The order is `ColorParams`' own, which is
577 /// what [`color_band`] indexes.703 /// what [`color_band`] indexes.
@@ -614,6 +740,48 @@ const HIST_H: f32 = 96.;
614 /// counts, lightened enough to read on the dark box.740 /// counts, lightened enough to read on the dark box.
615 const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];741 const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
616 742
743+/// Where the transport is. The one answer the button's glyph, its label, its
744+/// enablement, the play key and the repaint loop all read -- there is no play
745+/// flag anywhere else, because a second one is a second answer.
746+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
747+enum Transport {
748+ /// No timeline open. Nothing to play and the transport is dimmed.
749+ Stopped,
750+ Playing,
751+ Paused,
752+ /// Played out: the last frame is on screen, the decoder is finished, and the
753+ /// clock is still running past it -- which is exactly why "is the clock
754+ /// going" is not the same question as "is this playing".
755+ Ended,
756+}
757+
758+impl Transport {
759+ /// The timeline is in motion: two bars on the button, and a repaint owed
760+ /// every vsync.
761+ fn is_playing(self) -> bool {
762+ matches!(self, Transport::Playing)
763+ }
764+
765+ /// The play key and the transport button start over from the top rather
766+ /// than toggling -- the end of a timeline is where every NLE does this, and
767+ /// the button does it because the key already did.
768+ fn restarts(self) -> bool {
769+ matches!(self, Transport::Ended)
770+ }
771+}
772+
773+/// What a session's own two answers mean: the clock, unless the timeline has
774+/// been played out -- `played_out` is the engine's end of stream with no frame
775+/// still waiting on the pump, and it wins, because past the end a running clock
776+/// is measuring wall time and not a picture.
777+fn transport(playing: bool, played_out: bool) -> Transport {
778+ match (played_out, playing) {
779+ (true, _) => Transport::Ended,
780+ (_, true) => Transport::Playing,
781+ (_, false) => Transport::Paused,
782+ }
783+}
784+
617 struct Player {785 struct Player {
618 /// The timeline, once there is one. A run with no file opens without it and786 /// 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, and787 /// waits: the first media import or project load is what fills it, and
@@ -625,21 +793,20 @@ struct Player {
625 name: SharedString,793 name: SharedString,
626 image: Option<Arc<RenderImage>>,794 image: Option<Arc<RenderImage>>,
627 /// A frame that arrived before its time; shown on the tick it comes due.795 /// A frame that arrived before its time; shown on the tick it comes due.
796+ /// The pump's buffer, not transport state -- but a frame waiting here is
797+ /// what keeps a finished decoder from reading as [`Transport::Ended`] one
798+ /// tick early. See [`Player::transport`].
628 held: Option<Frame>,799 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 while800 /// 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.801 /// paused, which is the only way the new still ever reaches the screen.
635 pending_seek: bool,802 pending_seek: bool,
636 /// The ruler's own box, recorded at prepaint: a mouse listener is handed803 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
637 /// the window position and nothing else.804 /// the window position and nothing else.
638 ruler: Rc<Cell<Bounds<Pixels>>>,805 ruler: Rc<Cell<Bounds<Pixels>>>,
639- /// How much of the timeline the ruler and the lanes are showing. Held here806+ /// 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 of807 /// 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.808 /// it, so the boxes, the playhead and the pointer cannot disagree.
642- view: View,809+ scale: Scale,
643 /// Which clip the edit keys act on: the lane it is in and its index there.810 /// 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 on811 /// 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 move812 /// screen, but Lift has to know which half it was aimed at. Indices move
@@ -649,6 +816,10 @@ struct Player {
649 /// `selected` does, so it is closed by anything that can move indices --816 /// `selected` does, so it is closed by anything that can move indices --
650 /// every stroke, and every item of its own.817 /// every stroke, and every item of its own.
651 context_menu: Option<ContextMenu>,818 context_menu: Option<ContextMenu>,
819+ /// The choice list a click on an enumerated setting opened, if one is up:
820+ /// the project resolution or a clip's fit policy, every value on screen at
821+ /// once. Closed by anything that closes the menus, and for the same reason.
822+ picker: Option<Picker>,
652 /// The library menu a right-click on a row opened, if one is up. Names its823 /// 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 it824 /// 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.825 /// was opened on however the list is rebuilt under it.
@@ -704,6 +875,16 @@ struct Player {
704 /// the value being dragged, and stale between drags, which costs nothing --875 /// the value being dragged, and stale between drags, which costs nothing --
705 /// no drag starts without a press on the box it moves.876 /// no drag starts without a press on the box it moves.
706 grab: u32,877 grab: u32,
878+ /// Whether a drag or a trim is pulled onto the edges near it. On by
879+ /// default, because clips meeting exactly is what a timeline is for, and off
880+ /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement
881+ /// no magnet may take away.
882+ snap: bool,
883+ /// The frame the live gesture is about to land on, or `None` while it is
884+ /// over open bed: the line every lane draws so the snap is seen before it
885+ /// happens rather than discovered after the release. Stale between gestures,
886+ /// which costs nothing -- it is drawn only while one is live.
887+ snap_cue: Option<u32>,
707 last_scrub: Instant,888 last_scrub: Instant,
708 last_target: u32,889 last_target: u32,
709 /// The running export. While it owns the UI the editor is read-only.890 /// The running export. While it owns the UI the editor is read-only.
@@ -890,6 +1071,9 @@ impl Player {
890 /// the channel and only the last of them is shown, which *is* the1071 /// the channel and only the last of them is shown, which *is* the
891 /// drop-when-behind policy. A frame that is not due yet waits in `held`.1072 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
892 fn pump(&mut self, window: &mut Window) {1073 fn pump(&mut self, window: &mut Window) {
1074+ // Where the transport was before this drain, so the crossing into
1075+ // `Ended` can be recognised as the one transition it is.
1076+ let was = self.transport();
893 // No timeline, nothing to catch up to: the window is showing its empty1077 // No timeline, nothing to catch up to: the window is showing its empty
894 // state and there is no decoder to drain.1078 // state and there is no decoder to drain.
895 let Some(session) = &mut self.session else {1079 let Some(session) = &mut self.session else {
@@ -905,10 +1089,7 @@ impl Player {
905 // them apart -- `frame.index` is already a timeline index.1089 // them apart -- `frame.index` is already a timeline index.
906 None => match session.try_frame() {1090 None => match session.try_frame() {
907 Some(frame) => frame,1091 Some(frame) => frame,
908- None => {1092+ None => break,
909- self.eos = session.is_eos();
910- break;
911- }
912 },1093 },
913 };1094 };
914 if f64::from(frame.index) <= target {1095 if f64::from(frame.index) <= target {
@@ -943,29 +1124,56 @@ impl Player {
943 }1124 }
944 }1125 }
945 1126
946- if self.eos && self.held.is_none() && !self.done {1127+ if self.transport() == Transport::Ended {
947- self.done = true;
948 // A seek whose worker never produced a frame (vanished file) would1128 // A seek whose worker never produced a frame (vanished file) would
949- // otherwise repaint at vsync forever.1129+ // otherwise repaint at vsync forever. Held true for as long as the
1130+ // state does, not just on the crossing: nothing else is coming.
950 self.pending_seek = false;1131 self.pending_seek = false;
1132+ if was != Transport::Ended {
1133+ // Ended is a *stopped* transport, so the clock stops with it,
1134+ // on the out point the timecode and the playhead have been
1135+ // showing all along. Nothing else ever stopped it: past the
1136+ // last frame wall time takes over and `now()` walks off the end
1137+ // of the timeline for as long as the window is left open -- and
1138+ // the playhead is what a cut, a paste, an insert and the
1139+ // analyser all act at, so every one of them was aiming into
1140+ // empty space (measured: a 5 s timeline recognised its end at
1141+ // clock 17.5 s under a slow renderer). End of stream is left
1142+ // set, so this is still `Ended` and the next press restarts.
1143+ if let Some(session) = &mut self.session {
1144+ session.halt_at_end();
1145+ }
951 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());1146 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
952 eprintln!(1147 eprintln!(
953 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",1148 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
954 self.displayed,1149 self.displayed,
955 self.dropped,1150 self.dropped,
956- session.now()1151+ self.session.as_ref().map_or(0., PlaybackSession::now)
957 );1152 );
958 }1153 }
959 }1154 }
1155+ }
1156+
1157+ /// Where the transport is, asked of the session rather than remembered:
1158+ /// end of stream is the engine's own flag (any seek clears it, which is why
1159+ /// an edit past the end revives the picture) and so is the clock. A held
1160+ /// frame is one still owed to the screen, so the end is not the end yet.
1161+ fn transport(&self) -> Transport {
1162+ let Some(session) = &self.session else {
1163+ return Transport::Stopped;
1164+ };
1165+ transport(
1166+ session.is_playing(),
1167+ session.is_eos() && self.held.is_none(),
1168+ )
1169+ }
960 1170
961- /// Every end-of-stream flag is app state and the engine knows nothing about1171+ /// A frame owed to the screen after a reseek, and the buffered one dropped:
962- /// it, so clearing them after a reseek is what stops the picture from1172+ /// what stops the picture from staying frozen on the old last frame. The
963- /// staying frozen on the old last frame. Edits reseek inside the engine and1173+ /// end-of-stream flag itself is the engine's and its own seek clears it --
964- /// still owe this.1174+ /// edits reseek inside the engine and still owe this.
965 fn reset_after_reseek(&mut self) {1175 fn reset_after_reseek(&mut self) {
966 self.held = None;1176 self.held = None;
967- self.eos = false;
968- self.done = false;
969 self.pending_seek = true;1177 self.pending_seek = true;
970 // An edit moves the indices a drag in flight is holding -- a stroke1178 // An edit moves the indices a drag in flight is holding -- a stroke
971 // during one is exactly that -- and an edge committed against a moved1179 // during one is exactly that -- and an edge committed against a moved
@@ -1025,12 +1233,57 @@ impl Player {
1025 ActionId::Speed => self.open_speed(cx),1233 ActionId::Speed => self.open_speed(cx),
1026 ActionId::Silence => self.open_silence(cx),1234 ActionId::Silence => self.open_silence(cx),
1027 ActionId::Mix => self.open_mix(None, cx),1235 ActionId::Mix => self.open_mix(None, cx),
1236+ ActionId::ToggleSnap => self.toggle_snap(cx),
1028 // Nothing to cancel while nothing is exporting; the export guard in1237 // Nothing to cancel while nothing is exporting; the export guard in
1029 // the key handler is what answers this one while there is.1238 // the key handler is what answers this one while there is.
1030 ActionId::CancelExport => {}1239 ActionId::CancelExport => {}
1031 }1240 }
1032 }1241 }
1033 1242
1243+ /// The magnet off and on again, in words: a snap that stops working
1244+ /// silently reads as a bug, and one that starts working silently reads as
1245+ /// one too. The line goes with it -- nothing is being promised any more.
1246+ fn toggle_snap(&mut self, cx: &mut Context<Self>) {
1247+ self.snap = !self.snap;
1248+ self.snap_cue = None;
1249+ self.notice = Some(match self.snap {
1250+ true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
1251+ false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
1252+ });
1253+ cx.notify();
1254+ }
1255+
1256+ /// Whether the editor can be asked for `action` right now, and why not when
1257+ /// it cannot. `on` is the clip the question is about -- the one a clip menu
1258+ /// was opened on -- and `None` asks about the marked clip instead, which is
1259+ /// what a menu that hangs over no clip in particular means by "this one".
1260+ ///
1261+ /// The player's half of [`enable`]: it reads the state, the table decides.
1262+ fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable {
1263+ let Some(session) = &self.session else {
1264+ return enable(action, Ctx::default());
1265+ };
1266+ let clip = on
1267+ .or(self.selected)
1268+ .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane)));
1269+ enable(
1270+ action,
1271+ Ctx {
1272+ clip,
1273+ image: clip.is_some_and(|(clip, _)| {
1274+ session
1275+ .sources()
1276+ .get(clip.source)
1277+ .is_some_and(|s| engine::is_image(&s.path))
1278+ }),
1279+ playhead: frame_at(session.now(), self.fps),
1280+ timeline: true,
1281+ clipboard: self.clipboard.is_some(),
1282+ exporting: self.exporting().is_some(),
1283+ },
1284+ )
1285+ }
1286+
1034 /// The one place a clip becomes *the* selected one: a click, a right-click1287 /// The one place a clip becomes *the* selected one: a click, a right-click
1035 /// that opens the menu, and every selection key go through here, so what a1288 /// that opens the menu, and every selection key go through here, so what a
1036 /// keyboard marks and what a pointer marks are the same state marked the1289 /// keyboard marks and what a pointer marks are the same state marked the
@@ -1126,31 +1379,54 @@ impl Player {
1126 return;1379 return;
1127 };1380 };
1128 let next = next_fit(session.fit_of(lane, idx));1381 let next = next_fit(session.fit_of(lane, idx));
1129- if session.set_fit(lane, idx, next) {1382+ self.apply_fit(lane, idx, next, cx);
1383+ }
1384+
1385+ /// One clip's fit policy set, whichever asked: the stroke that steps to the
1386+ /// next one and the list that names one outright come through here, so they
1387+ /// cannot differ in what they do or in what they say they did.
1388+ fn apply_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy, cx: &mut Context<Self>) {
1389+ if let Some(session) = &mut self.session
1390+ && session.set_fit(lane, idx, fit)
1391+ {
1130 let (w, h) = session.resolution();1392 let (w, h) = session.resolution();
1131- self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(next)).into());1393+ self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(fit)).into());
1132 self.reset_after_reseek();1394 self.reset_after_reseek();
1133 }1395 }
1134 cx.notify();1396 cx.notify();
1135 }1397 }
1136 1398
1137- /// Magnifies the timeline about a point that stays put: `anchor` is where1399+ /// The scale against the bed it is drawn on and the timeline it is drawn
1138- /// along the bed to hold still (a ctrl+wheel holds the pointer), and with1400+ /// from: every clamp, zoom and scroll is worked out through this, and the
1139- /// none it is the playhead -- so the frame being worked on is still the1401+ /// bed is measured off the ruler's probe rather than remembered, so a
1402+ /// resized window is a resized view on the very next answer.
1403+ fn view(&self) -> View {
1404+ View {
1405+ scale: self.scale,
1406+ bed: f32::from(self.ruler.get().size.width),
1407+ duration: self.drawn_duration(),
1408+ fps: self.fps,
1409+ }
1410+ }
1411+
1412+ /// Magnifies the timeline about a point that stays put: `anchor` is how many
1413+ /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and
1414+ /// with none it is the playhead -- so the frame being worked on is still the
1140 /// frame on screen after the zoom. Clamped at both ends by [`View`]: out1415 /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
1141- /// stops at the whole timeline, in at a handful of frames.1416+ /// stops at [`ZOOM_MAX_SECONDS`] on the bed, in at a handful of frames.
1142 fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {1417 fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
1143- let duration = self.drawn_duration();1418+ let view = self.view();
1144- let at = self.playhead(duration);1419+ let at = self.playhead(view.duration);
1145- let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.));1420+ let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
1146- self.view = self.view.zoomed(factor, anchor, duration, self.fps);1421+ self.scale = view.zoomed(factor, anchor);
1147 cx.notify();1422 cx.notify();
1148 }1423 }
1149 1424
1150- /// All the way back out: the whole timeline across the bed, which is what1425+ /// All the way back out: the whole timeline across the bed, and the one
1151- /// the panel shows before anyone has zoomed at all.1426+ /// thing that reads the timeline's own length to decide how wide a second
1427+ /// is drawn.
1152 fn zoom_fit(&mut self, cx: &mut Context<Self>) {1428 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
1153- self.view = View::default();1429+ self.scale = self.view().fit();
1154 cx.notify();1430 cx.notify();
1155 }1431 }
1156 1432
@@ -1169,13 +1445,59 @@ impl Player {
1169 return;1445 return;
1170 };1446 };
1171 let (width, height) = next_resolution(session.resolution(), session.native_resolution());1447 let (width, height) = next_resolution(session.resolution(), session.native_resolution());
1172- if session.set_resolution(width, height) {1448+ self.apply_resolution(width, height, cx);
1449+ }
1450+
1451+ /// The project resized, whichever asked: the stroke that steps to the next
1452+ /// size and the list that names one outright come through here.
1453+ fn apply_resolution(&mut self, width: u32, height: u32, cx: &mut Context<Self>) {
1454+ if let Some(session) = &mut self.session
1455+ && session.set_resolution(width, height)
1456+ {
1173 self.notice = Some(format!("PROJECT: {width}x{height}").into());1457 self.notice = Some(format!("PROJECT: {width}x{height}").into());
1174 self.reset_after_reseek();1458 self.reset_after_reseek();
1175 }1459 }
1176 cx.notify();1460 cx.notify();
1177 }1461 }
1178 1462
1463+ /// Opens a choice list on a setting, where it was asked for. One floating
1464+ /// thing at a time: the click that opens it is the click that closes
1465+ /// whatever menu it was opened from.
1466+ fn open_picker(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) {
1467+ self.context_menu = None;
1468+ self.library_menu = None;
1469+ self.picker = Some(Picker { of, at });
1470+ cx.notify();
1471+ }
1472+
1473+ /// A row of the open list was picked. Closes the list first -- the rule
1474+ /// every menu item here follows -- then does exactly what the stroke for
1475+ /// that setting does, through the same door.
1476+ fn choose(&mut self, choice: Choice, cx: &mut Context<Self>) {
1477+ self.picker = None;
1478+ match choice {
1479+ Choice::Size(w, h) => self.apply_resolution(w, h, cx),
1480+ Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
1481+ }
1482+ }
1483+
1484+ /// Every value the open list offers, in the order it lists them. Empty
1485+ /// without a timeline, which is the state where nothing here has a value to
1486+ /// offer -- and where the surfaces that open the list are dimmed anyway.
1487+ fn choices(&self, of: Pick) -> Vec<ChoiceRow> {
1488+ let Some(session) = &self.session else {
1489+ return Vec::new();
1490+ };
1491+ match of {
1492+ Pick::Resolution => {
1493+ resolution_choices(session.resolution(), session.native_resolution())
1494+ }
1495+ Pick::Fit(lane, idx) => {
1496+ fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
1497+ }
1498+ }
1499+ }
1500+
1179 /// Opens the colour card on the clip a grade would go on: the clip that was1501 /// Opens the colour card on the clip a grade would go on: the clip that was
1180 /// clicked when it is a video one, and otherwise the clip the picture is1502 /// clicked when it is a video one, and otherwise the clip the picture is
1181 /// coming from -- the one the engine's own compositing rule picks, which is1503 /// coming from -- the one the engine's own compositing rule picks, which is
@@ -1863,41 +2185,78 @@ impl Player {
1863 cx.notify();2185 cx.notify();
1864 }2186 }
1865 2187
1866- /// Moves one band and says whether anything changed. Live only: the write2188+ /// Changes the picked band in place and says whether anything moved. Every
1867- /// is [`commit_eq`](Player::commit_eq)'s.2189+ /// edit of a band goes through here -- the drag, each key, each stepper
1868- fn set_band(&mut self, band: usize, gain_db: f32) -> bool {2190+ /// button -- so the card has exactly one place that clamps a band into what
1869- let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);2191+ /// the graph can draw, and no caller has to remember the limits.
1870- match self.eq_params.bands.get_mut(band) {2192+ fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
1871- Some(b) if b.gain_db != gain_db => {2193+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
1872- b.gain_db = gain_db;2194+ return false;
1873- true2195+ };
2196+ let was = *band;
2197+ change(band);
2198+ band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
2199+ band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
2200+ band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
2201+ *band != was
2202+ }
2203+
2204+ /// The keyboard's and the buttons' version of a drag: one step on the picked
2205+ /// band, committed straight away -- neither has a release to wait for.
2206+ fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
2207+ if self.set_band(change) {
2208+ self.commit_eq(cx);
1874 }2209 }
1875- _ => false,2210+ }
2211+
2212+ /// Where the pointer sits in the graph, as the picked band's frequency and
2213+ /// gain: across is the frequency axis and down is the gain one, so the
2214+ /// handle follows the hand both ways rather than sliding up a rail. Called
2215+ /// on every pointer sample, so the curve bends under it; the write is the
2216+ /// release's ([`commit_eq`](Player::commit_eq)).
2217+ fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
2218+ let bounds = self.eq_graph.get();
2219+ let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
2220+ let freq = eq_freq(frac_along(at.x, bounds));
2221+ if self.set_band(|b| {
2222+ b.gain_db = gain;
2223+ b.freq_hz = freq;
2224+ }) {
2225+ cx.notify();
1876 }2226 }
1877 }2227 }
1878 2228
1879- /// The keyboard's version of a drag: one step on the picked band, committed2229+ /// A band added beside the picked one, at the frequency with the most room
1880- /// straight away -- a keystroke has no release to wait for.2230+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
1881- fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {2231+ /// band that was just made. Refused rather than silently ignored at the cap.
1882- let gain = self2232+ fn add_band(&mut self, cx: &mut Context<Self>) {
1883- .eq_params2233+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
1884- .bands2234+ self.notice = Some(
1885- .get(self.eq_band)2235+ format!(
1886- .map_or(0., |b| b.gain_db);2236+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
1887- if self.set_band(self.eq_band, gain + by) {2237+ )
1888- self.commit_eq(cx);2238+ .into(),
2239+ );
2240+ cx.notify();
2241+ return;
1889 }2242 }
2243+ let band = inserted_band(&self.eq_params.bands, self.eq_band);
2244+ self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
2245+ self.eq_params.bands.insert(self.eq_band, band);
2246+ self.commit_eq(cx);
1890 }2247 }
1891 2248
1892- /// Where the pointer sits down the graph, as a gain on the picked band: the2249+ /// Takes the picked band out. The last one stays: an equalizer of no bands
1893- /// middle is flat and the top and bottom edges are the limit either way.2250+ /// is a card with nothing to edit, and flattening is what "off" means here.
1894- /// Called on every pointer sample, so the curve bends under the hand; the2251+ fn remove_band(&mut self, cx: &mut Context<Self>) {
1895- /// write is the release's ([`commit_eq`](Player::commit_eq)).2252+ if self.eq_params.bands.len() <= 1 {
1896- fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {2253+ self.notice = Some("LAST BAND — flatten it instead (r), or close the card".into());
1897- let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;
1898- if self.set_band(self.eq_band, gain) {
1899 cx.notify();2254 cx.notify();
2255+ return;
1900 }2256 }
2257+ self.eq_params.bands.remove(self.eq_band);
2258+ self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
2259+ self.commit_eq(cx);
1901 }2260 }
1902 2261
1903 /// Which band a press on the graph grabs: the nearest one along the2262 /// Which band a press on the graph grabs: the nearest one along the
@@ -1934,16 +2293,17 @@ impl Player {
1934 /// door a ruler click uses -- so a step while playing keeps playing, exactly2293 /// door a ruler click uses -- so a step while playing keeps playing, exactly
1935 /// as a click does. It starts from the frame the transport is showing, which2294 /// as a click does. It starts from the frame the transport is showing, which
1936 /// past the end is the last one, and that is what lets a step back off EOS2295 /// past the end is the last one, and that is what lets a step back off EOS
1937- /// revive the picture ([`Player::reset_after_reseek`] clears `done`). Both2296+ /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
1938 /// ends clamp, so the two go-to actions are this same step asked for more2297 /// ends clamp, so the two go-to actions are this same step asked for more
1939 /// frames than the timeline has. Selection is untouched: a seek is not an2298 /// frames than the timeline has. Selection is untouched: a seek is not an
1940 /// edit, and nothing it does moves a clip index.2299 /// edit, and nothing it does moves a clip index.
1941 fn step(&mut self, frames: i64, cx: &mut Context<Self>) {2300 fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
2301+ let ended = self.transport() == Transport::Ended;
1942 let Some(session) = &self.session else {2302 let Some(session) = &self.session else {
1943 return;2303 return;
1944 };2304 };
1945 let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);2305 let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
1946- let now = match self.done {2306+ let now = match ended {
1947 true => last,2307 true => last,
1948 false => i64::from(frame_at(session.now(), self.fps)),2308 false => i64::from(frame_at(session.now(), self.fps)),
1949 };2309 };
@@ -2183,9 +2543,8 @@ impl Player {
2183 let (path, stream) = key.clone();2543 let (path, stream) = key.clone();
2184 async move {2544 async move {
2185 engine::waveform::peaks(&path, stream, WAVE_BPS)2545 engine::waveform::peaks(&path, stream, WAVE_BPS)
2186- .ok()2546+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
2187- .flatten()2547+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
2188- .map(|peaks| Arc::new(normalise(peaks)))
2189 }2548 }
2190 });2549 });
2191 cx.spawn(async move |this, cx| {2550 cx.spawn(async move |this, cx| {
@@ -2194,11 +2553,14 @@ impl Player {
2194 this.waves.insert(2553 this.waves.insert(
2195 key,2554 key,
2196 match decoded {2555 match decoded {
2197- Some(peaks) => Wave::Peaks(peaks),2556+ Ok(Some(peaks)) => Wave::Peaks(peaks),
2198- // Either no audio track or a file we could not read2557+ // No audio track: an answer, and not worth asking
2199- // it from; both mean the lane has nothing to draw,2558+ // about again.
2200- // and neither is worth asking about again.2559+ Ok(None) => Wave::Silent,
2201- None => Wave::Silent,2560+ // A file whose sound we could not read is not a
2561+ // silent one, and a lane that drew it as silent is
2562+ // how a broken decode passes for a design choice.
2563+ Err(_) => Wave::Failed,
2202 },2564 },
2203 );2565 );
2204 cx.notify();2566 cx.notify();
@@ -2294,8 +2656,8 @@ impl Player {
2294 if self.exporting().is_some() {2656 if self.exporting().is_some() {
2295 return;2657 return;
2296 }2658 }
2297- let (Some(start), Some(was)) = (2659+ let (Some((start, _)), Some(was)) = (
2298- self.drop_frame(from, idx, to, x),2660+ self.drop_frame(from, idx, x),
2299 self.session2661 self.session
2300 .as_ref()2662 .as_ref()
2301 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),2663 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2351,46 +2713,83 @@ impl Player {
2351 /// there is no such clip to move. The engine has the last word on where it2713 /// there is no such clip to move. The engine has the last word on where it
2352 /// may actually go -- this is the ask, not the answer.2714 /// may actually go -- this is the ask, not the answer.
2353 ///2715 ///
2354- /// ponytail: the bed ends where the timeline does, so a clip cannot be2716+ /// ponytail: the bed now runs past the last frame whenever the timeline is
2355- /// dragged *past* the last frame -- the pointer has no pixel out there to2717+ /// shorter than the view ([`Scale::time_at`] clamps at the head only), so a
2356- /// name and [`View::time_at`] clamps to the duration. Room to the right is2718+ /// clip *can* be dragged out there. Zoomed in against the far end it cannot:
2357- /// made by pulling a tail out first ([`Player::drawn_duration`] already2719+ /// the scroll clamp pins the bed's right edge to the duration, and the
2358- /// lengthens the bed for exactly that gesture). The upgrade is to draw the2720+ /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2359- /// bed past the end while a clip drag is in flight, the way a trim already2721+ /// leave a screen of empty bed after the end, the way every NLE does.
2360- /// does: `drawn_duration` would take the dragged clip's length the same way2722+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2361- /// it takes a trim's reach.2723+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
2362- fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> {
2363- let session = self.session.as_ref()?;
2364- let clip = session.lane_clips(from).get(idx).copied()?;
2365 let raw = self.frame_under(x).saturating_sub(self.grab);2724 let raw = self.frame_under(x).saturating_sub(self.grab);
2366- // The edges worth landing on: both ends of every clip already on the2725+ let marks = self.snap_targets(Some((from, idx)));
2367- // lane it is being let go over, the playhead, and the head of the2726+ Some(self.snap_to(raw, clip.frames(), &marks))
2368- // timeline. Never the group's own boxes -- a clip does not snap to
2369- // where it already is.
2370- let mut marks: Vec<u32> = session
2371- .lane_clips(to)
2372- .iter()
2373- .enumerate()
2374- .filter(|&(i, c)| {
2375- (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link)
2376- })
2377- .flat_map(|(_, c)| [c.start, c.end()])
2378- .collect();
2379- marks.push(frame_at(session.now(), self.fps));
2380- marks.push(0);
2381- Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))
2382 }2727 }
2383 2728
2384- /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is2729+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
2385- /// a distance on screen, so zoomed right in it is worth less than a frame2730+ /// lane the drag named, since a stroke during the gesture moves the indices
2386- /// (no snap at all, which is what a hand placing single frames wants) and2731+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
2387- /// zoomed out to the whole timeline it is worth many.2732+ /// drawn in flight and the drop that commits -- so the promise and the
2388- fn snap_frames(&self) -> u32 {2733+ /// landing are made about one clip.
2389- let bed = f64::from(f32::from(self.ruler.get().size.width));2734+ fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
2390- if bed <= 0. {2735+ let session = self.session.as_ref()?;
2391- return 0;2736+ live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip)
2737+ }
2738+
2739+ /// The line while the clip is still in the hand: the very answer
2740+ /// [`Player::drop_frame`] will commit, worked out on every move of the drag,
2741+ /// so what the eye was promised is where the release puts it. A pointer that
2742+ /// has wandered off the bed promises nothing.
2743+ fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) {
2744+ let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue);
2745+ self.set_cue(cue, x, cx);
2746+ }
2747+
2748+ /// The same line for a library row on its way to a lane: it goes down at
2749+ /// the frame it is let go on ([`Player::insert_source`]), so that frame is
2750+ /// what snaps and what is drawn. No length to snap by -- the file's own is
2751+ /// not known until the engine has placed it -- so only its head lands.
2752+ fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) {
2753+ let marks = self.snap_targets(None);
2754+ let cue = self.snap_to(self.frame_under(x), 0, &marks).1;
2755+ self.set_cue(cue, x, cx);
2756+ }
2757+
2758+ /// Sets the line, or takes it away, and repaints only when it moved: a
2759+ /// pointer dragged off the bed (up to the library, say) is not promising a
2760+ /// landing any more.
2761+ fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) {
2762+ let bed = self.ruler.get();
2763+ let cue = cue.filter(|_| x >= bed.left() && x <= bed.right());
2764+ if cue != self.snap_cue {
2765+ self.snap_cue = cue;
2766+ cx.notify();
2767+ }
2768+ }
2769+
2770+ /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its
2771+ /// lanes, so a clip meets a take one track over as readily as one beside it.
2772+ fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> {
2773+ let Some(session) = &self.session else {
2774+ return Vec::new();
2775+ };
2776+ let lanes = session.lanes();
2777+ let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect();
2778+ let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx)));
2779+ snap_marks(&clips, skip, frame_at(session.now(), self.fps))
2780+ }
2781+
2782+ /// Where a gesture at `raw` lands and the mark that pulled it there, with
2783+ /// the switch honoured: snapping off, nothing moves and no line is drawn.
2784+ fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) {
2785+ snap_cue(self.snap, raw, len, self.snap_frames(), marks)
2392 }2786 }
2393- (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u322787+
2788+ /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
2789+ /// own width drops out of it, since a pixel is now worth the same stretch of
2790+ /// timeline wherever the view sits.
2791+ fn snap_frames(&self) -> u32 {
2792+ self.scale.snap_frames(self.fps)
2394 }2793 }
2395 2794
2396 /// Opens the clip menu on the box under the pointer, from the right button2795 /// Opens the clip menu on the box under the pointer, from the right button
@@ -2447,26 +2846,36 @@ impl Player {
2447 /// against the same duration the boxes are drawn to, so the edge tracks the2846 /// against the same duration the boxes are drawn to, so the edge tracks the
2448 /// pointer exactly.2847 /// pointer exactly.
2449 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {2848 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2450- let at = self.frame_under(x);2849+ let Some(trim) = self.trim else {
2451- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2452 return;2850 return;
2453 };2851 };
2454- let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {2852+ // The edge is pulled onto the same marks a whole clip is, by itself:
2853+ // there is no other end travelling with it, so it snaps at length zero.
2854+ let marks = self.snap_targets(Some((trim.lane, trim.idx)));
2855+ let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks);
2856+ let Some((lo, hi)) = self
2857+ .session
2858+ .as_ref()
2859+ .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge))
2860+ else {
2455 return;2861 return;
2456 };2862 };
2457- trim.to = at.clamp(lo, hi);2863+ let to = at.clamp(lo, hi);
2864+ // The line only stands where the edge actually stopped: a mark the
2865+ // engine's own room clamped away was never reached.
2866+ self.set_cue(cue.filter(|_| to == at), x, cx);
2867+ self.trim = Some(Trim { to, ..trim });
2458 cx.notify();2868 cx.notify();
2459 }2869 }
2460 2870
2461 /// The timeline frame a pointer at window x is on: along the same bed the2871 /// The timeline frame a pointer at window x is on: along the same bed the
2462- /// ruler is measured on, through the same [`View`] every box is drawn2872+ /// ruler is measured on, through the same [`Scale`] every box is drawn
2463 /// through, so a zoomed-in panel answers with the frame under the pointer2873 /// through, so a zoomed-in panel answers with the frame under the pointer
2464 /// and not with the one that would have been there unzoomed. The one2874 /// and not with the one that would have been there unzoomed. The one
2465 /// question a trim, a grab and a drop all ask.2875 /// question a trim, a grab and a drop all ask.
2466 fn frame_under(&self, x: Pixels) -> u32 {2876 fn frame_under(&self, x: Pixels) -> u32 {
2467- let duration = self.drawn_duration();
2468 frame_at(2877 frame_at(
2469- self.view.time_at(frac_along(x, self.ruler.get()), duration),2878+ self.scale.time_at(px_along(x, self.ruler.get())),
2470 self.fps,2879 self.fps,
2471 )2880 )
2472 }2881 }
@@ -2497,39 +2906,13 @@ impl Player {
2497 }) else {2906 }) else {
2498 return clip;2907 return clip;
2499 };2908 };
2500- match trim.edge {2909+ let still = self.session.as_ref().is_some_and(|session| {
2501- // A still grows forward from source frame 0 instead, exactly as
2502- // `Project::trim` writes it: with the in-point clamped at 0 the box
2503- // below would slide left rather than stretch, and the release would
2504- // then commit a wider clip than the drag drew.
2505- Edge::Start
2506- if self.session.as_ref().is_some_and(|session| {
2507 session2910 session
2508 .sources()2911 .sources()
2509 .get(clip.source)2912 .get(clip.source)
2510 .is_some_and(|s| engine::is_image(&s.path))2913 .is_some_and(|s| engine::is_image(&s.path))
2511- }) =>2914+ });
2512- {2915+ trimmed_clip(clip, trim.edge, trim.to, still)
2513- Clip {
2514- in_frame: 0,
2515- out_frame: clip.end().saturating_sub(trim.to).max(1),
2516- start: trim.to,
2517- ..clip
2518- }
2519- }
2520- // The in-point follows the head, exactly as `Project::trim` moves
2521- // it: what stays on screen plays what it always played.
2522- Edge::Start => Clip {
2523- in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
2524- .clamp(0, i64::from(clip.out_frame - 1)) as u32,
2525- start: trim.to,
2526- ..clip
2527- },
2528- Edge::End => Clip {
2529- out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
2530- ..clip
2531- },
2532- }
2533 }2916 }
2534 2917
2535 /// How long the timeline is *drawn* as: its own length, and while a tail is2918 /// How long the timeline is *drawn* as: its own length, and while a tail is
@@ -2537,6 +2920,15 @@ impl Player {
2537 /// at the last frame has nowhere to put a pointer that means "longer", so2920 /// at the last frame has nowhere to put a pointer that means "longer", so
2538 /// without this the last clip on the timeline could be pulled in and never2921 /// without this the last clip on the timeline could be pulled in and never
2539 /// let back out.2922 /// let back out.
2923+ ///
2924+ /// Scroll room only, now that a second is an absolute number of pixels
2925+ /// ([`Scale`]): the extra length loosens [`View::settled`]'s clamp, which is
2926+ /// where the pixels past the last frame come from, and moves no box by a
2927+ /// pixel. It is still the *only* headroom at the tail -- zoomed in against
2928+ /// the end, that clamp pins the bed's right edge to the duration and an
2929+ /// End-trim of the last clip would have nowhere to be dragged to. What it
2930+ /// must not do is be read as a length anyone is told: the timecode reads
2931+ /// `PlaybackSession::timeline_duration` for exactly that reason.
2540 fn drawn_duration(&self) -> f64 {2932 fn drawn_duration(&self) -> f64 {
2541 let Some(session) = &self.session else {2933 let Some(session) = &self.session else {
2542 return 0.;2934 return 0.;
@@ -2553,12 +2945,11 @@ impl Player {
2553 }2945 }
2554 }2946 }
2555 2947
2556- /// Where the playhead is, as the panel draws it. The clock keeps running2948+ /// Where the playhead is, as the panel draws it: pinned to the out point
2557- /// after the last frame (wall time takes over at audio EOF) while the2949+ /// once playback is done, and clamped to the drawn duration otherwise -- a
2558- /// picture is frozen, so what the UI shows is the clamped one, pinned to2950+ /// tail being dragged draws past the timeline it is about to become.
2559- /// the out-point once playback is done.
2560 fn playhead(&self, duration: f64) -> f64 {2951 fn playhead(&self, duration: f64) -> f64 {
2561- if self.done {2952+ if self.transport() == Transport::Ended {
2562 duration2953 duration
2563 } else {2954 } else {
2564 self.session2955 self.session
@@ -2753,11 +3144,11 @@ impl Player {
2753 self.export_path = PathBuf::new();3144 self.export_path = PathBuf::new();
2754 self.project_path = PathBuf::new();3145 self.project_path = PathBuf::new();
2755 self.fps = 30.;3146 self.fps = 30.;
2756- // No decoder to wait for a frame from: the hint is what shows.3147+ // No decoder to wait for a frame from: the hint is what shows. The
3148+ // transport reads `Stopped` from the session being gone, so there is no
3149+ // end-of-stream state left to clear here.
2757 self.reset_after_reseek();3150 self.reset_after_reseek();
2758 self.pending_seek = false;3151 self.pending_seek = false;
2759- self.eos = false;
2760- self.done = false;
2761 }3152 }
2762 3153
2763 /// One item of a library row's menu, done. Every one of them closes the3154 /// One item of a library row's menu, done. Every one of them closes the
@@ -3126,9 +3517,12 @@ impl Player {
3126 let Some(session) = &self.session else {3517 let Some(session) = &self.session else {
3127 return;3518 return;
3128 };3519 };
3520+ // Clamped to the timeline here rather than in the mapping: there is bed
3521+ // past the last frame now, and a seek out there is a seek to the end.
3129 let t = self3522 let t = self
3130- .view3523+ .scale
3131- .time_at(frac_along(x, self.ruler.get()), session.timeline_duration());3524+ .time_at(px_along(x, self.ruler.get()))
3525+ .clamp(0., session.timeline_duration());
3132 let target = (t * self.fps) as u32;3526 let target = (t * self.fps) as u32;
3133 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {3527 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
3134 self.last_target = target;3528 self.last_target = target;
@@ -3173,11 +3567,11 @@ impl Player {
3173 return;3567 return;
3174 }3568 }
3175 // Nothing to play is a message, not a transport state. An empty3569 // Nothing to play is a message, not a transport state. An empty
3176- // timeline is `done` from its one black frame onward, so the restart3570+ // timeline is [`Transport::Ended`] from its one black frame onward, so
3177- // below would start a clock against a zero-length timeline -- and it is3571+ // the restart below would start a clock against a zero-length timeline
3178- // `done` again by the next repaint, so no later press could ever stop3572+ // -- and it is Ended again by the next repaint, so no later press could
3179- // it: the button would read "Pause" and never pause. A delete can empty3573+ // ever stop it: the button would read "Pause" and never pause. A delete
3180- // the timeline mid-play, and that press must still stop it.3574+ // can empty the timeline mid-play, and that press must still stop it.
3181 if nothing_to_play(self.session.as_ref()) {3575 if nothing_to_play(self.session.as_ref()) {
3182 match self.session.as_mut().filter(|s| s.is_playing()) {3576 match self.session.as_mut().filter(|s| s.is_playing()) {
3183 Some(session) => session.pause(),3577 Some(session) => session.pause(),
@@ -3186,17 +3580,27 @@ impl Player {
3186 cx.notify();3580 cx.notify();
3187 return;3581 return;
3188 }3582 }
3189- if self.done {3583+ match self.transport() {
3584+ // Nothing open: the button is dimmed and the key says nothing.
3585+ Transport::Stopped => {}
3586+ // Back to the top and away, for the key and the button alike --
3587+ // whichever asked, the transport was showing Play.
3588+ state if state.restarts() => {
3190 self.seek(0., cx);3589 self.seek(0., cx);
3191 if let Some(session) = &mut self.session {3590 if let Some(session) = &mut self.session {
3192 session.play();3591 session.play();
3193 }3592 }
3194- } else if let Some(session) = &mut self.session {3593+ }
3594+ _ => {
3595+ if let Some(session) = &mut self.session {
3195 session.toggle();3596 session.toggle();
3196- // Past EOF nothing else asks for a repaint.3597+ // A paused timeline animates nothing; this is the repaint
3598+ // that puts the new glyph up.
3197 cx.notify();3599 cx.notify();
3198 }3600 }
3199 }3601 }
3602+ }
3603+ }
3200 3604
3201 /// The export that owns the UI, if any. A cancelled one does not: it has3605 /// The export that owns the UI, if any. A cancelled one does not: it has
3202 /// its own copy of the edit list and owes only its own cleanup.3606 /// its own copy of the edit list and owes only its own cleanup.
@@ -3428,11 +3832,9 @@ impl Render for Player {
3428 window.set_window_title(&title);3832 window.set_window_title(&title);
3429 self.titled = title;3833 self.titled = title;
3430 }3834 }
3431- // No shadow flag: the clock is the only truth about play state.3835+ // No shadow flag: the session is the only truth about play state, and
3432- let playing = self3836+ // [`Player::transport`] is the one place it is read.
3433- .session3837+ let state = self.transport();
3434- .as_ref()
3435- .is_some_and(PlaybackSession::is_playing);
3436 // A paused timeline has nothing to animate; the toggle handlers notify,3838 // A paused timeline has nothing to animate; the toggle handlers notify,
3437 // which is what starts the loop again. A paused seek keeps the loop3839 // which is what starts the loop again. A paused seek keeps the loop
3438 // running by itself until `pump` has the frame it asked for. An export3840 // running by itself until `pump` has the frame it asked for. An export
@@ -3440,7 +3842,7 @@ impl Render for Player {
3440 // the screen on a repaint. A notice does not: it waits to be dismissed3842 // the screen on a repaint. A notice does not: it waits to be dismissed
3441 // rather than for a clock, so keeping the loop alive for it would spin3843 // rather than for a clock, so keeping the loop alive for it would spin
3442 // the GPU until someone answered it.3844 // the GPU until someone answered it.
3443- if (playing && !self.done) || self.pending_seek || self.export.is_some() {3845+ if state.is_playing() || self.pending_seek || self.export.is_some() {
3444 window.request_animation_frame();3846 window.request_animation_frame();
3445 }3847 }
3446 3848
@@ -3453,7 +3855,7 @@ impl Render for Player {
3453 // edit that shortens the timeline moves the far end of the view, and a3855 // edit that shortens the timeline moves the far end of the view, and a
3454 // playhead that has run off the bed pulls the view after it -- which is3856 // playhead that has run off the bed pulls the view after it -- which is
3455 // what makes a zoomed-in timeline scroll while it plays.3857 // what makes a zoomed-in timeline scroll while it plays.
3456- self.view = self.view.following(position, duration, self.fps);3858+ self.scale = self.view().following(position);
3457 3859
3458 div()3860 div()
3459 .track_focus(&self.focus)3861 .track_focus(&self.focus)
@@ -3574,31 +3976,55 @@ impl Render for Player {
3574 // cannot move at all, and every one of them is listed in the3976 // cannot move at all, and every one of them is listed in the
3575 // keys menu (keymap.rs `FIXED`) rather than being a secret.3977 // keys menu (keymap.rs `FIXED`) rather than being a secret.
3576 if this.eq_open.is_some() {3978 if this.eq_open.is_some() {
3979+ // Shift makes the two horizontal keys Q instead of
3980+ // frequency: both are the *width* of the same hump, so they
3981+ // sit on the same axis rather than on two keys nobody would
3982+ // guess. Wider is a lower Q, which is why left widens.
3983+ let shift = event.keystroke.modifiers.shift;
3577 if key == ESCAPE {3984 if key == ESCAPE {
3578 // Nothing to undo: every change is already at the clip,3985 // Nothing to undo: every change is already at the clip,
3579 // and undo is undo's own key.3986 // and undo is undo's own key.
3580 this.eq_open = None;3987 this.eq_open = None;
3581 this.eq_dragging = false;3988 this.eq_dragging = false;
3582 } else if key == "up" {3989 } else if key == "up" {
3583- this.nudge_band(EQ_STEP, cx);3990+ this.nudge_band(|b| b.gain_db += EQ_STEP, cx);
3584 } else if key == "down" {3991 } else if key == "down" {
3585- this.nudge_band(-EQ_STEP, cx);3992+ this.nudge_band(|b| b.gain_db -= EQ_STEP, cx);
3993+ } else if key == "left" && shift {
3994+ this.nudge_band(|b| b.q /= EQ_Q_STEP, cx);
3995+ } else if key == "right" && shift {
3996+ this.nudge_band(|b| b.q *= EQ_Q_STEP, cx);
3997+ } else if key == "left" {
3998+ this.nudge_band(|b| b.freq_hz /= EQ_FREQ_STEP, cx);
3999+ } else if key == "right" {
4000+ this.nudge_band(|b| b.freq_hz *= EQ_FREQ_STEP, cx);
3586 } else if key == "r" {4001 } else if key == "r" {
3587 for band in &mut this.eq_params.bands {4002 for band in &mut this.eq_params.bands {
3588 band.gain_db = 0.;4003 band.gain_db = 0.;
3589 }4004 }
3590 this.commit_eq(cx);4005 this.commit_eq(cx);
4006+ } else if key == "f" {
4007+ // This one band back to flat, which is the undo of one
4008+ // hand movement -- `r` is the undo of the whole card.
4009+ this.nudge_band(|b| b.gain_db = 0., cx);
4010+ } else if key == "a" {
4011+ this.add_band(cx);
4012+ } else if key == "x" {
4013+ this.remove_band(cx);
3591 } else if key == "s" {4014 } else if key == "s" {
3592 // The analyser off and on. Nothing is committed: it is4015 // The analyser off and on. Nothing is committed: it is
3593 // what the card *shows*, so it survives no further than4016 // what the card *shows*, so it survives no further than
3594 // this window.4017 // this window.
3595 this.eq_spectrum = !this.eq_spectrum;4018 this.eq_spectrum = !this.eq_spectrum;
3596 } else if let Ok(digit) = key.parse::<usize>() {4019 } else if let Ok(digit) = key.parse::<usize>() {
3597- // 1-based, as the rows are numbered on screen; a digit4020+ // As the keys are laid out: 1-9 then 0 for the tenth,
3598- // past the last band picks nothing rather than panics.4021+ // which is the cap ([`EQ_BANDS_MAX`]). A digit past the
3599- if let Some(band) = digit.checked_sub(1)4022+ // last band picks nothing rather than panics.
3600- && band < this.eq_params.bands.len()4023+ let band = match digit {
3601- {4024+ 0 => EQ_BANDS_MAX - 1,
4025+ n => n - 1,
4026+ };
4027+ if band < this.eq_params.bands.len() {
3602 this.eq_band = band;4028 this.eq_band = band;
3603 }4029 }
3604 }4030 }
@@ -3702,9 +4128,12 @@ impl Render for Player {
3702 // Both menus, taken rather than short-circuited: the library's4128 // Both menus, taken rather than short-circuited: the library's
3703 // one names a row the edits below can remove, so it closes on a4129 // one names a row the edits below can remove, so it closes on a
3704 // stroke exactly as the clip menu does.4130 // stroke exactly as the clip menu does.
4131+ // A choice list goes the same way and for the same reason: it
4132+ // names a clip index too, and escape is the way out of it.
3705 let clip_menu = this.context_menu.take().is_some();4133 let clip_menu = this.context_menu.take().is_some();
3706 let row_menu = this.library_menu.take().is_some();4134 let row_menu = this.library_menu.take().is_some();
3707- if clip_menu || row_menu {4135+ let list = this.picker.take().is_some();
4136+ if clip_menu || row_menu || list {
3708 cx.notify();4137 cx.notify();
3709 if key == ESCAPE {4138 if key == ESCAPE {
3710 return;4139 return;
@@ -3737,6 +4166,26 @@ impl Render for Player {
3737 }4166 }
3738 }4167 }
3739 }))4168 }))
4169+ // A drop event carries no path of its own -- gpui only tells the
4170+ // target that something landed -- so the line that promises where
4171+ // it will land is fed by the drag's own moves, which do carry the
4172+ // pointer (gpui div.rs:282). On the root, because a drag crosses
4173+ // the window: it starts on a clip or on a library row and ends over
4174+ // a lane, and only an ancestor of both hears all of it.
4175+ .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| {
4176+ // The clip the payload named, wherever an edit mid-drag has
4177+ // since put it ([`Player::dragged`]): the line has to promise a
4178+ // landing for the take actually in the hand.
4179+ let drag = *event.drag(cx);
4180+ if let Some(idx) = this.dragged(&drag) {
4181+ this.preview_drop(drag.lane, idx, event.event.position.x, cx);
4182+ }
4183+ }))
4184+ .on_drag_move(
4185+ cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| {
4186+ this.preview_place(event.event.position.x, cx);
4187+ }),
4188+ )
3740 // Scrubbing is tracked on the root because the pointer leaves the4189 // Scrubbing is tracked on the root because the pointer leaves the
3741 // 6 px ruler on the first drag and its own listeners then stop4190 // 6 px ruler on the first drag and its own listeners then stop
3742 // firing; the root's hitbox is the whole window.4191 // firing; the root's hitbox is the whole window.
@@ -3745,7 +4194,7 @@ impl Render for Player {
3745 // the equalizer drag is tracked here for the ruler's reason.4194 // the equalizer drag is tracked here for the ruler's reason.
3746 if this.eq_dragging {4195 if this.eq_dragging {
3747 if event.pressed_button == Some(MouseButton::Left) {4196 if event.pressed_button == Some(MouseButton::Left) {
3748- this.drag_band(event.position.y, cx);4197+ this.drag_band(event.position, cx);
3749 } else {4198 } else {
3750 // Released outside the window: the up below never came,4199 // Released outside the window: the up below never came,
3751 // so this is where the gesture ends -- and it still owes4200 // so this is where the gesture ends -- and it still owes
@@ -3815,7 +4264,7 @@ impl Render for Player {
3815 if std::mem::take(&mut this.eq_dragging) {4264 if std::mem::take(&mut this.eq_dragging) {
3816 // The release lands exactly, then the gesture is written4265 // The release lands exactly, then the gesture is written
3817 // once -- the append-only table's whole reason.4266 // once -- the append-only table's whole reason.
3818- this.drag_band(event.position.y, cx);4267+ this.drag_band(event.position, cx);
3819 this.commit_eq(cx);4268 this.commit_eq(cx);
3820 return;4269 return;
3821 }4270 }
@@ -3905,7 +4354,7 @@ impl Render for Player {
3905 // Above the panel and only when there is one to show, so it costs4354 // Above the panel and only when there is one to show, so it costs
3906 // the picture nothing the rest of the time.4355 // the picture nothing the rest of the time.
3907 .children(self.notice_bar(cx))4356 .children(self.notice_bar(cx))
3908- .child(self.panel(position, duration, playing, cx))4357+ .child(self.panel(position, duration, state, cx))
3909 // Over the panel it was opened on, and under the cards: it is only4358 // Over the panel it was opened on, and under the cards: it is only
3910 // ever up while neither of them is (`modal`).4359 // ever up while neither of them is (`modal`).
3911 .children(self.context_card(window.viewport_size(), cx))4360 .children(self.context_card(window.viewport_size(), cx))
@@ -3917,11 +4366,14 @@ impl Render for Player {
3917 // column, and only one of the two is ever up.4366 // column, and only one of the two is ever up.
3918 .children(self.keys_overlay(cx))4367 .children(self.keys_overlay(cx))
3919 .children(self.export_card(window.viewport_size(), cx))4368 .children(self.export_card(window.viewport_size(), cx))
3920- .children(self.eq_card(cx))4369+ .children(self.eq_card(window.viewport_size(), cx))
3921 .children(self.color_card(cx))4370 .children(self.color_card(cx))
3922 .children(self.speed_card(cx))4371 .children(self.speed_card(cx))
3923 .children(self.silence_card(cx))4372 .children(self.silence_card(cx))
3924 .children(self.mix_card(cx))4373 .children(self.mix_card(cx))
4374+ // Last, so it floats over whatever opened it -- the panel's button
4375+ // or a clip menu -- rather than under it.
4376+ .children(self.picker_card(window.viewport_size(), cx))
3925 }4377 }
3926 }4378 }
3927 4379
@@ -4226,21 +4678,22 @@ impl Player {
4226 &self,4678 &self,
4227 position: f64,4679 position: f64,
4228 duration: f64,4680 duration: f64,
4229- playing: bool,4681+ state: Transport,
4230 cx: &mut Context<Self>,4682 cx: &mut Context<Self>,
4231 ) -> impl IntoElement {4683 ) -> impl IntoElement {
4232- // Where the playhead is *on the bed*, which at the fit is where along4684+ // Where the playhead is *on the bed*, in pixels from its left edge.
4233- // the timeline it is and zoomed in is where along the visible slice.4685+ // Clamped to the bed because it is drawn as a width as well as an
4234- // Clamped because it is drawn as a width as well as an offset, and the4686+ // offset, and the view follows the playhead anyway, so it is never off
4235- // view follows the playhead anyway, so it is never off the bed.4687+ // the bed for long.
4236- let filled = self.view.frac_at(position, duration).clamp(0., 1.);4688+ let bed_w = f32::from(self.ruler.get().size.width);
4689+ let filled = self.scale.px_at(position).clamp(0., bed_w);
4237 // An export owns the hint slot and the ruler while it runs: the4690 // An export owns the hint slot and the ruler while it runs: the
4238 // percentage and the accent bar are the same number, so the playhead4691 // percentage and the accent bar are the same number, so the playhead
4239 // fill doubles as the progress bar for free.4692 // fill doubles as the progress bar for free.
4240 let exporting = self.exporting().is_some();4693 let exporting = self.exporting().is_some();
4241 // Everything but Import and Keys needs a timeline to act on: with none4694 // Everything but Import and Keys needs a timeline to act on: with none
4242 // open they are dimmed rather than silently doing nothing.4695 // open they are dimmed rather than silently doing nothing.
4243- let live = self.session.is_some() && !exporting;4696+ let live = state != Transport::Stopped && !exporting;
4244 // The project's own picture size, for the button that cycles it: read4697 // The project's own picture size, for the button that cycles it: read
4245 // per render like everything else here, so a cycle shows on the button4698 // per render like everything else here, so a cycle shows on the button
4246 // that made it.4699 // that made it.
@@ -4256,7 +4709,7 @@ impl Player {
4256 // closure would hold it for as long as the iterator lives.4709 // closure would hold it for as long as the iterator lives.
4257 let mut rows = Vec::new();4710 let mut rows = Vec::new();
4258 for &lane in &lanes {4711 for &lane in &lanes {
4259- rows.push(self.lane_row(lane, duration, filled, cx));4712+ rows.push(self.lane_row(lane, filled, cx));
4260 }4713 }
4261 let (hint, filled) = if let Some(export) = self.exporting() {4714 let (hint, filled) = if let Some(export) = self.exporting() {
4262 let progress = export.progress();4715 let progress = export.progress();
@@ -4300,7 +4753,7 @@ impl Player {
4300 // of this line is what a narrow window truncates.4753 // of this line is what a narrow window truncates.
4301 (4754 (
4302 join_detail(4755 join_detail(
4303- &self.live_decode(position, playing),4756+ &self.live_decode(position, state.is_playing()),
4304 &format!(4757 &format!(
4305 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \4758 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
4306 import",4759 import",
@@ -4339,9 +4792,9 @@ impl Player {
4339 .overflow_x_scroll()4792 .overflow_x_scroll()
4340 .child(control(4793 .child(control(
4341 "transport",4794 "transport",
4342- Some(transport_glyph(playing).into_any_element()),4795+ Some(transport_glyph(state).into_any_element()),
4343- if playing { "Pause" } else { "Play" },4796+ if state.is_playing() { "Pause" } else { "Play" },
4344- if nothing_to_play(self.session.as_ref()) && !playing {4797+ if nothing_to_play(self.session.as_ref()) && !state.is_playing() {
4345 format!("{} — put a clip on a lane first", key(ActionId::Play))4798 format!("{} — put a clip on a lane first", key(ActionId::Play))
4346 } else {4799 } else {
4347 key(ActionId::Play)4800 key(ActionId::Play)
@@ -4351,7 +4804,7 @@ impl Player {
4351 // against nothing (the key press answers with the4804 // against nothing (the key press answers with the
4352 // notice). Still live while it *is* playing: a delete4805 // notice). Still live while it *is* playing: a delete
4353 // can empty the timeline mid-play and that has to stop.4806 // can empty the timeline mid-play and that has to stop.
4354- live && (playing || !nothing_to_play(self.session.as_ref())),4807+ live && (state.is_playing() || !nothing_to_play(self.session.as_ref())),
4355 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),4808 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
4356 ))4809 ))
4357 .child(separator())4810 .child(separator())
@@ -4448,35 +4901,38 @@ impl Player {
4448 ))4901 ))
4449 .child(separator())4902 .child(separator())
4450 // The size every clip is composed onto, which is also the4903 // The size every clip is composed onto, which is also the
4451- // size the export comes out at: the one project setting a4904+ // size the export comes out at. Five sizes, so a click opens
4452- // stroke used to be the only way to. Cycles exactly as the4905+ // the list of them with this one marked and picks whichever
4453- // key does, and says where it is now rather than opening a4906+ // was meant: a button that stepped one on per press made the
4454- // list to close again.4907+ // user click round the ladder to get back to where they
4908+ // were. The stroke still steps, for the hand already on it.
4455 .child(control(4909 .child(control(
4456 "resolution",4910 "resolution",
4457 None,4911 None,
4458 resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")),4912 resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")),
4459 match resolution {4913 match resolution {
4460 Some((w, h)) => format!(4914 Some((w, h)) => format!(
4461- "{} — the project is {w}x{h}; cycles source → 2160p → 1080p → 720p → 480p",4915+ "click to pick a size — the project is {w}x{h}; {} steps to the next",
4462 key(ActionId::Resolution)4916 key(ActionId::Resolution)
4463 ),4917 ),
4464 None => format!("{} — open a file first", key(ActionId::Resolution)),4918 None => format!("{} — open a file first", key(ActionId::Resolution)),
4465 },4919 },
4466 live,4920 live,
4467- cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(cx)),4921+ cx.listener(|this, event: &ClickEvent, _, cx| {
4922+ this.open_picker(Pick::Resolution, event.position(), cx)
4923+ }),
4468 ))4924 ))
4469 // How much of the timeline the panel below is showing --4925 // How much of the timeline the panel below is showing --
4470 // beside the resolution, since neither of them edits4926 // beside the resolution, since neither of them edits
4471 // anything: they are both what is being looked at. The4927 // anything: they are both what is being looked at. The
4472- // middle one reads as the state (1.0x is the whole4928+ // middle one says how much of it is on the bed, and is the
4473- // timeline) and is the way back to it.4929+ // way back to the whole of it.
4474 .child(control(4930 .child(control(
4475 "zoom-out",4931 "zoom-out",
4476 None,4932 None,
4477 "−",4933 "−",
4478 format!(4934 format!(
4479- "{} — show more of the timeline; stops at the whole of it",4935+ "{} — show more of the timeline; stops at four hours on the bed",
4480 key(ActionId::ZoomOut)4936 key(ActionId::ZoomOut)
4481 ),4937 ),
4482 live,4938 live,
@@ -4487,13 +4943,17 @@ impl Player {
4487 .child(control(4943 .child(control(
4488 "zoom-fit",4944 "zoom-fit",
4489 None,4945 None,
4490- format!("{:.1}x", self.view.zoom),4946+ // How much timeline is on the bed, not a multiple of
4947+ // "the whole of it": the scale no longer knows what the
4948+ // whole of it is, and a number that changed on every
4949+ // import was a number that lied.
4950+ span_label(self.view().span()),
4491 format!(4951 format!(
4492 "{} — fit the whole timeline; showing {} to {}",4952 "{} — fit the whole timeline; showing {} to {}",
4493 key(ActionId::ZoomFit),4953 key(ActionId::ZoomFit),
4494- timecode(self.view.start, self.fps),4954+ timecode(self.scale.start, self.fps),
4495 timecode(4955 timecode(
4496- (self.view.start + self.view.span(duration)).min(duration),4956+ (self.scale.start + self.view().span()).min(duration),
4497 self.fps4957 self.fps
4498 )4958 )
4499 ),4959 ),
@@ -4511,6 +4971,25 @@ impl Player {
4511 live,4971 live,
4512 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),4972 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
4513 ))4973 ))
4974+ // The magnet, beside the zoom for the zoom's own reason: it
4975+ // changes nothing on the timeline, it changes how the hand
4976+ // meets it. The label is the state, as the volume's is --
4977+ // a toggle that looks the same either way says nothing.
4978+ .child(control(
4979+ "snap",
4980+ None,
4981+ if self.snap { "Snap" } else { "No snap" },
4982+ format!(
4983+ "{} — {}",
4984+ key(ActionId::ToggleSnap),
4985+ match self.snap {
4986+ true => "drags and trims land on clip edges, the playhead and the start",
4987+ false => "drags and trims land exactly where the hand leaves them",
4988+ }
4989+ ),
4990+ live,
4991+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)),
4992+ ))
4514 // Import is not here: it belongs to the media list it adds4993 // Import is not here: it belongs to the media list it adds
4515 // to, and two doors into one action is a question about4994 // to, and two doors into one action is a question about
4516 // which one is the real one.4995 // which one is the real one.
@@ -4561,8 +5040,10 @@ impl Player {
4561 .child(control(5040 .child(control(
4562 "keys",5041 "keys",
4563 None,5042 None,
4564- "Keys",5043+ "Actions",
4565- "show and change the keybindings".to_string(),5044+ // The pointer's way to every action there is, including
5045+ // the ones no button here has room for.
5046+ "do any action, or change the key that does it".to_string(),
4566 !exporting,5047 !exporting,
4567 cx.listener(|this, _: &ClickEvent, _, cx| {5048 cx.listener(|this, _: &ClickEvent, _, cx| {
4568 this.keys_open = !this.keys_open;5049 this.keys_open = !this.keys_open;
@@ -4581,10 +5062,20 @@ impl Player {
4581 .gap(px(12.))5062 .gap(px(12.))
4582 // Fixed width and one line: changing digits must not push5063 // Fixed width and one line: changing digits must not push
4583 // the row around, nor wrap and change its height.5064 // the row around, nor wrap and change its height.
5065+ // The timeline's own length, never the drawn one: a tail
5066+ // being dragged inflates the bed to the room that edge has
5067+ // ([`Player::drawn_duration`]), and for a still that room is
5068+ // ten minutes -- a total that jumped to 10:00:00 the moment
5069+ // a picture's edge was pressed, and back on release.
4584 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(5070 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
4585 "{} / {}",5071 "{} / {}",
4586 timecode(position, self.fps),5072 timecode(position, self.fps),
4587- timecode(duration, self.fps)5073+ timecode(
5074+ self.session
5075+ .as_ref()
5076+ .map_or(0., PlaybackSession::timeline_duration),
5077+ self.fps
5078+ )
4588 )))5079 )))
4589 .child(5080 .child(
4590 div()5081 div()
@@ -4644,7 +5135,7 @@ impl Player {
4644 if dy == 0. {5135 if dy == 0. {
4645 return;5136 return;
4646 }5137 }
4647- let anchor = frac_along(event.position.x, this.ruler.get());5138+ let anchor = px_along(event.position.x, this.ruler.get());
4648 let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP };5139 let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP };
4649 this.zoom(factor, Some(anchor), cx);5140 this.zoom(factor, Some(anchor), cx);
4650 },5141 },
@@ -4666,7 +5157,7 @@ impl Player {
4666 .child(5157 .child(
4667 div()5158 div()
4668 .h_full()5159 .h_full()
4669- .w(relative(filled))5160+ .w(px(filled))
4670 .rounded(px(3.))5161 .rounded(px(3.))
4671 .bg(rgb(ACCENT)),5162 .bg(rgb(ACCENT)),
4672 ),5163 ),
@@ -4772,23 +5263,30 @@ impl Player {
4772 ctrl: false,5263 ctrl: false,
4773 }5264 }
4774 .pretty();5265 .pretty();
4775- // Every stroke that works, under its heading, and both halves of the5266+ // Every action there is, under its heading, and the strokes the modal
4776- // list come from the registry: one row per action -- an action with two5267+ // cards answer to beside them -- `keys_rows` is the whole of the order
4777- // strokes reads as one line ("x or delete") and a rebind replaces that5268+ // and every word in it comes off the registry.
4778- // whole set -- then the strokes the modal cards answer to, which are5269+ //
4779- // shown but not offered, because nothing may unbind the way out.5270+ // A row is two targets, not one: its label *does* the action, which is
5271+ // the pointer's way to the ones no button carries, and its stroke
5272+ // changes that stroke. An action with two strokes reads as one line
5273+ // ("x or delete") and a rebind replaces that whole set.
4780 let mut rows: Vec<AnyElement> = Vec::new();5274 let mut rows: Vec<AnyElement> = Vec::new();
4781- for category in keymap::Category::ALL {5275+ let row = || {
4782- let actions = ActionId::ALL
4783- .into_iter()
4784- .enumerate()
4785- .filter(|(_, a)| a.category() == category);
4786- let fixed = keymap::FIXED.iter().filter(|f| f.category == category);
4787- let mut headed = false;
4788- let mut head = |rows: &mut Vec<AnyElement>| {
4789- if !std::mem::replace(&mut headed, true) {
4790- rows.push(
4791 div()5276 div()
5277+ .flex()
5278+ // The floor, not the height: a row that needed two lines
5279+ // would otherwise paint over the one under it.
5280+ .min_h(px(KEYS_ROW_H))
5281+ .items_center()
5282+ .justify_between()
5283+ .gap(px(12.))
5284+ .px(px(6.))
5285+ .rounded(px(3.))
5286+ };
5287+ for (i, key_row) in keys_rows().into_iter().enumerate() {
5288+ rows.push(match key_row {
5289+ KeyRow::Head(category) => div()
4792 .flex_none()5290 .flex_none()
4793 .px(px(6.))5291 .px(px(6.))
4794 .pt(px(4.))5292 .pt(px(4.))
@@ -4796,59 +5294,84 @@ impl Player {
4796 .text_color(rgb(INK_DIM))5294 .text_color(rgb(INK_DIM))
4797 .child(category.label())5295 .child(category.label())
4798 .into_any_element(),5296 .into_any_element(),
4799- );5297+ KeyRow::Act(action) => {
4800- }
4801- };
4802- for (i, action) in actions {
4803- head(&mut rows);
4804 let capturing = self.rebinding == Some(action);5298 let capturing = self.rebinding == Some(action);
5299+ // Why the label half will not answer, if it will not: the
5300+ // registry's one answer, the same the clip menu dims by.
5301+ let refusal = self.enable(action, None);
4805 let out = out.clone();5302 let out = out.clone();
4806- rows.push(5303+ row()
5304+ .when(capturing, |d| d.bg(rgb(SELECTED)))
5305+ .child(
5306+ div()
5307+ .id(("do", i))
5308+ .flex_1()
5309+ .min_w(px(0.))
5310+ .flex()
5311+ .min_h(px(KEYS_ROW_H))
5312+ .items_center()
5313+ .child(action.label())
5314+ // The reason rides on the label rather than in
5315+ // the stroke column, which the rebind half
5316+ // needs whatever the editor's state is: an
5317+ // action nobody can ask for right now is still
5318+ // one whose key may be changed.
5319+ .when_some(refusal.why(), |d, why| {
5320+ let why: SharedString = why.into();
5321+ d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into())
5322+ })
5323+ .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed())
5324+ .when(refusal.yes(), |d| {
5325+ d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click(
5326+ cx.listener(move |this, _: &ClickEvent, _, cx| {
5327+ // The card goes first: several of
5328+ // these open a card of their own,
5329+ // and every edit moves the indices
5330+ // the menus are holding.
5331+ this.keys_open = false;
5332+ this.rebinding = None;
5333+ this.act(action, cx);
5334+ cx.notify();
5335+ }),
5336+ )
5337+ }),
5338+ )
5339+ .child(
5340+ // ponytail: the column is as wide as the stroke it
5341+ // prints, so a one-character chord gives this half a
5342+ // hit area under the 24px WCAG 2.5.8 floor -- tall
5343+ // enough, narrow. Upgrade: a min_w of HIT_MIN here.
4807 div()5344 div()
4808 .id(("bind", i))5345 .id(("bind", i))
5346+ .flex_none()
4809 .flex()5347 .flex()
4810- // The floor, not the height: a row that needed two lines
4811- // would otherwise paint over the one under it.
4812 .min_h(px(KEYS_ROW_H))5348 .min_h(px(KEYS_ROW_H))
4813 .items_center()5349 .items_center()
4814- .justify_between()
4815- .gap(px(12.))
4816- .px(px(6.))
4817- .rounded(px(3.))
4818 .cursor_pointer()5350 .cursor_pointer()
4819 .hover(|s| s.bg(rgb(HOVER)))5351 .hover(|s| s.bg(rgb(HOVER)))
4820- .when(capturing, |d| d.bg(rgb(SELECTED)))
4821 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {5352 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4822 this.rebinding = Some(action);5353 this.rebinding = Some(action);
4823 cx.notify();5354 cx.notify();
4824 }))5355 }))
4825- .child(action.label())
4826 .child(if capturing {5356 .child(if capturing {
4827 div()5357 div()
4828 .text_color(rgb(INK_DIM))5358 .text_color(rgb(INK_DIM))
4829 .child(format!("press a key — {out} cancels"))5359 .child(format!("press a key — {out} cancels"))
4830 } else {5360 } else {
4831 div().child(self.keymap.display(action))5361 div().child(self.keymap.display(action))
4832- })5362+ }),
4833- .into_any_element(),5363+ )
4834- );5364+ .into_any_element()
4835 }5365 }
4836- for f in fixed {5366+ KeyRow::Fixed(f) => {
4837- head(&mut rows);5367+ let f = &keymap::FIXED[f];
4838- rows.push(5368+ row()
4839- div()
4840- .flex()
4841- .min_h(px(KEYS_ROW_H))
4842- .items_center()
4843- .justify_between()
4844- .gap(px(12.))
4845- .px(px(6.))
4846 .child(f.label)5369 .child(f.label)
4847 // Dim, and no hover: this one is not a row you can click.5370 // Dim, and no hover: this one is not a row you can click.
4848 .child(div().text_color(rgb(INK_DIM)).child(f.chord))5371 .child(div().text_color(rgb(INK_DIM)).child(f.chord))
4849- .into_any_element(),5372+ .into_any_element()
4850- );
4851 }5373 }
5374+ });
4852 }5375 }
4853 Some(5376 Some(
4854 div()5377 div()
@@ -4875,7 +5398,7 @@ impl Player {
4875 // Title and instruction are two children, never one5398 // Title and instruction are two children, never one
4876 // wrapping line: a fixed-height slot whose text wrapped5399 // wrapping line: a fixed-height slot whose text wrapped
4877 // painted its second line over the first row.5400 // painted its second line over the first row.
4878- .child(div().flex_none().px(px(6.)).child("Keybindings"))5401+ .child(div().flex_none().px(px(6.)).child("Actions & keys"))
4879 // One status line, under the title where the eye starts.5402 // One status line, under the title where the eye starts.
4880 // A refusal takes it over -- it is the more urgent of the5403 // A refusal takes it over -- it is the more urgent of the
4881 // two, and the notice bar it would otherwise appear in is5404 // two, and the notice bar it would otherwise appear in is
@@ -4893,7 +5416,10 @@ impl Player {
4893 .child(5416 .child(
4894 self.notice5417 self.notice
4895 .clone()5418 .clone()
4896- .unwrap_or_else(|| "click a row, then press a key".into()),5419+ .unwrap_or_else(|| {
5420+ "click an action to do it · click its key to change it"
5421+ .into()
5422+ }),
4897 ),5423 ),
4898 )5424 )
4899 // Capped and scrolling rather than as tall as the action5425 // Capped and scrolling rather than as tall as the action
@@ -5329,20 +5855,28 @@ impl Player {
5329 }5855 }
5330 5856
5331 /// The equalizer of one audio clip: its frequency response drawn as a5857 /// The equalizer of one audio clip: its frequency response drawn as a
5332- /// curve, a handle per band sitting on it, and a row that flattens them5858+ /// curve, a handle per band sitting on it, each band's own bell under the
5333- /// all. The curve is the clip's actual filter (`EqParams::response_db`5859+ /// sum, and a row that reads and moves the picked band's three numbers. The
5334- /// reads the coefficients the samples go through), and it is redrawn on5860+ /// curve is the clip's actual filter (`EqParams::response_db` reads the
5335- /// every pointer sample of a drag, so the shape bends under the hand.5861+ /// coefficients the samples go through), and it is redrawn on every pointer
5862+ /// sample of a drag, so the shape bends under the hand.
5336 ///5863 ///
5337- /// The same scrim and width as the other two cards, and the same plain divs5864+ /// Wider than the other cards and wider still on a bigger window
5338- /// -- nothing here takes focus, so the root keeps the keyboard and the5865+ /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
5339- /// card's own strokes (`1`–`5`, up, down, `r`) reach it.5866+ /// of the row-shaped cards have any use for. The same scrim and the same
5867+ /// plain divs -- nothing here takes focus, so the root keeps the keyboard
5868+ /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`,
5869+ /// `s`) reach it.
5340 ///5870 ///
5341 /// Every change is written at the clip as it is made5871 /// Every change is written at the clip as it is made
5342 /// ([`Player::commit_eq`]), so what the card shows is always what is5872 /// ([`Player::commit_eq`]), so what the card shows is always what is
5343 /// playing: there is no OK button to forget, and closing it changes5873 /// playing: there is no OK button to forget, and closing it changes
5344 /// nothing. What takes a curve back off is undo, like every other edit.5874 /// nothing. What takes a curve back off is undo, like every other edit.
5345- fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {5875+ fn eq_card(
5876+ &self,
5877+ viewport: Size<Pixels>,
5878+ cx: &mut Context<Self>,
5879+ ) -> Option<impl IntoElement> {
5346 let (lane, idx) = self.eq_open?;5880 let (lane, idx) = self.eq_open?;
5347 // The rate the engine filters this timeline at, so the drawn curve is5881 // The rate the engine filters this timeline at, so the drawn curve is
5348 // the one those coefficients make -- near the top of the axis a 44.1 kHz5882 // the one those coefficients make -- near the top of the axis a 44.1 kHz
@@ -5396,13 +5930,20 @@ impl Player {
5396 .bg(rgb(HOVER_DIM))5930 .bg(rgb(HOVER_DIM))
5397 .cursor_pointer()5931 .cursor_pointer()
5398 // The press picks the band under it *and* is already the first5932 // The press picks the band under it *and* is already the first
5399- // sample of the drag, so a plain click sets a value.5933+ // sample of the drag, so a plain click sets a value. A second click
5934+ // takes that band back to flat instead: the gesture that undoes one
5935+ // handle, with no modifier to remember.
5400 .on_mouse_down(5936 .on_mouse_down(
5401 MouseButton::Left,5937 MouseButton::Left,
5402 cx.listener(|this, event: &MouseDownEvent, _, cx| {5938 cx.listener(|this, event: &MouseDownEvent, _, cx| {
5403 this.eq_band = this.nearest_band(event.position.x);5939 this.eq_band = this.nearest_band(event.position.x);
5940+ if event.click_count >= 2 {
5941+ this.eq_dragging = false;
5942+ this.nudge_band(|b| b.gain_db = 0., cx);
5943+ return;
5944+ }
5404 this.eq_dragging = true;5945 this.eq_dragging = true;
5405- this.drag_band(event.position.y, cx);5946+ this.drag_band(event.position, cx);
5406 }),5947 }),
5407 )5948 )
5408 .child(bounds_probe(self.eq_graph.clone()))5949 .child(bounds_probe(self.eq_graph.clone()))
@@ -5494,7 +6035,7 @@ impl Player {
5494 })6035 })
5495 .child(6036 .child(
5496 div()6037 div()
5497- .w(px(KEYS_W))6038+ .w(px(eq_card_w(f32::from(viewport.width))))
5498 .flex()6039 .flex()
5499 .flex_col()6040 .flex_col()
5500 .gap(px(2.))6041 .gap(px(2.))
@@ -5515,28 +6056,15 @@ impl Player {
5515 .text_size(px(11.))6056 .text_size(px(11.))
5516 .text_color(rgb(INK_DIM))6057 .text_color(rgb(INK_DIM))
5517 .child(self.notice.clone().unwrap_or_else(|| {6058 .child(self.notice.clone().unwrap_or_else(|| {
5518- "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into()6059+ "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()
5519 })),6060 })),
5520 )6061 )
5521 .child(graph)6062 .child(graph)
5522- // Which band the keyboard is holding and what it is set6063+ // Which band the keyboard is holding and every number it
5523- // to: the curve shows the sum, and a band pushed against6064+ // is set to, each with the pair of buttons that moves it:
5524- // one pulling the other way is not readable off it.6065+ // the curve shows the sum, and a band pushed against one
5525- .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(6066+ // pulling the other way is not readable off it.
5526- match picked {6067+ .child(self.eq_numbers(picked, cx))
5527- // Q as well as the two the curve shows: it is
5528- // how wide the hump under the handle is, and
5529- // nothing else on the card says so.
5530- Some(band) => format!(
5531- "{} {} {:+.1} dB — Q {:.2}",
5532- self.eq_band + 1,
5533- band_label(band),
5534- band.gain_db,
5535- band.q
5536- ),
5537- None => "no bands".into(),
5538- },
5539- ))
5540 .child(6068 .child(
5541 div()6069 div()
5542 .mt(px(4.))6070 .mt(px(4.))
@@ -5560,7 +6088,45 @@ impl Player {
5560 }6088 }
5561 this.commit_eq(cx);6089 this.commit_eq(cx);
5562 }))6090 }))
5563- .child("Flatten"),6091+ .child("Flatten all"),
6092+ )
6093+ // The two that change how many bands there are.
6094+ // The engine takes any cascade -- the count was
6095+ // only ever fixed because this card had no way
6096+ // to say otherwise.
6097+ .child(
6098+ div()
6099+ .id("eq-add")
6100+ .flex()
6101+ .flex_1()
6102+ .h(px(CONTROL_H))
6103+ .items_center()
6104+ .justify_center()
6105+ .rounded(px(3.))
6106+ .bg(rgb(CHROME))
6107+ .cursor_pointer()
6108+ .hover(|s| s.bg(rgb(HOVER)))
6109+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
6110+ this.add_band(cx)
6111+ }))
6112+ .child("Add band"),
6113+ )
6114+ .child(
6115+ div()
6116+ .id("eq-remove")
6117+ .flex()
6118+ .flex_1()
6119+ .h(px(CONTROL_H))
6120+ .items_center()
6121+ .justify_center()
6122+ .rounded(px(3.))
6123+ .bg(rgb(CHROME))
6124+ .cursor_pointer()
6125+ .hover(|s| s.bg(rgb(HOVER)))
6126+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
6127+ this.remove_band(cx)
6128+ }))
6129+ .child("Remove band"),
5564 )6130 )
5565 // The analyser's switch, next to the one other6131 // The analyser's switch, next to the one other
5566 // button the card has: `s` does the same, and a6132 // button the card has: `s` does the same, and a
@@ -5595,6 +6161,103 @@ impl Player {
5595 )6161 )
5596 }6162 }
5597 6163
6164+ /// The picked band's three numbers -- where it sits, how far it pushes and
6165+ /// how wide it is -- each beside the pair of buttons that moves it. The
6166+ /// arrows do the same three things, but a value only a key can change is a
6167+ /// value a hand on the pointer cannot reach at all, which is the same reason
6168+ /// [`Player::mbps_steppers`] exists.
6169+ fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context<Self>) -> impl IntoElement {
6170+ let row = div()
6171+ .flex_none()
6172+ .flex()
6173+ .items_center()
6174+ .gap(px(10.))
6175+ .px(px(6.))
6176+ .text_size(px(11.));
6177+ let Some(band) = picked.copied() else {
6178+ return row.child("no bands — a adds one");
6179+ };
6180+ let step = |id: &'static str,
6181+ label: &'static str,
6182+ change: fn(&mut Band),
6183+ cx: &mut Context<Self>| {
6184+ div()
6185+ .id(id)
6186+ .flex()
6187+ .w(px(HIT_MIN))
6188+ .h(px(HIT_MIN))
6189+ .items_center()
6190+ .justify_center()
6191+ .rounded(px(3.))
6192+ .bg(rgb(CHROME))
6193+ .cursor_pointer()
6194+ .hover(|s| s.bg(rgb(HOVER)))
6195+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
6196+ this.nudge_band(change, cx)
6197+ }))
6198+ .child(label)
6199+ };
6200+ let number = |value: String,
6201+ ids: (&'static str, &'static str),
6202+ by: (fn(&mut Band), fn(&mut Band)),
6203+ cx: &mut Context<Self>| {
6204+ div()
6205+ .flex()
6206+ .items_center()
6207+ .gap(px(4.))
6208+ .child(div().child(value))
6209+ .child(step(ids.0, "−", by.0, cx))
6210+ .child(step(ids.1, "+", by.1, cx))
6211+ };
6212+ row.child(format!(
6213+ "Band {} of {}",
6214+ self.eq_band + 1,
6215+ self.eq_params.bands.len()
6216+ ))
6217+ .child(number(
6218+ band_label(&band),
6219+ ("eq-freq-down", "eq-freq-up"),
6220+ (
6221+ |b| b.freq_hz /= EQ_FREQ_STEP,
6222+ |b| b.freq_hz *= EQ_FREQ_STEP,
6223+ ),
6224+ cx,
6225+ ))
6226+ .child(number(
6227+ format!("{:+.1} dB", band.gain_db),
6228+ ("eq-gain-down", "eq-gain-up"),
6229+ (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP),
6230+ cx,
6231+ ))
6232+ // Q is width, so its buttons are labelled by what they *do* to the
6233+ // hump rather than by which way the number goes: a wider band is a
6234+ // smaller Q, and nobody should have to know that to use the card.
6235+ .child(number(
6236+ format!("Q {:.2}", band.q),
6237+ ("eq-q-wider", "eq-q-narrower"),
6238+ (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP),
6239+ cx,
6240+ ))
6241+ .child(
6242+ div()
6243+ .id("eq-flat-band")
6244+ .flex()
6245+ .h(px(HIT_MIN))
6246+ .px(px(8.))
6247+ .items_center()
6248+ .rounded(px(3.))
6249+ .bg(rgb(CHROME))
6250+ .cursor_pointer()
6251+ .hover(|s| s.bg(rgb(HOVER)))
6252+ .on_click(
6253+ cx.listener(|this, _: &ClickEvent, _, cx| {
6254+ this.nudge_band(|b| b.gain_db = 0., cx)
6255+ }),
6256+ )
6257+ .child("Flatten this"),
6258+ )
6259+ }
6260+
5598 /// The colour card: the graded frame's histogram over a row per control,6261 /// The colour card: the graded frame's histogram over a row per control,
5599 /// each row a bar the pointer drags straight to a value -- no stepper6262 /// each row a bar the pointer drags straight to a value -- no stepper
5600 /// buttons, because a slider is a thing to pull, and the arrow keys still6263 /// buttons, because a slider is a thing to pull, and the arrow keys still
@@ -6432,7 +7095,6 @@ impl Player {
6432 let menu = self.context_menu?;7095 let menu = self.context_menu?;
6433 let session = self.session.as_ref()?;7096 let session = self.session.as_ref()?;
6434 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;7097 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
6435- let playhead = frame_at(session.now(), self.fps);
6436 let source = session.sources().get(clip.source).cloned()?;7098 let source = session.sources().get(clip.source).cloned()?;
6437 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);7099 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
6438 let row = |n: usize| {7100 let row = |n: usize| {
@@ -6486,7 +7148,20 @@ impl Player {
6486 }7148 }
6487 } else {7149 } else {
6488 for action in MENU_ITEMS {7150 for action in MENU_ITEMS {
6489- let enabled = applicable(&clip, menu.lane, action, playhead);7151+ // The registry's own answer, the same one the actions card
7152+ // dims a row with -- and a row that takes no click says *why*
7153+ // rather than printing a stroke that would do nothing.
7154+ let refusal = self.enable(action, Some((menu.lane, menu.idx)));
7155+ // A grade on a waveform, an equalizer on a picture, a silence
7156+ // scan on a still: things that do not exist for what was
7157+ // right-clicked, so the menu is the list of what this clip can
7158+ // do rather than the registry with most of it struck through.
7159+ // The state refusals below stay, dimmed and saying why -- the
7160+ // next click of the playhead lights them.
7161+ if !refusal.listed() {
7162+ continue;
7163+ }
7164+ let enabled = refusal.yes();
6490 // The one item that is not about this clip says so, and says it7165 // The one item that is not about this clip says so, and says it
6491 // here rather than in the registry: the stroke is global too,7166 // here rather than in the registry: the stroke is global too,
6492 // but its row in the keys menu is not sitting on a clip.7167 // but its row in the keys menu is not sitting on a clip.
@@ -6498,20 +7173,42 @@ impl Player {
6498 rows.push(7173 rows.push(
6499 row(rows.len())7174 row(rows.len())
6500 .child(label)7175 .child(label)
6501- .child(7176+ .child(match refusal.why() {
6502- div()7177+ // One truncated line, like the details side: a
7178+ // reason that wrapped would make the card taller
7179+ // than the height `menu_at` placed it by.
7180+ Some(why) => div()
7181+ .min_w(px(0.))
7182+ .truncate()
7183+ .text_size(px(11.))
7184+ .text_color(rgb(INK_DIM))
7185+ .child(why),
7186+ None => div()
6503 .text_color(rgb(INK_DIM))7187 .text_color(rgb(INK_DIM))
6504 .child(self.keymap.display(action)),7188 .child(self.keymap.display(action)),
6505- )7189+ })
6506 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())7190 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
6507 .when(enabled, |d| {7191 .when(enabled, |d| {
6508 d.cursor_pointer()7192 d.cursor_pointer()
6509 .hover(|s| s.bg(rgb(HOVER)))7193 .hover(|s| s.bg(rgb(HOVER)))
6510- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {7194+ .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
6511 // Closed first: the action moves the very7195 // Closed first: the action moves the very
6512 // indices this menu is holding.7196 // indices this menu is holding.
6513 this.context_menu = None;7197 this.context_menu = None;
7198+ // The one item that is a *choice* and not a
7199+ // doing: four policies, so the pointer gets
7200+ // the list of them on this clip rather than
7201+ // the next one stepped to behind the click.
7202+ // The stroke still steps -- same door.
7203+ if action == ActionId::Fit {
7204+ this.open_picker(
7205+ Pick::Fit(menu.lane, menu.idx),
7206+ event.position(),
7207+ cx,
7208+ );
7209+ } else {
6514 this.act(action, cx);7210 this.act(action, cx);
7211+ }
6515 }))7212 }))
6516 })7213 })
6517 .into_any_element(),7214 .into_any_element(),
@@ -6611,6 +7308,137 @@ impl Player {
6611 )7308 )
6612 }7309 }
6613 7310
7311+ /// The open choice list: every value of one enumerated setting at once, the
7312+ /// one in force marked, and a click on any of them picks *that* one -- what
7313+ /// a button stepping one value on per click could never say. Built on the
7314+ /// clip menu's machinery down to the scrim, the placement and the scroll
7315+ /// cap, so it hangs and closes exactly as the menus do and fits the same
7316+ /// 640x360 floor. The stroke for the setting is untouched: this is the
7317+ /// pointer's door to it, not a second setting.
7318+ fn picker_card(
7319+ &self,
7320+ viewport: Size<Pixels>,
7321+ cx: &mut Context<Self>,
7322+ ) -> Option<impl IntoElement> {
7323+ let picker = self.picker?;
7324+ let rows: Vec<AnyElement> = self
7325+ .choices(picker.of)
7326+ .into_iter()
7327+ .enumerate()
7328+ .map(|(n, (choice, label, detail, picked))| {
7329+ div()
7330+ .id(("picker-row", n))
7331+ .flex()
7332+ // The floor, not the height, and `HIT_MIN` of it: a row of a
7333+ // list is a click target like every other one here (WCAG
7334+ // 2.5.8).
7335+ .min_h(px(MENU_ROW_H))
7336+ .items_center()
7337+ .justify_between()
7338+ .gap(px(12.))
7339+ .px(px(6.))
7340+ .rounded(px(3.))
7341+ .cursor_pointer()
7342+ .hover(|s| s.bg(rgb(HOVER)))
7343+ // The mark is a glyph as well as a highlight, like the
7344+ // export card's rows: a background alone is gone under a
7345+ // hover and invisible to anyone who cannot tell the two
7346+ // greys apart (WCAG 1.4.1).
7347+ .when(picked, |d| d.bg(rgb(SELECTED)))
7348+ .child(
7349+ div()
7350+ .flex()
7351+ .flex_none()
7352+ .items_center()
7353+ .gap(px(8.))
7354+ .child(div().w(px(10.)).child(match picked {
7355+ true => "✓",
7356+ false => " ",
7357+ }))
7358+ .child(label),
7359+ )
7360+ .child(
7361+ div()
7362+ .min_w(px(0.))
7363+ .truncate()
7364+ .text_size(px(11.))
7365+ // On the picked row the dim ink sits on the
7366+ // highlight, where it is only 3.3:1 (WCAG 1.4.3).
7367+ .text_color(rgb(match picked {
7368+ true => INK,
7369+ false => INK_DIM,
7370+ }))
7371+ .child(detail),
7372+ )
7373+ .on_click(
7374+ cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx)),
7375+ )
7376+ .into_any_element()
7377+ })
7378+ .collect();
7379+ let (x, y) = menu_at(
7380+ picker.at,
7381+ viewport,
7382+ // Past the cap the list scrolls and the card stops growing, exactly
7383+ // as the menus and the export list do.
7384+ MENU_PAD * 2. + (rows.len() as f32 * MENU_ROW_H).min(MENU_ROWS_H),
7385+ );
7386+ Some(
7387+ div()
7388+ .absolute()
7389+ .inset_0()
7390+ // Click away closes it, either button, swallowed so nothing
7391+ // under the list also takes the press -- the clip menu's rule.
7392+ .on_mouse_down(
7393+ MouseButton::Left,
7394+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
7395+ this.picker = None;
7396+ cx.notify();
7397+ cx.stop_propagation();
7398+ }),
7399+ )
7400+ .on_mouse_down(
7401+ MouseButton::Right,
7402+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
7403+ this.picker = None;
7404+ cx.notify();
7405+ cx.stop_propagation();
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-bit64 /// 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 Main68 /// 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 every69 /// 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 codec71+/// 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 already79 # 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 image80 # 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 AOM81 # crate, so this links what the build already compiled. BSD-2 with the AOM
crates/engine/src/audio.rsmodified+378 -87
@@ -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 the69 /// 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 hole203 /// 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 is211+ /// 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 refuses212+ /// 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 file308 continue; // a gap opens no file
305 };309 };
310+ if silent.get(source) == Some(&true) {
311+ continue;
312+ }
306 let slot = tracks313 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 ran317 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> = segs342 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 first355 // 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 calling555 /// -- 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 everything558+ // Matroska: what symphonia reads out of one ([`Track::open`]) plus the
545- // else -- Opus, AC-3, DTS, none of which symphonia decodes at any559+ // 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 reason560+ // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here
547- // given. A Matroska file with no audio track at all returns `None` here561+ // 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 -- the624 // A Matroska file has exactly one readable audio stream here -- the
602- // reader's default track ([`SymTrack::open`]) -- so it lists like a625+ // 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 no627 // 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 the784 /// 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 becomes787+ /// Every source that *has* a track must declare the same
747- /// one output track with one esds. Import refuses a mismatch up front; the788+ /// [`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 many791 /// A segment naming **no** source is a gap, and is copied as that many
751 /// packets of [`silent_packet`] silence — the rounding debt carried through792 /// packets of [`silent_packet`] silence — the rounding debt carried through
752 /// it like any other, so the hole occupies its exact duration and the audio793 /// 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 gets794 /// 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 silence831 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 the847 // 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. Sources922+/// 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 = tracks933 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, exactly979 // 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 file1022 /// 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 the1025+ // 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 open1026+ // 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: symphonia1027+ // 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 one1028+ // 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 a1064 // 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 and1215 // 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 = reader1227+ 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 = track1231 let time_base = track
1132 .time_base1232 .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 the1274 /// 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 own1578 /// 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 a1579 /// 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 decoder1580 /// 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. The1585 /// 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 the1586 /// 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 registry1598 registry
1392 .first_decoder(&params)1599 .first_decoder(&params)
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 the1603+/// 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 an1604+/// 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 whole1605+/// 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 decoder1618 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 one2436 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 first2448 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;
2467+ }
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
2222 }2497 }
2223- let next = pos + (interleaved.len() / channels) as u64;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+463 -49
@@ -103,9 +103,10 @@ impl Demuxer {
103 }103 }
104 104
105 /// Bits per luma sample the stream is coded at: 8 for everything but an105 /// 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 an106+ /// 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 has107+ /// 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 a332+/// 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.7333+/// 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 a334+/// 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 block348 /// The whole segment is walked once at open -- element *headers* only, the block
343 /// payloads are seeked over -- because Matroska carries no sample table: the349 /// 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 is362 /// 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 same363 /// 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 by367+ /// 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 one387 // 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`, ...), or491 /// 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 worth492 /// `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 file493+/// 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 the635+/// 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 a636+/// 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 handful642 /// 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 mp4736 // `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-ISOBMFF813 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
664 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same814 /// §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 sequence822 /// 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, for823+/// 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 = rec829 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(),
838+ );
684 }839 }
685- Ok(rec.get(4..).unwrap_or_default().to_vec())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 span846 /// 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 laced905+ // 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 its1605 /// 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 name1635+ /// 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 a1640 // 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_bitdepth1652 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_bit1657 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 record1670 // 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 //! ```text3 //! ```text
4-//! edith 94+//! edith 10
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7 //! fps 30.07 //! fps 30.0
8 //! limiter -1.0 on8 //! limiter -1.0 on
9 //! source 0 test_av.mp49 //! source 0 test_av.mp4
10 //! source 1 /elsewhere/test_av2.mp410 //! 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:pk13 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
12 //! color 0.1:1.2:0.9:-0.314 //! color 0.1:1.2:0.9:-0.3
13 //! video 1 0 0 120 0 0 0 0 fit 100015 //! 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 has25 //! 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 mix37 //! 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 lane90 //! 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 without93+//! **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 such98 //! **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 exactly110 //! 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 grades111 //! 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 one112 //! 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 a113+//! 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 is116 //! 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 module147 /// 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 file184 /// 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 a192 /// 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 scaffolding193 /// v9 file that leaves it out, which both mean "whatever the scaffolding
174 /// source runs at" -- the inference a project of nothing but stills and194 /// 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 the316 // 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. Reading412 // 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 the415+ // 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.playhead1488 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.playhead1555 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.playhead1632 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 the1880 // 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 the1992 // 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: the690 // 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) and691 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -755,6 +766,47 @@ impl PlaybackSession {
755 self.project.sources()766 self.project.sources()
756 }767 }
757 768
769+ /// The subtitle tracks on this timeline, in the order they were added: what
770+ /// a front-end lists and what [`save_project`](Self::save_project) writes.
771+ /// A track that could not be read is *in* this list, saying why
772+ /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
773+ /// dropped.
774+ pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
775+ self.project.subtitles()
776+ }
777+
778+ /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
779+ /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
780+ /// were added -- 0 for a file whose tracks are all on the timeline already,
781+ /// since importing the same file twice is the same subtitles.
782+ ///
783+ /// An error only when the file cannot be read *at all*; a track this cannot
784+ /// parse is added refused by name, for the reason
785+ /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
786+ /// subtitles are not clips and land on no lane.
787+ pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
788+ let tracks = match path.extension().is_some_and(|e| {
789+ let e = e.to_string_lossy().to_ascii_lowercase();
790+ e == "mkv" || e == "webm"
791+ }) {
792+ true => crate::subtitle::of_matroska(path)?,
793+ false => vec![crate::subtitle::open(path, None)],
794+ };
795+ // A standalone file that could not be parsed is a refusal here rather
796+ // than a row nobody asked for: the import is the moment to say so, and
797+ // the load is the moment to keep it.
798+ if let [one] = &tracks[..]
799+ && one.track.is_none()
800+ && let Some(why) = &one.refused
801+ {
802+ return Err(why.clone().into());
803+ }
804+ Ok(tracks
805+ .into_iter()
806+ .filter(|t| self.project.add_subtitles(t))
807+ .count())
808+ }
809+
758 /// Writes the timeline to `path` as a `.edith`, atomically (see810 /// Writes the timeline to `path` as a `.edith`, atomically (see
759 /// [`crate::edith`]). Sources no clip plays from are left out, and the811 /// [`crate::edith`]). Sources no clip plays from are left out, and the
760 /// playhead is saved with it so a reopened project resumes where it stood.812 /// playhead is saved with it so a reopened project resumes where it stood.
@@ -780,6 +832,9 @@ impl PlaybackSession {
780 // project's, not this machine's (the monitoring volume is not832 // project's, not this machine's (the monitoring volume is not
781 // written and never will be).833 // written and never will be).
782 &self.project.lane_gains(),834 &self.project.lane_gains(),
835+ // The subtitle tracks with them, by reference: which file the cues
836+ // are in, never the cues (see [`crate::edith`]).
837+ self.project.subtitles(),
783 &eq,838 &eq,
784 &color,839 &color,
785 (self.meta.width, self.meta.height),840 (self.meta.width, self.meta.height),
@@ -1604,8 +1659,9 @@ impl PlaybackSession {
1604 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take1659 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
1605 /// back, and nothing reseeks.1660 /// back, and nothing reseeks.
1606 ///1661 ///
1607- /// Refused unless it can join the timeline -- same codec, same audio1662+ /// Refused unless it can join the timeline -- a decoder this machine can
1608- /// parameters or both silent; the `Err` names the property that disagrees,1663+ /// open, and audio parameters that agree or none at all; the `Err` names
1664+ /// the property that disagrees,
1609 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of1665 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
1610 /// its own is not a refusal: the clip is placed on the project canvas by its1666 /// its own is not a refusal: the clip is placed on the project canvas by its
1611 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame1667 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
@@ -1732,6 +1788,25 @@ impl PlaybackSession {
1732 }1788 }
1733 }1789 }
1734 1790
1791+ /// Stops the transport where the timeline stops: the clock is paused and put
1792+ /// on the out point.
1793+ ///
1794+ /// Playing past the last frame is wall time counting on past the end of the
1795+ /// media -- there is no picture left to pace it -- so a session left at EOF
1796+ /// reports a `now()` that walks off the end of the timeline in real time,
1797+ /// and a caller that reads the playhead (a cut, a paste, an insert) then
1798+ /// acts at a position no clip is at. How far off depends only on how long
1799+ /// the window was left open, so no clamp in a caller is worth writing.
1800+ ///
1801+ /// End of stream is deliberately left set: the picture is still the last
1802+ /// frame and this is still the end. That is what makes it safe to call on
1803+ /// the crossing into it -- the state the transport shows does not change,
1804+ /// only the running clock stops.
1805+ pub fn halt_at_end(&mut self) {
1806+ self.pause();
1807+ self.clock.seek_to(self.timeline_duration());
1808+ }
1809+
1735 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:1810 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
1736 /// one knob, because muting and turning it down are the same thing to the1811 /// one knob, because muting and turning it down are the same thing to the
1737 /// device, and *which* the user meant is a question only the UI can answer1812 /// device, and *which* the user meant is a question only the UI can answer
@@ -1944,8 +2019,9 @@ impl Drop for PlaybackSession {
1944 }2019 }
1945 2020
1946 /// Whether `path`, already demuxed to `meta`, may join a timeline whose2021 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
1947-/// parameters are `timeline` and whose audio probes as `first`: same codec,2022+/// parameters are `timeline` and whose audio probes as `first`: a decoder this
1948-/// same audio parameters or both silent, and a frame rate that can be named2023+/// machine can open, audio parameters that agree (or no audio at all), and a
2024+/// frame rate that can be named
1949 /// against the timeline's. The [`Rate`] it will be read at comes back with the2025 /// against the timeline's. The [`Rate`] it will be read at comes back with the
1950 /// answer, so the number the check was decided on is the number it plays by.2026 /// answer, so the number the check was decided on is the number it plays by.
1951 ///2027 ///
@@ -1954,7 +2030,9 @@ impl Drop for PlaybackSession {
1954 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a2030 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
1955 /// letterboxed clip rather than a refusal, and so is a frame rate of its own:2031 /// letterboxed clip rather than a refusal, and so is a frame rate of its own:
1956 /// the timeline keeps its own rate and the file is read at [`Rate`] against it2032 /// the timeline keeps its own rate and the file is read at [`Rate`] against it
1957-/// ([`PlaybackSession::import`] notes how long it is *here*).2033+/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
2034+/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
2035+/// decoder each rather than a refusal.
1958 ///2036 ///
1959 /// The `Err` names the property that disagrees, and those strings are what a2037 /// The `Err` names the property that disagrees, and those strings are what a
1960 /// front-end shows verbatim; [`PlaybackSession::import`] and2038 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1966,18 +2044,22 @@ fn matches_timeline(
1966 timeline: &VideoMeta,2044 timeline: &VideoMeta,
1967 first: &Option<crate::AudioProbe>,2045 first: &Option<crate::AudioProbe>,
1968 ) -> crate::Result<Rate> {2046 ) -> crate::Result<Rate> {
1969- // Codec first: one timeline is one kind of source. Mixing them would decode2047+ // The codec is *not* held to the timeline's -- every clip opens its own
1970- // (every clip opens its own decoder) but on a machine without the VA-API2048+ // decoder, so an H.264 take and an HEVC one play on one timeline. What the
1971- // plugin the VP9 half would be black frames with the refusal only on2049+ // codec gate was really protecting against stays, in the one place that can
1972- // stderr, which is exactly what a front-end cannot show.2050+ // actually answer it: on a machine without the VA-API plugin an HEVC or VP9
1973- if meta.codec != timeline.codec {2051+ // clip would be black frames with the refusal on stderr alone, so the file
1974- return Err(format!(2052+ // is asked for a decoder *here*, at the door, where the `Err` is still
1975- "{} does not match the timeline's {}",2053+ // something a front-end can show. A zero-length range probes and starts no
1976- meta.codec.name(),2054+ // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
1977- timeline.codec.name()2055+ // only enters VA-API off that path.
1978- )2056+ DecodeSession::open_worker(
1979- .into());2057+ &source.path,
1980- }2058+ 0,
2059+ 0,
2060+ ColorParams::default(),
2061+ Composer::passthrough(),
2062+ )?;
1981 // The frame rate is *not* a refusal any more: a file shot at another rate is2063 // The frame rate is *not* a refusal any more: a file shot at another rate is
1982 // placed for the seconds it lasts and read through [`Rate`] at the2064 // placed for the seconds it lasts and read through [`Rate`] at the
1983 // decoder's door, so it plays at the speed it was shot at on a timeline2065 // decoder's door, so it plays at the speed it was shot at on a timeline
@@ -1995,8 +2077,9 @@ fn matches_timeline(
1995 }2077 }
1996 2078
1997 /// Whether a candidate's audio may join a timeline whose first source probes as2079 /// Whether a candidate's audio may join a timeline whose first source probes as
1998-/// `first`: same rate, same layout, or both silent. One output device and one2080+/// `first`: same rate, same layout -- or no audio of its own at all, which is
1999-/// exported track is all there is, and no resampler.2081+/// silence over the clip's span and agrees with everything. One output device
2082+/// and one exported track is all there is, and no resampler.
2000 ///2083 ///
2001 /// The audio half of [`matches_timeline`], which a stream placed on its own2084 /// The audio half of [`matches_timeline`], which a stream placed on its own
2002 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it2085 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
@@ -2014,9 +2097,9 @@ fn matches_timeline(
2014 /// `Ok(None)` for a timeline whose first such source is silent, and for one of2097 /// `Ok(None)` for a timeline whose first such source is silent, and for one of
2015 /// nothing but stills. That is a silent timeline, and a file with sound is2098 /// nothing but stills. That is a silent timeline, and a file with sound is
2016 /// still refused by [`audio_matches`] in the words it always used ("the file2099 /// still refused by [`audio_matches`] in the words it always used ("the file
2017-/// has audio, the timeline is silent") -- the same answer a silent *video* as2100+/// has audio, the timeline is silent") -- the device was opened on source 0's
2018-/// source 0 has always given. This function widens which source is asked, not2101+/// track and there is none to open. This function widens which source is asked,
2019-/// what the answer means.2102+/// not what the answer means.
2020 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {2103 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
2021 match audio_source_of(sources) {2104 match audio_source_of(sources) {
2022 Some(first) => AudioSession::probe(&first.path, first.audio_stream),2105 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
@@ -2045,12 +2128,19 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R
2045 if probe == *first {2128 if probe == *first {
2046 return Ok(());2129 return Ok(());
2047 }2130 }
2048- Err(match (probe, first) {2131+ // ...and a *silent* file joins whatever the timeline is: it contributes
2049- (None, _) => "the file is silent, the timeline has audio".to_string(),2132+ // silence over its span, which is the very thing both audio paths already
2050- (_, None) => "the file has audio, the timeline is silent".to_string(),2133+ // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
2051- (Some(a), Some(b)) => format!(2134+ // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
2135+ // no layout to disagree about, so there is nothing left to refuse.
2136+ let Some(probe) = probe else {
2137+ return Ok(());
2138+ };
2139+ Err(match first {
2140+ None => "the file has audio, the timeline is silent".to_string(),
2141+ Some(b) => format!(
2052 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",2142 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
2053- a.sample_rate, a.channels, b.sample_rate, b.channels2143+ probe.sample_rate, probe.channels, b.sample_rate, b.channels
2054 ),2144 ),
2055 }2145 }
2056 .into())2146 .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 mix74 /// -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 not619 /// 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, which629 /// ([`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 the630 /// 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 self1137 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)'s1169 /// 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 the1170 /// 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 always15 /// 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 in18+/// 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* — two19+/// ~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 the20+/// 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 the260 /// 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 decodes261 /// *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
@@ -511,6 +511,67 @@ fn a_cancelled_audio_export_leaves_no_file() {
511 assert!(!part_path(&out).exists(), "no half-written .part either");511 assert!(!part_path(&out).exists(), "no half-written .part either");
512 }512 }
513 513
514+/// The samples a silent take contributes: a clip of a file with no audio track
515+/// is silence for exactly its span, between two clips that are heard. This is
516+/// what makes `PlaybackSession::import` letting such a file in honest -- the
517+/// export reads the same play list playback does, so a hole here is a hole in
518+/// the ear too.
519+#[test]
520+fn a_silent_clip_exports_as_silence_over_its_own_span() {
521+ let clip = |start, source| Clip {
522+ start,
523+ in_frame: 0,
524+ out_frame: 30,
525+ source,
526+ link: None,
527+ eq: None,
528+ color: None,
529+ fit: FitPolicy::default(),
530+ speed: Speed::NORMAL,
531+ };
532+ let project = Project::from_parts(
533+ vec![
534+ Source::new(asset("test_av.mp4"), 0),
535+ // Video only, no audio track at all: the silent take.
536+ Source::new(asset("test_mismatch.mp4"), 0),
537+ ],
538+ vec![
539+ (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
540+ (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
541+ ],
542+ Vec::new(),
543+ Vec::new(),
544+ )
545+ .expect("a project whose middle take is silent");
546+
547+ let out = out_path("silent_clip", "wav");
548+ let handle = engine::export::start(
549+ project,
550+ meta(),
551+ &out,
552+ &ExportSettings {
553+ format: Format::Wav,
554+ ..Default::default()
555+ },
556+ );
557+ wait(&handle, Duration::from_secs(60)).expect("wav export");
558+ let (audio, samples) = decode(&out);
559+ let channels = usize::from(audio.channels);
560+ assert_eq!(
561+ samples.len(),
562+ (3.0 * f64::from(RATE)) as usize * channels,
563+ "three seconds of timeline, silent take included"
564+ );
565+ let heard = rms(&samples, channels, 0.05, 0.95);
566+ let quiet = rms(&samples, channels, 1.0, 2.0);
567+ let again = rms(&samples, channels, 2.05, 2.95);
568+ println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}");
569+ assert!(heard > 0.01, "the first take is audible");
570+ assert!(again > 0.01, "the third take is audible");
571+ assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall");
572+ std::fs::remove_file(&out).unwrap();
573+}
574+
514 /// A silent timeline cannot become an audio file, and says so rather than575 /// A silent timeline cannot become an audio file, and says so rather than
515 /// writing zero samples that a user would take for a broken microphone.576 /// writing zero samples that a user would take for a broken microphone.
516 #[test]577 #[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 one255 // 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 read77 /// 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 its78 /// 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 a158+/// 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 = session168 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 it242 /// 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 count243 /// 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 a115+/// 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 = session127 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 packet235 /// 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 middle52 /// 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 the62 // `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 and791+/// 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 = session798+ // 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 on810 // 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 = session812+ // 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 a817 // 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 -- see818 // 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 = session829 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 = silent854 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 one885 /// 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 is747 // 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 -- a748+ // 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(&notes, "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(&notes)
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 a79+/// 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 = session89 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 as103 # 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` is104 # 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 the105 # 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, because106+# 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 deliberate107+# 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 says108+# 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.mkv115 -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 as154 # 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` for155 # 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 the156 # 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.mkv179 -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 with198 # 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 that199 # 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+86 -48
@@ -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+ };
52+ let d = dct4(half, |k| spec[k] as f64, tw);
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();
49 }68 }
50- return out;69+ imdct_direct(spec)
51 }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/277 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 out89 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 validate92 /// 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 oracle232 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 out279 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);