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 +5687 -1062

Cargo.lockmodified+89 -0
@@ -1003,6 +1003,12 @@ dependencies = [
10031003 "thiserror 2.0.20",
10041004 ]
10051005
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+
10061012 [[package]]
10071013 name = "compression-codecs"
10081014 version = "0.4.38"
@@ -1636,8 +1642,10 @@ dependencies = [
16361642 "libloading",
16371643 "mp4",
16381644 "oxideav-ac3",
1645+ "oxideav-ass",
16391646 "oxideav-core",
16401647 "oxideav-h265",
1648+ "oxideav-subtitle",
16411649 "rav1e",
16421650 "rusty_aac",
16431651 "rusty_h264",
@@ -3940,6 +3948,16 @@ dependencies = [
39403948 "oxideav-core",
39413949 ]
39423950
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+
39433961 [[package]]
39443962 name = "oxideav-core"
39453963 version = "0.1.34"
@@ -3958,6 +3976,77 @@ dependencies = [
39583976 "oxideav-core",
39593977 ]
39603978
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+
39614050 [[package]]
39624051 name = "parking"
39634052 version = "2.2.1"
Cargo.tomlmodified+4 -1
@@ -23,7 +23,10 @@ edition = "2024"
2323 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
2424 # term (the fast path in the same file serves the encoder only),
2525 # which is 4x slower than real time for 5.1 and therefore not
26-# playable at all; the patch caches the cosine matrix
26+# playable at all; the patch routes the IMDCT through the same
27+# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`),
28+# 40x the matrix version it started as -- 2 hours of 5.1 for a
29+# waveform in 2.4 minutes rather than an hour
2730 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
2831 # refuses any dimension that is not a multiple of the 16-sample
2932 # 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 {
7878 Speed,
7979 Silence,
8080 Mix,
81+ ToggleSnap,
8182 CancelExport,
8283 }
8384
8485 impl ActionId {
8586 /// Display order everywhere -- the editor lists them in it and
8687 /// [`Keymap::defaults`] binds them in it.
87- pub const ALL: [ActionId; 39] = [
88+ pub const ALL: [ActionId; 40] = [
8889 ActionId::Play,
8990 ActionId::StepBack,
9091 ActionId::StepForward,
@@ -123,6 +124,7 @@ impl ActionId {
123124 ActionId::Speed,
124125 ActionId::Silence,
125126 ActionId::Mix,
127+ ActionId::ToggleSnap,
126128 ActionId::CancelExport,
127129 ];
128130
@@ -167,6 +169,7 @@ impl ActionId {
167169 ActionId::Speed => "Speed (tape)…",
168170 ActionId::Silence => "Silences: cut or speed up…",
169171 ActionId::Mix => "Mix: track volumes and the limiter…",
172+ ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
170173 ActionId::CancelExport => "Cancel export",
171174 }
172175 }
@@ -213,6 +216,7 @@ impl ActionId {
213216 ActionId::Speed => "speed",
214217 ActionId::Silence => "silence",
215218 ActionId::Mix => "mix",
219+ ActionId::ToggleSnap => "toggle-snap",
216220 ActionId::CancelExport => "cancel-export",
217221 }
218222 }
@@ -265,6 +269,9 @@ impl ActionId {
265269 | ActionId::AddVideoLane
266270 | ActionId::AddAudioLane
267271 | 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
268275 | ActionId::RemoveAudioLane => Category::Editing,
269276 ActionId::ToggleMute
270277 | ActionId::VolumeUp
@@ -326,7 +333,7 @@ pub struct Fixed {
326333 pub category: Category,
327334 }
328335
329-pub const FIXED: [Fixed; 21] = [
336+pub const FIXED: [Fixed; 26] = [
330337 // Not a chord at all but a way of pressing one, and the only place the
331338 // editor can say so: holding a key that moves a *value* runs it, and
332339 // holding anything else still does what one press did.
@@ -394,7 +401,7 @@ pub const FIXED: [Fixed; 21] = [
394401 // its own: a band nothing but a drag can reach is a band half the users of
395402 // this editor cannot move at all. Card-local, so none of them is bindable.
396403 Fixed {
397- chord: "1–5",
404+ chord: "1–9, 0",
398405 label: "Pick an equalizer band",
399406 category: Category::Audio,
400407 },
@@ -408,6 +415,31 @@ pub const FIXED: [Fixed; 21] = [
408415 label: "Lower the picked band 1 dB",
409416 category: Category::Audio,
410417 },
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+ },
411443 Fixed {
412444 chord: "r",
413445 label: "Flatten every band",
@@ -645,6 +677,9 @@ impl Keymap {
645677 // machine's volume and not the project's -- two things one key
646678 // must not mean.
647679 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),
648683 b(ActionId::CancelExport, "escape", false),
649684 ],
650685 }
@@ -907,7 +942,7 @@ mod tests {
907942 #[test]
908943 fn every_default_stroke_reaches_its_action() {
909944 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);
945+ assert_eq!(k.entries().len(), 42);
911946 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912947 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913948 // ends of the timeline.
@@ -1141,7 +1176,8 @@ mod tests {
11411176 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
11421177 // The label is the editor's column, and never the file's word for it.
11431178 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");
11451181 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
11461182 }
11471183
crates/app/src/main.rsmodified+2912 -738

Diff too large; view file

@@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed};
1919 use engine::scale::FitPolicy;
2020 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
2121 use gpui::{
22- AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
23- KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
24- Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign,
25- TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px,
26- relative, rgb, rgba, size,
22+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
23+ FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
24+ PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size,
25+ Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img,
26+ point, prelude::*, px, relative, rgb, rgba, size,
2727 };
2828
2929 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -85,6 +85,13 @@ const WAVE_BPS: u32 = 40;
8585 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
8686 /// and a path with a point per pixel is a path per repaint.
8787 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;
8895 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
8996 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
9097 const HIT_MIN: f32 = 24.;
@@ -260,6 +267,10 @@ enum Wave {
260267 Loading,
261268 /// The file has no audio track. An answer, not a miss.
262269 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,
263274 Peaks(Arc<Vec<(f32, f32)>>),
264275 }
265276
@@ -277,6 +288,13 @@ struct AssetDrag(PathBuf, usize);
277288 struct ClipDrag {
278289 lane: Lane,
279290 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,
280298 }
281299
282300 /// A clip edge being dragged: which end of which clip, and the timeline frame
@@ -335,6 +353,38 @@ struct LibraryMenu {
335353 details: bool,
336354 }
337355
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+
338388 /// What a library row's menu offers, in the order it lists them. Unlike the clip
339389 /// menu's items none of these is a stroke -- there is no keyboard way to a row --
340390 /// so the label and the hint are written here rather than read off the keymap.
@@ -402,6 +452,47 @@ const MENU_ITEMS: [ActionId; 14] = [
402452 ActionId::ToggleMute,
403453 ];
404454
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+
405496 /// The project resolutions [`Player::cycle_resolution`] offers, largest first.
406497 /// A short list of the sizes people name; the media's own is cycled in beside
407498 /// 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.;
524615 /// and short enough that the card still fits a 360 px window.
525616 const EQ_GRAPH_H: f32 = 132.;
526617
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+
527648 /// How many points the curve is drawn from. One per ~3 px across the card:
528649 /// past that the line is smooth and the extra biquad evaluations are wasted.
529650 const EQ_CURVE_STEPS: usize = 96;
@@ -572,6 +693,11 @@ const EQ_SPECTRUM_INK: u32 = 0x7f95ad66;
572693 /// its weight: it is what makes a boost read as a hill rather than as a wire.
573694 const EQ_FILL_INK: u32 = 0x4a9eff26;
574695
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+
575701 /// The colour card's four controls, in the order it lists them: what each is
576702 /// called and the range it moves in. The order is `ColorParams`' own, which is
577703 /// what [`color_band`] indexes.
@@ -614,6 +740,48 @@ const HIST_H: f32 = 96.;
614740 /// counts, lightened enough to read on the dark box.
615741 const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
616742
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+
617785 struct Player {
618786 /// The timeline, once there is one. A run with no file opens without it and
619787 /// waits: the first media import or project load is what fills it, and
@@ -625,21 +793,20 @@ struct Player {
625793 name: SharedString,
626794 image: Option<Arc<RenderImage>>,
627795 /// 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`].
628799 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,
633800 /// A seek is waiting for its frame. Keeps the repaint loop alive while
634801 /// paused, which is the only way the new still ever reaches the screen.
635802 pending_seek: bool,
636803 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
637804 /// the window position and nothing else.
638805 ruler: Rc<Cell<Bounds<Pixels>>>,
639- /// How much of the timeline the ruler and the lanes are showing. Held here
806+ /// How wide a second of timeline is drawn, and from which moment. Held here
640807 /// and nowhere else: every frame-to-pixel answer in the panel comes out of
641808 /// it, so the boxes, the playhead and the pointer cannot disagree.
642- view: View,
809+ scale: Scale,
643810 /// Which clip the edit keys act on: the lane it is in and its index there.
644811 /// The *clicked* half, not the group -- a group is what gets marked on
645812 /// screen, but Lift has to know which half it was aimed at. Indices move
@@ -649,6 +816,10 @@ struct Player {
649816 /// `selected` does, so it is closed by anything that can move indices --
650817 /// every stroke, and every item of its own.
651818 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>,
652823 /// The library menu a right-click on a row opened, if one is up. Names its
653824 /// row by file and stream rather than by position, so it acts on the row it
654825 /// was opened on however the list is rebuilt under it.
@@ -704,6 +875,16 @@ struct Player {
704875 /// the value being dragged, and stale between drags, which costs nothing --
705876 /// no drag starts without a press on the box it moves.
706877 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>,
707888 last_scrub: Instant,
708889 last_target: u32,
709890 /// The running export. While it owns the UI the editor is read-only.
@@ -890,6 +1071,9 @@ impl Player {
8901071 /// the channel and only the last of them is shown, which *is* the
8911072 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
8921073 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();
8931077 // No timeline, nothing to catch up to: the window is showing its empty
8941078 // state and there is no decoder to drain.
8951079 let Some(session) = &mut self.session else {
@@ -905,10 +1089,7 @@ impl Player {
9051089 // them apart -- `frame.index` is already a timeline index.
9061090 None => match session.try_frame() {
9071091 Some(frame) => frame,
908- None => {
909- self.eos = session.is_eos();
910- break;
911- }
1092+ None => break,
9121093 },
9131094 };
9141095 if f64::from(frame.index) <= target {
@@ -943,29 +1124,56 @@ impl Player {
9431124 }
9441125 }
9451126
946- if self.eos && self.held.is_none() && !self.done {
947- self.done = true;
1127+ if self.transport() == Transport::Ended {
9481128 // 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.
9501131 self.pending_seek = false;
951- let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
952- eprintln!(
953- "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
954- self.displayed,
955- self.dropped,
956- session.now()
957- );
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+ }
1146+ let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
1147+ eprintln!(
1148+ "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
1149+ self.displayed,
1150+ self.dropped,
1151+ self.session.as_ref().map_or(0., PlaybackSession::now)
1152+ );
1153+ }
9581154 }
9591155 }
9601156
961- /// Every end-of-stream flag is app state and the engine knows nothing about
962- /// it, so clearing them after a reseek is what stops the picture from
963- /// staying frozen on the old last frame. Edits reseek inside the engine and
964- /// still owe this.
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+ }
1170+
1171+ /// A frame owed to the screen after a reseek, and the buffered one dropped:
1172+ /// what stops the picture from staying frozen on the old last frame. The
1173+ /// end-of-stream flag itself is the engine's and its own seek clears it --
1174+ /// edits reseek inside the engine and still owe this.
9651175 fn reset_after_reseek(&mut self) {
9661176 self.held = None;
967- self.eos = false;
968- self.done = false;
9691177 self.pending_seek = true;
9701178 // An edit moves the indices a drag in flight is holding -- a stroke
9711179 // during one is exactly that -- and an edge committed against a moved
@@ -1025,12 +1233,57 @@ impl Player {
10251233 ActionId::Speed => self.open_speed(cx),
10261234 ActionId::Silence => self.open_silence(cx),
10271235 ActionId::Mix => self.open_mix(None, cx),
1236+ ActionId::ToggleSnap => self.toggle_snap(cx),
10281237 // Nothing to cancel while nothing is exporting; the export guard in
10291238 // the key handler is what answers this one while there is.
10301239 ActionId::CancelExport => {}
10311240 }
10321241 }
10331242
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+
10341287 /// The one place a clip becomes *the* selected one: a click, a right-click
10351288 /// that opens the menu, and every selection key go through here, so what a
10361289 /// keyboard marks and what a pointer marks are the same state marked the
@@ -1126,31 +1379,54 @@ impl Player {
11261379 return;
11271380 };
11281381 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+ {
11301392 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());
11321394 self.reset_after_reseek();
11331395 }
11341396 cx.notify();
11351397 }
11361398
1137- /// Magnifies the timeline about a point that stays put: `anchor` is where
1138- /// along the bed to hold still (a ctrl+wheel holds the pointer), and with
1139- /// none it is the playhead -- so the frame being worked on is still the
1399+ /// The scale against the bed it is drawn on and the timeline it is drawn
1400+ /// from: every clamp, zoom and scroll is worked out through this, and the
1401+ /// 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
11401415 /// 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.
11421417 fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
1143- let duration = self.drawn_duration();
1144- let at = self.playhead(duration);
1145- let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.));
1146- self.view = self.view.zoomed(factor, anchor, duration, self.fps);
1418+ let view = self.view();
1419+ let at = self.playhead(view.duration);
1420+ let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
1421+ self.scale = view.zoomed(factor, anchor);
11471422 cx.notify();
11481423 }
11491424
1150- /// All the way back out: the whole timeline across the bed, which is what
1151- /// the panel shows before anyone has zoomed at all.
1425+ /// All the way back out: the whole timeline across the bed, and the one
1426+ /// thing that reads the timeline's own length to decide how wide a second
1427+ /// is drawn.
11521428 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
1153- self.view = View::default();
1429+ self.scale = self.view().fit();
11541430 cx.notify();
11551431 }
11561432
@@ -1169,13 +1445,59 @@ impl Player {
11691445 return;
11701446 };
11711447 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+ {
11731457 self.notice = Some(format!("PROJECT: {width}x{height}").into());
11741458 self.reset_after_reseek();
11751459 }
11761460 cx.notify();
11771461 }
11781462
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+
11791501 /// Opens the colour card on the clip a grade would go on: the clip that was
11801502 /// clicked when it is a video one, and otherwise the clip the picture is
11811503 /// coming from -- the one the engine's own compositing rule picks, which is
@@ -1863,41 +2185,78 @@ impl Player {
18632185 cx.notify();
18642186 }
18652187
1866- /// Moves one band and says whether anything changed. Live only: the write
1867- /// is [`commit_eq`](Player::commit_eq)'s.
1868- fn set_band(&mut self, band: usize, gain_db: f32) -> bool {
1869- let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
1870- match self.eq_params.bands.get_mut(band) {
1871- Some(b) if b.gain_db != gain_db => {
1872- b.gain_db = gain_db;
1873- true
1874- }
1875- _ => false,
2188+ /// Changes the picked band in place and says whether anything moved. Every
2189+ /// edit of a band goes through here -- the drag, each key, each stepper
2190+ /// button -- so the card has exactly one place that clamps a band into what
2191+ /// the graph can draw, and no caller has to remember the limits.
2192+ fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
2193+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
2194+ return false;
2195+ };
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);
18762209 }
18772210 }
18782211
1879- /// The keyboard's version of a drag: one step on the picked band, committed
1880- /// straight away -- a keystroke has no release to wait for.
1881- fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {
1882- let gain = self
1883- .eq_params
1884- .bands
1885- .get(self.eq_band)
1886- .map_or(0., |b| b.gain_db);
1887- if self.set_band(self.eq_band, gain + by) {
1888- self.commit_eq(cx);
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();
2226+ }
2227+ }
2228+
2229+ /// A band added beside the picked one, at the frequency with the most room
2230+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
2231+ /// band that was just made. Refused rather than silently ignored at the cap.
2232+ fn add_band(&mut self, cx: &mut Context<Self>) {
2233+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
2234+ self.notice = Some(
2235+ format!(
2236+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
2237+ )
2238+ .into(),
2239+ );
2240+ cx.notify();
2241+ return;
18892242 }
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);
18902247 }
18912248
1892- /// Where the pointer sits down the graph, as a gain on the picked band: the
1893- /// middle is flat and the top and bottom edges are the limit either way.
1894- /// Called on every pointer sample, so the curve bends under the hand; the
1895- /// write is the release's ([`commit_eq`](Player::commit_eq)).
1896- fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {
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) {
2249+ /// Takes the picked band out. The last one stays: an equalizer of no bands
2250+ /// is a card with nothing to edit, and flattening is what "off" means here.
2251+ fn remove_band(&mut self, cx: &mut Context<Self>) {
2252+ if self.eq_params.bands.len() <= 1 {
2253+ self.notice = Some("LAST BAND — flatten it instead (r), or close the card".into());
18992254 cx.notify();
2255+ return;
19002256 }
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);
19012260 }
19022261
19032262 /// Which band a press on the graph grabs: the nearest one along the
@@ -1934,16 +2293,17 @@ impl Player {
19342293 /// door a ruler click uses -- so a step while playing keeps playing, exactly
19352294 /// as a click does. It starts from the frame the transport is showing, which
19362295 /// 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`). Both
2296+ /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
19382297 /// ends clamp, so the two go-to actions are this same step asked for more
19392298 /// frames than the timeline has. Selection is untouched: a seek is not an
19402299 /// edit, and nothing it does moves a clip index.
19412300 fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
2301+ let ended = self.transport() == Transport::Ended;
19422302 let Some(session) = &self.session else {
19432303 return;
19442304 };
19452305 let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
1946- let now = match self.done {
2306+ let now = match ended {
19472307 true => last,
19482308 false => i64::from(frame_at(session.now(), self.fps)),
19492309 };
@@ -2183,9 +2543,8 @@ impl Player {
21832543 let (path, stream) = key.clone();
21842544 async move {
21852545 engine::waveform::peaks(&path, stream, WAVE_BPS)
2186- .ok()
2187- .flatten()
2188- .map(|peaks| Arc::new(normalise(peaks)))
2546+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
2547+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
21892548 }
21902549 });
21912550 cx.spawn(async move |this, cx| {
@@ -2194,11 +2553,14 @@ impl Player {
21942553 this.waves.insert(
21952554 key,
21962555 match decoded {
2197- Some(peaks) => Wave::Peaks(peaks),
2198- // Either no audio track or a file we could not read
2199- // it from; both mean the lane has nothing to draw,
2200- // and neither is worth asking about again.
2201- None => Wave::Silent,
2556+ Ok(Some(peaks)) => Wave::Peaks(peaks),
2557+ // No audio track: an answer, and not worth asking
2558+ // about again.
2559+ Ok(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,
22022564 },
22032565 );
22042566 cx.notify();
@@ -2294,8 +2656,8 @@ impl Player {
22942656 if self.exporting().is_some() {
22952657 return;
22962658 }
2297- let (Some(start), Some(was)) = (
2298- self.drop_frame(from, idx, to, x),
2659+ let (Some((start, _)), Some(was)) = (
2660+ self.drop_frame(from, idx, x),
22992661 self.session
23002662 .as_ref()
23012663 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2351,46 +2713,83 @@ impl Player {
23512713 /// there is no such clip to move. The engine has the last word on where it
23522714 /// may actually go -- this is the ask, not the answer.
23532715 ///
2354- /// ponytail: the bed ends where the timeline does, so a clip cannot be
2355- /// dragged *past* the last frame -- the pointer has no pixel out there to
2356- /// name and [`View::time_at`] clamps to the duration. Room to the right is
2357- /// made by pulling a tail out first ([`Player::drawn_duration`] already
2358- /// lengthens the bed for exactly that gesture). The upgrade is to draw the
2359- /// bed past the end while a clip drag is in flight, the way a trim already
2360- /// does: `drawn_duration` would take the dragged clip's length the same way
2361- /// it takes a trim's reach.
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()?;
2716+ /// ponytail: the bed now runs past the last frame whenever the timeline is
2717+ /// shorter than the view ([`Scale::time_at`] clamps at the head only), so a
2718+ /// clip *can* be dragged out there. Zoomed in against the far end it cannot:
2719+ /// the scroll clamp pins the bed's right edge to the duration, and the
2720+ /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2721+ /// leave a screen of empty bed after the end, the way every NLE does.
2722+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2723+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
23652724 let raw = self.frame_under(x).saturating_sub(self.grab);
2366- // The edges worth landing on: both ends of every clip already on the
2367- // lane it is being let go over, the playhead, and the head of the
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))
2725+ let marks = self.snap_targets(Some((from, idx)));
2726+ Some(self.snap_to(raw, clip.frames(), &marks))
23822727 }
23832728
2384- /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is
2385- /// a distance on screen, so zoomed right in it is worth less than a frame
2386- /// (no snap at all, which is what a hand placing single frames wants) and
2387- /// zoomed out to the whole timeline it is worth many.
2388- fn snap_frames(&self) -> u32 {
2389- let bed = f64::from(f32::from(self.ruler.get().size.width));
2390- if bed <= 0. {
2391- return 0;
2729+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
2730+ /// lane the drag named, since a stroke during the gesture moves the indices
2731+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
2732+ /// drawn in flight and the drop that commits -- so the promise and the
2733+ /// landing are made about one clip.
2734+ fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
2735+ let session = self.session.as_ref()?;
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();
23922767 }
2393- (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u32
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)
2786+ }
2787+
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)
23942793 }
23952794
23962795 /// Opens the clip menu on the box under the pointer, from the right button
@@ -2447,26 +2846,36 @@ impl Player {
24472846 /// against the same duration the boxes are drawn to, so the edge tracks the
24482847 /// pointer exactly.
24492848 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2450- let at = self.frame_under(x);
2451- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2849+ let Some(trim) = self.trim else {
24522850 return;
24532851 };
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 {
24552861 return;
24562862 };
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 });
24582868 cx.notify();
24592869 }
24602870
24612871 /// 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 drawn
2872+ /// ruler is measured on, through the same [`Scale`] every box is drawn
24632873 /// through, so a zoomed-in panel answers with the frame under the pointer
24642874 /// and not with the one that would have been there unzoomed. The one
24652875 /// question a trim, a grab and a drop all ask.
24662876 fn frame_under(&self, x: Pixels) -> u32 {
2467- let duration = self.drawn_duration();
24682877 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())),
24702879 self.fps,
24712880 )
24722881 }
@@ -2497,39 +2906,13 @@ impl Player {
24972906 }) else {
24982907 return clip;
24992908 };
2500- match trim.edge {
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- session
2508- .sources()
2509- .get(clip.source)
2510- .is_some_and(|s| engine::is_image(&s.path))
2511- }) =>
2512- {
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- }
2909+ let still = self.session.as_ref().is_some_and(|session| {
2910+ session
2911+ .sources()
2912+ .get(clip.source)
2913+ .is_some_and(|s| engine::is_image(&s.path))
2914+ });
2915+ trimmed_clip(clip, trim.edge, trim.to, still)
25332916 }
25342917
25352918 /// How long the timeline is *drawn* as: its own length, and while a tail is
@@ -2537,6 +2920,15 @@ impl Player {
25372920 /// at the last frame has nowhere to put a pointer that means "longer", so
25382921 /// without this the last clip on the timeline could be pulled in and never
25392922 /// 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.
25402932 fn drawn_duration(&self) -> f64 {
25412933 let Some(session) = &self.session else {
25422934 return 0.;
@@ -2553,12 +2945,11 @@ impl Player {
25532945 }
25542946 }
25552947
2556- /// Where the playhead is, as the panel draws it. The clock keeps running
2557- /// after the last frame (wall time takes over at audio EOF) while the
2558- /// picture is frozen, so what the UI shows is the clamped one, pinned to
2559- /// the out-point once playback is done.
2948+ /// Where the playhead is, as the panel draws it: pinned to the out point
2949+ /// once playback is done, and clamped to the drawn duration otherwise -- a
2950+ /// tail being dragged draws past the timeline it is about to become.
25602951 fn playhead(&self, duration: f64) -> f64 {
2561- if self.done {
2952+ if self.transport() == Transport::Ended {
25622953 duration
25632954 } else {
25642955 self.session
@@ -2753,11 +3144,11 @@ impl Player {
27533144 self.export_path = PathBuf::new();
27543145 self.project_path = PathBuf::new();
27553146 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.
27573150 self.reset_after_reseek();
27583151 self.pending_seek = false;
2759- self.eos = false;
2760- self.done = false;
27613152 }
27623153
27633154 /// One item of a library row's menu, done. Every one of them closes the
@@ -3126,9 +3517,12 @@ impl Player {
31263517 let Some(session) = &self.session else {
31273518 return;
31283519 };
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.
31293522 let t = self
3130- .view
3131- .time_at(frac_along(x, self.ruler.get()), session.timeline_duration());
3523+ .scale
3524+ .time_at(px_along(x, self.ruler.get()))
3525+ .clamp(0., session.timeline_duration());
31323526 let target = (t * self.fps) as u32;
31333527 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
31343528 self.last_target = target;
@@ -3173,11 +3567,11 @@ impl Player {
31733567 return;
31743568 }
31753569 // Nothing to play is a message, not a transport state. An empty
3176- // timeline is `done` from its one black frame onward, so the restart
3177- // below would start a clock against a zero-length timeline -- and it is
3178- // `done` again by the next repaint, so no later press could ever stop
3179- // it: the button would read "Pause" and never pause. A delete can empty
3180- // the timeline mid-play, and that press must still stop it.
3570+ // timeline is [`Transport::Ended`] from its one black frame onward, so
3571+ // the restart below would start a clock against a zero-length timeline
3572+ // -- and it is Ended again by the next repaint, so no later press could
3573+ // ever stop it: the button would read "Pause" and never pause. A delete
3574+ // can empty the timeline mid-play, and that press must still stop it.
31813575 if nothing_to_play(self.session.as_ref()) {
31823576 match self.session.as_mut().filter(|s| s.is_playing()) {
31833577 Some(session) => session.pause(),
@@ -3186,15 +3580,25 @@ impl Player {
31863580 cx.notify();
31873581 return;
31883582 }
3189- if self.done {
3190- self.seek(0., cx);
3191- if let Some(session) = &mut self.session {
3192- session.play();
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() => {
3589+ self.seek(0., cx);
3590+ if let Some(session) = &mut self.session {
3591+ session.play();
3592+ }
3593+ }
3594+ _ => {
3595+ if let Some(session) = &mut self.session {
3596+ session.toggle();
3597+ // A paused timeline animates nothing; this is the repaint
3598+ // that puts the new glyph up.
3599+ cx.notify();
3600+ }
31933601 }
3194- } else if let Some(session) = &mut self.session {
3195- session.toggle();
3196- // Past EOF nothing else asks for a repaint.
3197- cx.notify();
31983602 }
31993603 }
32003604
@@ -3428,11 +3832,9 @@ impl Render for Player {
34283832 window.set_window_title(&title);
34293833 self.titled = title;
34303834 }
3431- // No shadow flag: the clock is the only truth about play state.
3432- let playing = self
3433- .session
3434- .as_ref()
3435- .is_some_and(PlaybackSession::is_playing);
3835+ // No shadow flag: the session is the only truth about play state, and
3836+ // [`Player::transport`] is the one place it is read.
3837+ let state = self.transport();
34363838 // A paused timeline has nothing to animate; the toggle handlers notify,
34373839 // which is what starts the loop again. A paused seek keeps the loop
34383840 // running by itself until `pump` has the frame it asked for. An export
@@ -3440,7 +3842,7 @@ impl Render for Player {
34403842 // the screen on a repaint. A notice does not: it waits to be dismissed
34413843 // rather than for a clock, so keeping the loop alive for it would spin
34423844 // 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() {
34443846 window.request_animation_frame();
34453847 }
34463848
@@ -3453,7 +3855,7 @@ impl Render for Player {
34533855 // edit that shortens the timeline moves the far end of the view, and a
34543856 // playhead that has run off the bed pulls the view after it -- which is
34553857 // 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);
34573859
34583860 div()
34593861 .track_focus(&self.focus)
@@ -3574,31 +3976,55 @@ impl Render for Player {
35743976 // cannot move at all, and every one of them is listed in the
35753977 // keys menu (keymap.rs `FIXED`) rather than being a secret.
35763978 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;
35773984 if key == ESCAPE {
35783985 // Nothing to undo: every change is already at the clip,
35793986 // and undo is undo's own key.
35803987 this.eq_open = None;
35813988 this.eq_dragging = false;
35823989 } else if key == "up" {
3583- this.nudge_band(EQ_STEP, cx);
3990+ this.nudge_band(|b| b.gain_db += EQ_STEP, cx);
35843991 } 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);
35864001 } else if key == "r" {
35874002 for band in &mut this.eq_params.bands {
35884003 band.gain_db = 0.;
35894004 }
35904005 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);
35914014 } else if key == "s" {
35924015 // The analyser off and on. Nothing is committed: it is
35934016 // what the card *shows*, so it survives no further than
35944017 // this window.
35954018 this.eq_spectrum = !this.eq_spectrum;
35964019 } else if let Ok(digit) = key.parse::<usize>() {
3597- // 1-based, as the rows are numbered on screen; a digit
3598- // past the last band picks nothing rather than panics.
3599- if let Some(band) = digit.checked_sub(1)
3600- && band < this.eq_params.bands.len()
3601- {
4020+ // As the keys are laid out: 1-9 then 0 for the tenth,
4021+ // which is the cap ([`EQ_BANDS_MAX`]). A digit past the
4022+ // last band picks nothing rather than panics.
4023+ let band = match digit {
4024+ 0 => EQ_BANDS_MAX - 1,
4025+ n => n - 1,
4026+ };
4027+ if band < this.eq_params.bands.len() {
36024028 this.eq_band = band;
36034029 }
36044030 }
@@ -3702,9 +4128,12 @@ impl Render for Player {
37024128 // Both menus, taken rather than short-circuited: the library's
37034129 // one names a row the edits below can remove, so it closes on a
37044130 // 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.
37054133 let clip_menu = this.context_menu.take().is_some();
37064134 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 {
37084137 cx.notify();
37094138 if key == ESCAPE {
37104139 return;
@@ -3737,6 +4166,26 @@ impl Render for Player {
37374166 }
37384167 }
37394168 }))
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+ )
37404189 // Scrubbing is tracked on the root because the pointer leaves the
37414190 // 6 px ruler on the first drag and its own listeners then stop
37424191 // firing; the root's hitbox is the whole window.
@@ -3745,7 +4194,7 @@ impl Render for Player {
37454194 // the equalizer drag is tracked here for the ruler's reason.
37464195 if this.eq_dragging {
37474196 if event.pressed_button == Some(MouseButton::Left) {
3748- this.drag_band(event.position.y, cx);
4197+ this.drag_band(event.position, cx);
37494198 } else {
37504199 // Released outside the window: the up below never came,
37514200 // so this is where the gesture ends -- and it still owes
@@ -3815,7 +4264,7 @@ impl Render for Player {
38154264 if std::mem::take(&mut this.eq_dragging) {
38164265 // The release lands exactly, then the gesture is written
38174266 // once -- the append-only table's whole reason.
3818- this.drag_band(event.position.y, cx);
4267+ this.drag_band(event.position, cx);
38194268 this.commit_eq(cx);
38204269 return;
38214270 }
@@ -3905,7 +4354,7 @@ impl Render for Player {
39054354 // Above the panel and only when there is one to show, so it costs
39064355 // the picture nothing the rest of the time.
39074356 .children(self.notice_bar(cx))
3908- .child(self.panel(position, duration, playing, cx))
4357+ .child(self.panel(position, duration, state, cx))
39094358 // Over the panel it was opened on, and under the cards: it is only
39104359 // ever up while neither of them is (`modal`).
39114360 .children(self.context_card(window.viewport_size(), cx))
@@ -3917,11 +4366,14 @@ impl Render for Player {
39174366 // column, and only one of the two is ever up.
39184367 .children(self.keys_overlay(cx))
39194368 .children(self.export_card(window.viewport_size(), cx))
3920- .children(self.eq_card(cx))
4369+ .children(self.eq_card(window.viewport_size(), cx))
39214370 .children(self.color_card(cx))
39224371 .children(self.speed_card(cx))
39234372 .children(self.silence_card(cx))
39244373 .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))
39254377 }
39264378 }
39274379
@@ -4226,21 +4678,22 @@ impl Player {
42264678 &self,
42274679 position: f64,
42284680 duration: f64,
4229- playing: bool,
4681+ state: Transport,
42304682 cx: &mut Context<Self>,
42314683 ) -> impl IntoElement {
4232- // Where the playhead is *on the bed*, which at the fit is where along
4233- // the timeline it is and zoomed in is where along the visible slice.
4234- // Clamped because it is drawn as a width as well as an offset, and the
4235- // view follows the playhead anyway, so it is never off the bed.
4236- let filled = self.view.frac_at(position, duration).clamp(0., 1.);
4684+ // Where the playhead is *on the bed*, in pixels from its left edge.
4685+ // Clamped to the bed because it is drawn as a width as well as an
4686+ // offset, and the view follows the playhead anyway, so it is never off
4687+ // the bed for long.
4688+ let bed_w = f32::from(self.ruler.get().size.width);
4689+ let filled = self.scale.px_at(position).clamp(0., bed_w);
42374690 // An export owns the hint slot and the ruler while it runs: the
42384691 // percentage and the accent bar are the same number, so the playhead
42394692 // fill doubles as the progress bar for free.
42404693 let exporting = self.exporting().is_some();
42414694 // Everything but Import and Keys needs a timeline to act on: with none
42424695 // open they are dimmed rather than silently doing nothing.
4243- let live = self.session.is_some() && !exporting;
4696+ let live = state != Transport::Stopped && !exporting;
42444697 // The project's own picture size, for the button that cycles it: read
42454698 // per render like everything else here, so a cycle shows on the button
42464699 // that made it.
@@ -4256,7 +4709,7 @@ impl Player {
42564709 // closure would hold it for as long as the iterator lives.
42574710 let mut rows = Vec::new();
42584711 for &lane in &lanes {
4259- rows.push(self.lane_row(lane, duration, filled, cx));
4712+ rows.push(self.lane_row(lane, filled, cx));
42604713 }
42614714 let (hint, filled) = if let Some(export) = self.exporting() {
42624715 let progress = export.progress();
@@ -4300,7 +4753,7 @@ impl Player {
43004753 // of this line is what a narrow window truncates.
43014754 (
43024755 join_detail(
4303- &self.live_decode(position, playing),
4756+ &self.live_decode(position, state.is_playing()),
43044757 &format!(
43054758 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
43064759 import",
@@ -4339,9 +4792,9 @@ impl Player {
43394792 .overflow_x_scroll()
43404793 .child(control(
43414794 "transport",
4342- Some(transport_glyph(playing).into_any_element()),
4343- if playing { "Pause" } else { "Play" },
4344- if nothing_to_play(self.session.as_ref()) && !playing {
4795+ Some(transport_glyph(state).into_any_element()),
4796+ if state.is_playing() { "Pause" } else { "Play" },
4797+ if nothing_to_play(self.session.as_ref()) && !state.is_playing() {
43454798 format!("{} — put a clip on a lane first", key(ActionId::Play))
43464799 } else {
43474800 key(ActionId::Play)
@@ -4351,7 +4804,7 @@ impl Player {
43514804 // against nothing (the key press answers with the
43524805 // notice). Still live while it *is* playing: a delete
43534806 // 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())),
43554808 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
43564809 ))
43574810 .child(separator())
@@ -4448,35 +4901,38 @@ impl Player {
44484901 ))
44494902 .child(separator())
44504903 // The size every clip is composed onto, which is also the
4451- // size the export comes out at: the one project setting a
4452- // stroke used to be the only way to. Cycles exactly as the
4453- // key does, and says where it is now rather than opening a
4454- // list to close again.
4904+ // size the export comes out at. Five sizes, so a click opens
4905+ // the list of them with this one marked and picks whichever
4906+ // was meant: a button that stepped one on per press made the
4907+ // user click round the ladder to get back to where they
4908+ // were. The stroke still steps, for the hand already on it.
44554909 .child(control(
44564910 "resolution",
44574911 None,
44584912 resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")),
44594913 match resolution {
44604914 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",
44624916 key(ActionId::Resolution)
44634917 ),
44644918 None => format!("{} — open a file first", key(ActionId::Resolution)),
44654919 },
44664920 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+ }),
44684924 ))
44694925 // How much of the timeline the panel below is showing --
44704926 // beside the resolution, since neither of them edits
44714927 // anything: they are both what is being looked at. The
4472- // middle one reads as the state (1.0x is the whole
4473- // timeline) and is the way back to it.
4928+ // middle one says how much of it is on the bed, and is the
4929+ // way back to the whole of it.
44744930 .child(control(
44754931 "zoom-out",
44764932 None,
44774933 "−",
44784934 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",
44804936 key(ActionId::ZoomOut)
44814937 ),
44824938 live,
@@ -4487,13 +4943,17 @@ impl Player {
44874943 .child(control(
44884944 "zoom-fit",
44894945 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()),
44914951 format!(
44924952 "{} — fit the whole timeline; showing {} to {}",
44934953 key(ActionId::ZoomFit),
4494- timecode(self.view.start, self.fps),
4954+ timecode(self.scale.start, self.fps),
44954955 timecode(
4496- (self.view.start + self.view.span(duration)).min(duration),
4956+ (self.scale.start + self.view().span()).min(duration),
44974957 self.fps
44984958 )
44994959 ),
@@ -4511,6 +4971,25 @@ impl Player {
45114971 live,
45124972 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
45134973 ))
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+ ))
45144993 // Import is not here: it belongs to the media list it adds
45154994 // to, and two doors into one action is a question about
45164995 // which one is the real one.
@@ -4561,8 +5040,10 @@ impl Player {
45615040 .child(control(
45625041 "keys",
45635042 None,
4564- "Keys",
4565- "show and change the keybindings".to_string(),
5043+ "Actions",
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(),
45665047 !exporting,
45675048 cx.listener(|this, _: &ClickEvent, _, cx| {
45685049 this.keys_open = !this.keys_open;
@@ -4581,10 +5062,20 @@ impl Player {
45815062 .gap(px(12.))
45825063 // Fixed width and one line: changing digits must not push
45835064 // 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.
45845070 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
45855071 "{} / {}",
45865072 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+ )
45885079 )))
45895080 .child(
45905081 div()
@@ -4644,7 +5135,7 @@ impl Player {
46445135 if dy == 0. {
46455136 return;
46465137 }
4647- let anchor = frac_along(event.position.x, this.ruler.get());
5138+ let anchor = px_along(event.position.x, this.ruler.get());
46485139 let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP };
46495140 this.zoom(factor, Some(anchor), cx);
46505141 },
@@ -4666,7 +5157,7 @@ impl Player {
46665157 .child(
46675158 div()
46685159 .h_full()
4669- .w(relative(filled))
5160+ .w(px(filled))
46705161 .rounded(px(3.))
46715162 .bg(rgb(ACCENT)),
46725163 ),
@@ -4772,83 +5263,115 @@ impl Player {
47725263 ctrl: false,
47735264 }
47745265 .pretty();
4775- // Every stroke that works, under its heading, and both halves of the
4776- // list come from the registry: one row per action -- an action with two
4777- // strokes reads as one line ("x or delete") and a rebind replaces that
4778- // whole set -- then the strokes the modal cards answer to, which are
4779- // shown but not offered, because nothing may unbind the way out.
5266+ // Every action there is, under its heading, and the strokes the modal
5267+ // cards answer to beside them -- `keys_rows` is the whole of the order
5268+ // and every word in it comes off the registry.
5269+ //
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.
47805274 let mut rows: Vec<AnyElement> = Vec::new();
4781- for category in keymap::Category::ALL {
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()
4792- .flex_none()
4793- .px(px(6.))
4794- .pt(px(4.))
4795- .text_size(px(11.))
4796- .text_color(rgb(INK_DIM))
4797- .child(category.label())
4798- .into_any_element(),
4799- );
4800- }
4801- };
4802- for (i, action) in actions {
4803- head(&mut rows);
4804- let capturing = self.rebinding == Some(action);
4805- let out = out.clone();
4806- rows.push(
4807- div()
4808- .id(("bind", i))
4809- .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))
4813- .items_center()
4814- .justify_between()
4815- .gap(px(12.))
4816- .px(px(6.))
4817- .rounded(px(3.))
4818- .cursor_pointer()
4819- .hover(|s| s.bg(rgb(HOVER)))
5275+ let row = || {
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()
5290+ .flex_none()
5291+ .px(px(6.))
5292+ .pt(px(4.))
5293+ .text_size(px(11.))
5294+ .text_color(rgb(INK_DIM))
5295+ .child(category.label())
5296+ .into_any_element(),
5297+ KeyRow::Act(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);
5302+ let out = out.clone();
5303+ row()
48205304 .when(capturing, |d| d.bg(rgb(SELECTED)))
4821- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4822- this.rebinding = Some(action);
4823- cx.notify();
4824- }))
4825- .child(action.label())
4826- .child(if capturing {
5305+ .child(
48275306 div()
4828- .text_color(rgb(INK_DIM))
4829- .child(format!("press a key — {out} cancels"))
4830- } else {
4831- div().child(self.keymap.display(action))
4832- })
4833- .into_any_element(),
4834- );
4835- }
4836- for f in fixed {
4837- head(&mut rows);
4838- rows.push(
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.))
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.
5344+ div()
5345+ .id(("bind", i))
5346+ .flex_none()
5347+ .flex()
5348+ .min_h(px(KEYS_ROW_H))
5349+ .items_center()
5350+ .cursor_pointer()
5351+ .hover(|s| s.bg(rgb(HOVER)))
5352+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
5353+ this.rebinding = Some(action);
5354+ cx.notify();
5355+ }))
5356+ .child(if capturing {
5357+ div()
5358+ .text_color(rgb(INK_DIM))
5359+ .child(format!("press a key — {out} cancels"))
5360+ } else {
5361+ div().child(self.keymap.display(action))
5362+ }),
5363+ )
5364+ .into_any_element()
5365+ }
5366+ KeyRow::Fixed(f) => {
5367+ let f = &keymap::FIXED[f];
5368+ row()
48465369 .child(f.label)
48475370 // Dim, and no hover: this one is not a row you can click.
48485371 .child(div().text_color(rgb(INK_DIM)).child(f.chord))
4849- .into_any_element(),
4850- );
4851- }
5372+ .into_any_element()
5373+ }
5374+ });
48525375 }
48535376 Some(
48545377 div()
@@ -4875,7 +5398,7 @@ impl Player {
48755398 // Title and instruction are two children, never one
48765399 // wrapping line: a fixed-height slot whose text wrapped
48775400 // 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"))
48795402 // One status line, under the title where the eye starts.
48805403 // A refusal takes it over -- it is the more urgent of the
48815404 // two, and the notice bar it would otherwise appear in is
@@ -4893,7 +5416,10 @@ impl Player {
48935416 .child(
48945417 self.notice
48955418 .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+ }),
48975423 ),
48985424 )
48995425 // Capped and scrolling rather than as tall as the action
@@ -5329,20 +5855,28 @@ impl Player {
53295855 }
53305856
53315857 /// 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 them
5333- /// all. The curve is the clip's actual filter (`EqParams::response_db`
5334- /// reads the coefficients the samples go through), and it is redrawn on
5335- /// every pointer sample of a drag, so the shape bends under the hand.
5858+ /// curve, a handle per band sitting on it, each band's own bell under the
5859+ /// sum, and a row that reads and moves the picked band's three numbers. The
5860+ /// curve is the clip's actual filter (`EqParams::response_db` reads the
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.
53365863 ///
5337- /// The same scrim and width as the other two cards, and the same plain divs
5338- /// -- nothing here takes focus, so the root keeps the keyboard and the
5339- /// card's own strokes (`1`–`5`, up, down, `r`) reach it.
5864+ /// Wider than the other cards and wider still on a bigger window
5865+ /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
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.
53405870 ///
53415871 /// Every change is written at the clip as it is made
53425872 /// ([`Player::commit_eq`]), so what the card shows is always what is
53435873 /// playing: there is no OK button to forget, and closing it changes
53445874 /// 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> {
53465880 let (lane, idx) = self.eq_open?;
53475881 // The rate the engine filters this timeline at, so the drawn curve is
53485882 // the one those coefficients make -- near the top of the axis a 44.1 kHz
@@ -5396,13 +5930,20 @@ impl Player {
53965930 .bg(rgb(HOVER_DIM))
53975931 .cursor_pointer()
53985932 // 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.
54005936 .on_mouse_down(
54015937 MouseButton::Left,
54025938 cx.listener(|this, event: &MouseDownEvent, _, cx| {
54035939 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+ }
54045945 this.eq_dragging = true;
5405- this.drag_band(event.position.y, cx);
5946+ this.drag_band(event.position, cx);
54065947 }),
54075948 )
54085949 .child(bounds_probe(self.eq_graph.clone()))
@@ -5494,7 +6035,7 @@ impl Player {
54946035 })
54956036 .child(
54966037 div()
5497- .w(px(KEYS_W))
6038+ .w(px(eq_card_w(f32::from(viewport.width))))
54986039 .flex()
54996040 .flex_col()
55006041 .gap(px(2.))
@@ -5515,28 +6056,15 @@ impl Player {
55156056 .text_size(px(11.))
55166057 .text_color(rgb(INK_DIM))
55176058 .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()
55196060 })),
55206061 )
55216062 .child(graph)
5522- // Which band the keyboard is holding and what it is set
5523- // to: the curve shows the sum, and a band pushed against
5524- // one pulling the other way is not readable off it.
5525- .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(
5526- match picked {
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- ))
6063+ // Which band the keyboard is holding and every number it
6064+ // is set to, each with the pair of buttons that moves it:
6065+ // the curve shows the sum, and a band pushed against one
6066+ // pulling the other way is not readable off it.
6067+ .child(self.eq_numbers(picked, cx))
55406068 .child(
55416069 div()
55426070 .mt(px(4.))
@@ -5560,9 +6088,47 @@ impl Player {
55606088 }
55616089 this.commit_eq(cx);
55626090 }))
5563- .child("Flatten"),
6091+ .child("Flatten all"),
55646092 )
5565- // The analyser's switch, next to the one other
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"),
6130+ )
6131+ // The analyser's switch, next to the one other
55666132 // button the card has: `s` does the same, and a
55676133 // toggle only a keystroke can reach is one most
55686134 // people never find.
@@ -5595,6 +6161,103 @@ impl Player {
55956161 )
55966162 }
55976163
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+
55986261 /// The colour card: the graded frame's histogram over a row per control,
55996262 /// each row a bar the pointer drags straight to a value -- no stepper
56006263 /// buttons, because a slider is a thing to pull, and the arrow keys still
@@ -6432,7 +7095,6 @@ impl Player {
64327095 let menu = self.context_menu?;
64337096 let session = self.session.as_ref()?;
64347097 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
6435- let playhead = frame_at(session.now(), self.fps);
64367098 let source = session.sources().get(clip.source).cloned()?;
64377099 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
64387100 let row = |n: usize| {
@@ -6486,7 +7148,20 @@ impl Player {
64867148 }
64877149 } else {
64887150 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();
64907165 // The one item that is not about this clip says so, and says it
64917166 // here rather than in the registry: the stroke is global too,
64927167 // but its row in the keys menu is not sitting on a clip.
@@ -6498,20 +7173,42 @@ impl Player {
64987173 rows.push(
64997174 row(rows.len())
65007175 .child(label)
6501- .child(
6502- div()
7176+ .child(match refusal.why() {
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()
65037187 .text_color(rgb(INK_DIM))
65047188 .child(self.keymap.display(action)),
6505- )
7189+ })
65067190 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
65077191 .when(enabled, |d| {
65087192 d.cursor_pointer()
65097193 .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| {
65117195 // Closed first: the action moves the very
65127196 // indices this menu is holding.
65137197 this.context_menu = None;
6514- this.act(action, cx);
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 {
7210+ this.act(action, cx);
7211+ }
65157212 }))
65167213 })
65177214 .into_any_element(),
@@ -6611,6 +7308,137 @@ impl Player {
66117308 )
66127309 }
66137310
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+ )
crates/engine-hw/src/lib.rsmodified+4 -3
@@ -59,7 +59,8 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
5959 /// still loads and still decodes H.264 (it simply refuses the newer codecs'
6060 /// files at `Demuxer`).
6161 ///
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.
6364 /// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit
6465 /// I420 every frame here is ([`Session::emit`]).
6566 ///
@@ -67,8 +68,8 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
6768 /// interface all the way to the renderer. That costs the low two bits of a Main
6869 /// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every
6970 /// stage between here and the texture upload, not to this file.
70-/// VP9 profile 2 and 10-bit AV1 are still refused by `Demuxer`: neither codec
71-/// states its depth where this reads it.
71+/// VP9 profile 2 is still refused by `Demuxer`: a VP9 stream does not state its
72+/// depth where that reads it (an `av1C` and an `hvcC` both do).
7273 enum Decoder {
7374 H264(Dec<H264>),
7475 Hevc(Dec<H265>),
crates/engine/Cargo.tomlmodified+10 -0
@@ -66,6 +66,16 @@ symphonia = { version = "0.6", default-features = false, features = [
6666 ] }
6767 oxideav-ac3 = "=0.0.10"
6868 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 }
6979 # The software AV1 encoder, and the only new name in this list that was already
7080 # in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image
7181 # crate, so this links what the build already compiled. BSD-2 with the AOM
crates/engine/src/audio.rsmodified+381 -90
@@ -66,10 +66,6 @@ const PRE_ROLL: u32 = 2;
6666 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.
6767 const SAMPLES_PER_PACKET: u32 = 1024;
6868
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-
7369 /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
7470 /// 256-sample overlap-add the target frame is reconstructed with.
7571 const AC3_PRE_ROLL: u32 = 1;
@@ -207,10 +203,14 @@ impl AudioSession {
207203 /// pause — the master clock counts what the device has been fed, so a hole
208204 /// that fed nothing would stall the whole timeline on it.
209205 ///
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+ ///
210210 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
211- /// is empty or its first entry has no AAC track; a later source that is
212- /// missing audio or disagrees on rate/layout is an `Err` — import refuses
213- /// those up front (one timeline, one output device), this is the backstop.
211+ /// is empty or its first entry has no AAC track; a later source that
212+ /// disagrees on rate/layout is an `Err` — import refuses those up front (one
213+ /// timeline, one output device), this is the backstop.
214214 pub fn open_multi_segments(
215215 sources: &[PathBuf],
216216 segs: &[(Option<usize>, f64, f64)],
@@ -298,11 +298,18 @@ impl AudioSession {
298298 first.check_decoder()?;
299299
300300 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();
301305 tracks[at] = Some(first);
302306 for &(source, ..) in segs {
303307 let Some(source) = source else {
304308 continue; // a gap opens no file
305309 };
310+ if silent.get(source) == Some(&true) {
311+ continue;
312+ }
306313 let slot = tracks
307314 .get_mut(source)
308315 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
@@ -310,8 +317,14 @@ impl AudioSession {
310317 continue; // already opened, and the checks below already ran
311318 }
312319 let (path, stream) = &sources[source];
313- let track = Track::open(path, *stream)?
314- .ok_or_else(|| format!("source {source} has no audio track"))?;
320+ // A source with no audio track at all is not a failure: its
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+ };
315328 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
316329 return Err(format!(
317330 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
@@ -328,14 +341,15 @@ impl AudioSession {
328341
329342 let segments: Vec<Segment> = segs
330343 .iter()
331- .map(|&(source, start_secs, end_secs)| match source {
332- Some(source) => tracks[source]
333- .as_ref()
334- .expect("opened above")
335- .segment(source, start_secs, end_secs),
336- None => Segment::silence(
337- ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
338- ),
344+ // A gap, and a source with no track to decode, are the same stretch
345+ // of nothing: as many frames of silence as the window is long.
346+ .map(|&(source, start_secs, end_secs)| {
347+ match source.and_then(|source| Some((source, tracks[source].as_ref()?))) {
348+ Some((source, track)) => track.segment(source, start_secs, end_secs),
349+ None => Segment::silence(
350+ ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
351+ ),
352+ }
339353 })
340354 .collect();
341355 // Chunk numbering is continuous across every join, counted from the first
@@ -541,17 +555,26 @@ impl AudioSession {
541555 /// -- nothing to tell the user there. Header only, and only worth calling
542556 /// once the open has already returned no audio.
543557 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
544- // Matroska: AAC is read out of one ([`Track::open`]) and everything
545- // else -- Opus, AC-3, DTS, none of which symphonia decodes at any
546- // version -- is named rather than left playing silent with no reason
547- // given. A Matroska file with no audio track at all returns `None` here
548- // like any other silent file.
558+ // Matroska: what symphonia reads out of one ([`Track::open`]) plus the
559+ // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder
560+ // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here
561+ // has at any version -- is named rather than left playing silent with no
562+ // reason given. A Matroska file with no audio track at all returns
563+ // `None` here like any other silent file.
549564 if crate::demux::is_matroska(path.as_ref()) {
550- return Ok(
551- crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {
552- format!("the {codec} track of this Matroska file cannot be decoded (AAC only)")
553- }),
554- );
565+ let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else {
566+ return Ok(None);
567+ };
568+ // An AC-3 track that came up silent all the same is one that could
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+ }));
555578 }
556579 let file = File::open(path.as_ref())?;
557580 let size = file.metadata()?.len();
@@ -599,11 +622,29 @@ impl AudioSession {
599622 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
600623 let path = path.as_ref();
601624 // A Matroska file has exactly one readable audio stream here -- the
602- // reader's default track ([`SymTrack::open`]) -- so it lists like a
625+ // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one
626+ // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a
603627 // standalone audio file rather than like an mp4, and one with no
604628 // readable track at all lists as the silent source it is.
605629 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 {
607648 return Ok(Vec::new());
608649 };
609650 return Ok(vec![StreamInfo {
@@ -616,7 +657,7 @@ impl AudioSession {
616657 }]);
617658 }
618659 if crate::is_audio(path) {
619- let track = SymTrack::open(path)?;
660+ let track = SymTrack::open_required(path)?;
620661 return Ok(vec![StreamInfo {
621662 index: 0,
622663 codec: track.codec.into(),
@@ -743,15 +784,18 @@ impl AudioSession {
743784 /// half a packet over the whole list however many files it spans, and the
744785 /// extra priming packet is still the very first segment's alone.
745786 ///
746- /// Every source must declare the same [`AacTrackParams`]: the copy becomes
747- /// one output track with one esds. Import refuses a mismatch up front; the
748- /// check here is the backstop, as is the missing-track `Err`.
787+ /// Every source that *has* a track must declare the same
788+ /// [`AacTrackParams`]: the copy becomes one output track with one esds.
789+ /// Import refuses a mismatch up front; the check here is the backstop.
749790 ///
750791 /// A segment naming **no** source is a gap, and is copied as that many
751792 /// packets of [`silent_packet`] silence — the rounding debt carried through
752793 /// it like any other, so the hole occupies its exact duration and the audio
753794 /// 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`]).
755799 pub fn copy_multi_segments(
756800 sources: &[PathBuf],
757801 segs: &[(Option<usize>, f64, f64)],
@@ -770,24 +814,34 @@ impl AudioSession {
770814 sources: &[(PathBuf, usize)],
771815 segs: &[(Option<usize>, f64, f64)],
772816 ) -> 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 {
774831 return Ok(None); // no segments, or nothing but silence
775832 };
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);
785833
786834 let sample_rate = params.sample_rate;
787835 let mut err = 0i64;
788836 let mut packets: Vec<AacPacket> = Vec::new();
789837 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 {
791845 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
792846 let bytes = silent_packet(params.chan_conf)?;
793847 // A reader drops the first packet of an AAC track as the
@@ -805,7 +859,6 @@ impl AudioSession {
805859 }
806860 continue;
807861 };
808- let track = source_at(&mut tracks, sources, source)?;
809862 if track.track_params() != params {
810863 return Err(format!(
811864 "source {source} audio is {:?}, the timeline's is {params:?}",
@@ -866,24 +919,25 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
866919 }
867920 }
868921
869-/// The source at `index`, on the stream it names, opened on first use. Sources
870-/// a segment list never names are never touched: a project's list only grows.
922+/// The source at `index`, on the stream it names, opened on first use -- and
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.
871928 fn source_at<'a>(
872- tracks: &'a mut [Option<AacTrack>],
929+ tracks: &'a mut [Option<Option<AacTrack>>],
873930 sources: &[(PathBuf, usize)],
874931 index: usize,
875-) -> crate::Result<&'a mut AacTrack> {
932+) -> crate::Result<Option<&'a mut AacTrack>> {
876933 let slot = tracks
877934 .get_mut(index)
878935 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
879936 if slot.is_none() {
880937 let (path, stream) = &sources[index];
881- *slot = Some(
882- copy_track(path, *stream)?
883- .ok_or_else(|| format!("source {index} has no audio track"))?,
884- );
938+ *slot = Some(copy_track(path, *stream)?);
885939 }
886- Ok(slot.as_mut().expect("just opened"))
940+ Ok(slot.as_mut().expect("just opened").as_mut())
887941 }
888942
889943 /// 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>> {
924978 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
925979 // sample table can hold. The export decodes it and encodes AAC, exactly
926980 // 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")),
928982 }
929983 }
930984
@@ -947,6 +1001,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error {
9471001 enum Track {
9481002 Aac(AacTrack),
9491003 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),
9501007 Sym(SymTrack),
9511008 }
9521009
@@ -965,20 +1022,43 @@ impl Track {
9651022 /// has exactly one, so any `stream` above 0 there is a promise the file
9661023 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
9671024 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
968- // A Matroska file goes straight to symphonia, whose `mkv` reader is the
969- // one thing here that reads its packets -- neither mp4 reader can open
970- // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia
971- // has no such decoder at any version) leaves the source the silent one
972- // it always was, which `AudioSession::unsupported` puts into words,
973- // rather than failing the import of a file whose picture is fine.
1025+ // A Matroska file goes to symphonia, whose `mkv` reader is the one thing
1026+ // here that reads its packets -- neither mp4 reader can open the file at
1027+ // all -- except for the two codecs symphonia has no decoder for at any
1028+ // version and this project does: AC-3 and E-AC-3 are handed to the Dolby
1029+ // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
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.
9741034 if crate::demux::is_matroska(path) {
9751035 if stream > 0 {
9761036 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
9771037 }
978- return Ok(SymTrack::open(path)
979- .ok()
980- .filter(|t| t.decoder().is_ok())
981- .map(Self::Sym));
1038+ match MkvAc3Track::open(path) {
1039+ Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1040+ Ok(None) => {}
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)));
9821062 }
9831063 let audio_file = crate::is_audio(path);
9841064 // Ahead of the AAC reader, because that one answers "not AAC" for a
@@ -999,13 +1079,14 @@ impl Track {
9991079 if stream > 0 {
10001080 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
10011081 }
1002- SymTrack::open(path).map(|track| Some(Self::Sym(track)))
1082+ SymTrack::open_required(path).map(|track| Some(Self::Sym(track)))
10031083 }
10041084
10051085 fn sample_rate(&self) -> u32 {
10061086 match self {
10071087 Self::Aac(t) => t.sample_rate,
10081088 Self::Ac3(t) => t.sample_rate,
1089+ Self::Mkv(t) => t.sample_rate,
10091090 Self::Sym(t) => t.sample_rate,
10101091 }
10111092 }
@@ -1021,6 +1102,11 @@ impl Track {
10211102 1 | 2 => Ok(t.channels),
10221103 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
10231104 },
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+ },
10241110 Self::Sym(t) => match t.channels {
10251111 1 | 2 => Ok(t.channels),
10261112 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
@@ -1033,6 +1119,7 @@ impl Track {
10331119 match self {
10341120 Self::Aac(t) => t.total_samples,
10351121 Self::Ac3(t) => t.total_samples,
1122+ Self::Mkv(t) => t.total_samples,
10361123 Self::Sym(t) => t.total_samples,
10371124 }
10381125 }
@@ -1042,6 +1129,9 @@ impl Track {
10421129 match self {
10431130 Self::Aac(t) => t.priming,
10441131 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,
10451135 Self::Sym(t) => t.priming,
10461136 }
10471137 }
@@ -1052,6 +1142,7 @@ impl Track {
10521142 match self {
10531143 Self::Aac(t) => t.segment(source, start_secs, end_secs),
10541144 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
1145+ Self::Mkv(t) => t.segment(source, start_secs, end_secs),
10551146 Self::Sym(t) => {
10561147 let media_target = t.media(start_secs);
10571148 Segment {
@@ -1073,7 +1164,10 @@ impl Track {
10731164 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
10741165 }
10751166 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)?;
10771171 }
10781172 Self::Sym(t) => {
10791173 t.decoder()?;
@@ -1110,7 +1204,13 @@ struct SymTrack {
11101204 }
11111205
11121206 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>> {
11141214 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
11151215 // The extension is a hint, not a decision: the probe reads the magic and
11161216 // is free to disagree, which is what makes a mislabelled file work.
@@ -1124,9 +1224,9 @@ impl SymTrack {
11241224 FormatOptions::default(),
11251225 MetadataOptions::default(),
11261226 )?;
1127- let track = reader
1128- .default_track(SymKind::Audio)
1129- .ok_or_else(|| format!("{} has no audio track", path.display()))?;
1227+ let Some(track) = reader.default_track(SymKind::Audio) else {
1228+ return Ok(None);
1229+ };
11301230 let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);
11311231 let time_base = track
11321232 .time_base
@@ -1147,7 +1247,7 @@ impl SymTrack {
11471247 let codec = symphonia::default::get_codecs()
11481248 .get_audio_decoder(params.codec)
11491249 .map_or("an unsupported format", |d| d.codec.info.short_name);
1150- Ok(Self {
1250+ Ok(Some(Self {
11511251 reader,
11521252 track_id,
11531253 sample_rate,
@@ -1161,7 +1261,14 @@ impl SymTrack {
11611261 time_base,
11621262 params,
11631263 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())
11651272 }
11661273
11671274 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
@@ -1326,9 +1433,9 @@ impl Ac3Track {
13261433 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
13271434 .nfchans;
13281435 let requested = (nfchans > 1).then_some(2);
1329- let mut decoder = ac3_decoder(requested)?;
1436+ let mut decoder = ac3_decoder("ac3", requested)?;
13301437 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)
13321439 .filter(|&c| c > 0)
13331440 .ok_or("the first AC-3 syncframe decoded to nothing")?;
13341441
@@ -1373,6 +1480,101 @@ impl Ac3Track {
13731480 }
13741481 }
13751482
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+
13761578 /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
13771579 /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
13781580 /// 5.1 track at all. Fresh per segment for the same reason every other decoder
@@ -1383,32 +1585,47 @@ impl Ac3Track {
13831585 /// mono track asks for no downmix at all and stays the mono source it is. The
13841586 /// upgrade path is `Some(2)` unconditionally once the library duplicates the
13851587 /// 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>> {
13871594 let mut registry = CodecRegistry::new();
13881595 oxideav_ac3::register_codecs(&mut registry);
1389- let mut params = CodecParameters::audio(CodecId::new("ac3"));
1596+ let mut params = CodecParameters::audio(CodecId::new(codec));
13901597 params.channels = channels;
13911598 registry
13921599 .first_decoder(&params)
13931600 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
13941601 }
13951602
1396-/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the
1397-/// decoder wants more input before it can hand a frame back, which is not an
1398-/// error. The library speaks S16 little-endian; `/32768` is the whole
1399-/// conversion, and it lands in the `[-1, 1)` every other reader here emits.
1400-fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> {
1603+/// One syncframe in, one buffer of interleaved f32 out and the frames per
1604+/// channel it holds. `Ok(None)` when the decoder wants more input before it can
1605+/// hand a frame back, which is not an error. The library speaks S16
1606+/// little-endian; `/32768` is the whole conversion, and it lands in the
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)>> {
14011617 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
14021618 decoder
14031619 .send_packet(&packet)
14041620 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
14051621 match decoder.receive_frame() {
1406- Ok(Frame::Audio(audio)) => Ok(Some(
1622+ Ok(Frame::Audio(audio)) => Ok(Some((
14071623 audio.data[0]
14081624 .chunks_exact(2)
14091625 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
14101626 .collect(),
1411- )),
1627+ u64::from(audio.samples),
1628+ ))),
14121629 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
14131630 Err(oxideav_core::Error::NeedMore) => Ok(None),
14141631 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
@@ -2026,6 +2243,21 @@ fn run(mut w: Worker) {
20262243 }
20272244 continue;
20282245 }
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+ }
20292261 Track::Ac3(track) => {
20302262 if !run_ac3(
20312263 track,
@@ -2191,7 +2423,7 @@ fn run_ac3(
21912423 timeline: &mut u64,
21922424 tx: &SyncSender<AudioChunk>,
21932425 ) -> bool {
2194- let mut decoder = match ac3_decoder(track.requested) {
2426+ let mut decoder = match ac3_decoder("ac3", track.requested) {
21952427 Ok(decoder) => decoder,
21962428 Err(e) => {
21972429 eprintln!("audio decoder init failed: {e}");
@@ -2200,7 +2432,6 @@ fn run_ac3(
22002432 };
22012433 let mut pos = seg.start_pos;
22022434 for id in seg.start_id..=track.sample_count {
2203- let mut interleaved;
22042435 if pos >= seg.media_end {
22052436 return true; // segment done, on to the next one
22062437 }
@@ -2212,15 +2443,75 @@ fn run_ac3(
22122443 return true;
22132444 }
22142445 };
2215- match decode_ac3(&mut decoder, &sample.bytes) {
2216- Ok(Some(pcm)) => interleaved = pcm,
2446+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) {
2447+ Ok(Some(decoded)) => decoded,
22172448 Ok(None) => continue, // the decoder wants another frame first
22182449 Err(e) => {
22192450 eprintln!("audio decode error at sample {id}: {e}");
22202451 return true;
22212452 }
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;
22222467 }
2223- let next = pos + (interleaved.len() / channels) as u64;
2468+ pos = next;
2469+ }
2470+ true
2471+}
2472+
2473+/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
2474+/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
2475+/// stereo downmix are the same ones; only where a packet comes from differs.
2476+/// `false` means the consumer went away.
2477+fn run_mkv_ac3(
2478+ track: &mut MkvAc3Track,
2479+ seg: &Segment,
2480+ mut eq: Option<&mut EqState>,
2481+ speed: &mut Option<Resample>,
2482+ channels: usize,
2483+ timeline: &mut u64,
2484+ tx: &SyncSender<AudioChunk>,
2485+) -> bool {
2486+ let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) {
2487+ Ok(decoder) => decoder,
2488+ Err(e) => {
2489+ eprintln!("audio decoder init failed: {e}");
2490+ return true;
2491+ }
2492+ };
2493+ let mut pos = seg.start_pos;
2494+ for id in seg.start_id as usize.. {
2495+ if pos >= seg.media_end {
2496+ return true; // segment done, on to the next one
2497+ }
2498+ let block = match track.mkv.frame(id) {
2499+ Ok(Some(bytes)) => bytes,
2500+ Ok(None) => return true, // end of the track
2501+ Err(e) => {
2502+ eprintln!("audio demux error at block {id}: {e}");
2503+ return true;
2504+ }
2505+ };
2506+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
2507+ Ok(Some(decoded)) => decoded,
2508+ Ok(None) => continue, // the decoder wants another frame first
2509+ Err(e) => {
2510+ eprintln!("audio decode error at block {id}: {e}");
2511+ return true;
2512+ }
2513+ };
2514+ let next = pos + samples;
22242515 if !emit(
22252516 &mut interleaved,
22262517 channels,
crates/engine/src/demux.rsmodified+464 -50
@@ -103,9 +103,10 @@ impl Demuxer {
103103 }
104104
105105 /// Bits per luma sample the stream is coded at: 8 for everything but an
106- /// HEVC Main 10 track, which decodes into a P010 surface rather than an
107- /// NV12 one. Not part of [`VideoMeta`] because nothing above the plugin has
108- /// a use for it -- what comes out of the read-back is 8-bit either way.
106+ /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface
107+ /// rather than an NV12 one. Not part of [`VideoMeta`] because nothing above
108+ /// the plugin has a use for it -- what comes out of the read-back is 8-bit
109+ /// either way.
109110 pub fn bit_depth(&self) -> u8 {
110111 match self {
111112 Self::Mp4(d) => d.bit_depth,
@@ -234,7 +235,9 @@ impl Mp4Demuxer {
234235 let (_, entry) = sample_entry(path, track_id)?;
235236 let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C")
236237 .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;
238241 }
239242 // No parameter sets: a VP9 sample is self-contained.
240243 Codec::Vp9 => {}
@@ -326,18 +329,21 @@ impl Mp4Demuxer {
326329 }
327330 }
328331
329-/// One Matroska block of the video track: where its bytes are and whether a
330-/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7
331-/// MB of index -- the price of knowing the frame count and the sync points of a
332+/// One Matroska block of an indexed track: where its bytes are, whether a
333+/// decoder may start on it, and when it is presented (in `TimestampScale`
334+/// ticks, which is what a sound track seeks against -- Matroska indexes no
335+/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of
336+/// index -- the price of knowing the frame count and the sync points of a
332337 /// container that indexes neither.
333338 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
334339 struct Block {
335340 at: u64,
336341 len: usize,
337342 key: bool,
343+ ts: i64,
338344 }
339345
340-/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`).
346+/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
341347 ///
342348 /// The whole segment is walked once at open -- element *headers* only, the block
343349 /// payloads are seeked over -- because Matroska carries no sample table: the
@@ -355,10 +361,11 @@ pub struct MkvDemuxer {
355361 ///
356362 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
357363 /// 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.
359366 config: Vec<u8>,
360- /// Bytes of the NAL length prefix an HEVC block is written with; unused by
361- /// AV1, whose block is one temporal unit and carries no prefixes.
367+ /// Bytes of the NAL length prefix an HEVC or H.264 block is written with;
368+ /// unused by AV1, whose block is one temporal unit and carries no prefixes.
362369 nal_length: usize,
363370 /// Bits per luma sample; see [`Demuxer::bit_depth`].
364371 bit_depth: u8,
@@ -374,7 +381,7 @@ impl MkvDemuxer {
374381 let mut file = File::open(path)?;
375382 let end = file.metadata()?.len();
376383 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)?;
378385 let video = match video {
379386 Some(video) => video,
380387 // Named, because "no video track" is a lie about a file that has one
@@ -382,7 +389,7 @@ impl MkvDemuxer {
382389 None => {
383390 return Err(match other {
384391 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"
386393 ),
387394 None => "this Matroska file has no video track".to_string(),
388395 }
@@ -483,13 +490,99 @@ impl MkvDemuxer {
483490
484491 /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
485492 /// `None` for a Matroska file with no sound at all. Header only, and only worth
486-/// calling once a session has come up silent: no audio track of a Matroska file
487-/// is decoded yet, so this exists to say which one is being left out.
493+/// calling once a session has come up silent: a Matroska file's sound is read
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.
488496 pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
489497 let mut file = File::open(path)?;
490498 let end = file.metadata()?.len();
491499 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+ }
493586 }
494587
495588 /// 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)> {
539632 Err("no Segment element: not a Matroska file".into())
540633 }
541634
542-/// The video track of `segment`, the codec id of its first audio track, and the
543-/// codec id of a video track this cannot read -- the last two are what tell a
544-/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`])
545-/// or refuses to open at all.
635+/// The video track of `segment`, the number and codec id of its first audio
636+/// track, the codec id of a video track this cannot read, and the segment's
637+/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a
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.
546641 ///
547642 /// Header only: the walk stops at the first `Cluster`, so this costs a handful
548643 /// of seeks whatever the file weighs.
549644 fn mkv_tracks(
550645 file: &mut File,
551646 segment: (u64, u64),
552-) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> {
647+) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> {
553648 let (mut video, mut audio, mut other) = (None, None, None);
554649 let mut timestamp_scale = 1_000_000;
555650 let mut at = segment.0;
@@ -572,7 +667,9 @@ fn mkv_tracks(
572667 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
573668 MkvEntry::Video(track) if video.is_none() => video = Some(track),
574669 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+ }
576673 _ => {}
577674 }
578675 }
@@ -583,7 +680,7 @@ fn mkv_tracks(
583680 }
584681 at = stop;
585682 }
586- Ok((video, audio, other))
683+ Ok((video, audio, other, timestamp_scale))
587684 }
588685
589686 /// What one `TrackEntry` turned out to be.
@@ -591,8 +688,9 @@ enum MkvEntry {
591688 Video(MkvVideo),
592689 /// A video track in a codec this does not read, by the name it gives itself.
593690 OtherVideo(String),
594- /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...).
595- Audio(String),
691+ /// An audio track: its track number, which is what [`MkvAudio`] indexes the
692+ /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...).
693+ Audio(u64, String),
596694 /// Subtitles, buttons: nobody's here.
597695 Other,
598696 }
@@ -638,13 +736,23 @@ fn mkv_track_entry(
638736 // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4
639737 // sample entry carries, so it parses with the very same reader.
640738 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+ }
642743 (1, "V_MPEGH/ISO/HEVC") => {
643744 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
644745 (Codec::Hevc, nal_length, sets, bit_depth)
645746 }
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+ }
646754 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
647- (2, _) => return Ok(MkvEntry::Audio(codec)),
755+ (2, _) => return Ok(MkvEntry::Audio(number, codec)),
648756 _ => return Ok(MkvEntry::Other),
649757 };
650758 Ok(MkvEntry::Video(MkvVideo {
@@ -660,29 +768,79 @@ fn mkv_track_entry(
660768 }))
661769 }
662770
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+
663813 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
664814 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same
665815 /// low-overhead format the blocks are in, so it needs no reframing.
666816 ///
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+///
667822 /// An empty record is not an error -- an encoder that repeats its sequence
668-/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for
669-/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage`
670-/// read-back are 8-bit, and the upgrade path is a P010 pool.
671-fn parse_av1c(rec: &[u8]) -> crate::Result<Vec<u8>> {
823+/// header in-band needs none -- and is taken as 8-bit, which is what the depth
824+/// defaults to everywhere else here.
825+fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> {
672826 if rec.is_empty() {
673- return Ok(Vec::new());
827+ return Ok((Vec::new(), 8));
674828 }
675829 let &flags = rec
676830 .get(2)
677831 .ok_or("av1C record shorter than its fixed header")?;
678- if flags & 0x40 != 0 {
679- return Err(format!(
680- "{}-bit AV1 is not supported yet — this file is not 8-bit",
681- if flags & 0x20 != 0 { 12 } else { 10 }
682- )
683- .into());
684- }
685- Ok(rec.get(4..).unwrap_or_default().to_vec())
832+ // `twelve_bit` only says anything when `high_bitdepth` is set (AV1 §5.5.1),
833+ // so it is read where the record means it and nowhere else.
834+ let bit_depth = match (flags & 0x40 != 0, flags & 0x20 != 0) {
835+ (true, true) => {
836+ return Err(
837+ "12-bit AV1 is not supported — 8- and 10-bit are what the decoder carries".into(),
838+ );
839+ }
840+ (true, false) => 10,
841+ _ => 8,
842+ };
843+ Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth))
686844 }
687845
688846 /// Every block of track `number`, in storage order, with the presentation span
@@ -743,11 +901,17 @@ fn mkv_blocks(
743901 if block.number != number {
744902 continue;
745903 }
746- // Lacing packs several frames into one block. Audio muxers use it,
747- // video ones do not, and guessing at frame boundaries inside a laced
748- // block is not something to do silently.
904+ // Lacing packs several frames into one block, behind a header of
905+ // frame sizes this does not read. Video muxers write none; an audio
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.
749913 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());
751915 }
752916 let ts = cluster_ts + i64::from(block.rel);
753917 span = Some(match span {
@@ -758,6 +922,7 @@ fn mkv_blocks(
758922 at: block.at,
759923 len: block.len,
760924 key,
925+ ts,
761926 });
762927 }
763928 }
@@ -1138,6 +1303,216 @@ fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
11381303 ))
11391304 }
11401305
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+
11411516 #[cfg(test)]
11421517 mod tests {
11431518 use super::*;
@@ -1195,6 +1570,37 @@ mod tests {
11951570 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
11961571 }
11971572
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+
11981604 /// EBML's variable-length integers, which every Matroska read starts with:
11991605 /// the leading zeros of the first byte are the length, an *id* keeps its
12001606 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
@@ -1226,8 +1632,9 @@ mod tests {
12261632 }
12271633
12281634 /// The `av1C` record: four fixed bytes and then the sequence header OBU,
1229- /// which is handed to the decoder as it stands. 10-bit is refused by name
1230- /// exactly as HEVC Main 10 is, and for the same 8-bit read-back reason.
1635+ /// which is handed to the decoder as it stands, and the depth beside it --
1636+ /// 10-bit reads as 10 (the P010 pool, exactly as HEVC Main 10), 12-bit is
1637+ /// refused by name.
12311638 #[test]
12321639 fn reads_the_sequence_header_out_of_an_av1c_record() {
12331640 // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
@@ -1236,14 +1643,16 @@ mod tests {
12361643 rec.extend_from_slice(&[
12371644 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
12381645 ]);
1239- let config = parse_av1c(&rec).unwrap();
1646+ let (config, depth) = parse_av1c(&rec).unwrap();
12401647 assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
12411648 assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
1649+ assert_eq!(depth, 8);
12421650
12431651 let mut ten = rec.clone();
12441652 ten[2] |= 0x40; // high_bitdepth
1245- let refused = parse_av1c(&ten).unwrap_err().to_string();
1246- assert!(refused.contains("10-bit"), "{refused}");
1653+ let (ten_config, ten_depth) = parse_av1c(&ten).unwrap();
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");
12471656 let mut twelve = ten.clone();
12481657 twelve[2] |= 0x20; // twelve_bit
12491658 assert!(
@@ -1252,10 +1661,15 @@ mod tests {
12521661 .to_string()
12531662 .contains("12-bit")
12541663 );
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);
12551669
12561670 // An encoder that repeats its sequence header in-band writes no record
12571671 // 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());
12591673 assert!(parse_av1c(&[0x81, 0x05]).is_err());
12601674 }
12611675
crates/engine/src/edith.rsmodified+167 -24
@@ -1,13 +1,15 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 9
4+//! edith 10
55 //! playhead 90
66 //! resolution 1920 1080
77 //! fps 30.0
88 //! limiter -1.0 on
99 //! source 0 test_av.mp4
1010 //! source 1 /elsewhere/test_av2.mp4
11+//! subtitle - subs.srt
12+//! subtitle 3 test_av.mp4
1113 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
1214 //! color 0.1:1.2:0.9:-0.3
1315 //! video 1 0 0 120 0 0 0 0 fit 1000
@@ -23,6 +25,15 @@
2325 //! is an answer only a project holding a video has
2426 //! ([`crate::PlaybackSession::open_project`]).
2527 //!
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+//!
2637 //! The `limiter` line is the master limiter over the whole mix
2738 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
2839 //! spelled `on` or `off`. Left out when it is the default, which is off.
@@ -79,7 +90,9 @@
7990 //! is the only way an empty lane could still be there on the way back. A lane
8091 //! number may not skip one of its kind.
8192 //!
82-//! **Version 8** was this without the `fps` and `limiter` lines and without
93+//! **Version 9** was this without the `subtitle` lines: such a project shows no
94+//! subtitles, which is all any project could do.
95+//! **Version 8** was that without the `fps` and `limiter` lines and without
8396 //! the `gain` ones: such a project mixes every lane at unity, limits nothing,
8497 //! and comes back at the rate its scaffolding source runs at.
8598 //! **Version 7** was that without the clip's speed field -- every clip of such
@@ -97,8 +110,8 @@
97110 //! cumulatively and copied onto both lanes as one group each, which is exactly
98111 //! what a v1 timeline meant, and an older file simply equalizes and grades
99112 //! nothing, and an older one plays everything at real time, and an older one
100-//! mixes flat -- and saving any of them writes v9. An older reader refuses a
101-//! newer file by name.
113+//! mixes flat, and an older one shows no subtitles -- and saving any of them
114+//! writes v10. An older reader refuses a newer file by name.
102115 //!
103116 //! Text because an edit list is a few integers and a path, and a path is
104117 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -129,10 +142,12 @@ use crate::eq::{Band, BandKind, EqParams};
129142 use crate::limiter::Limiter;
130143 use crate::project::{Clip, Lane, LaneKind, Source, Speed};
131144 use crate::scale::FitPolicy;
145+use crate::subtitle::SubtitleTrack;
132146
133147 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
134148 /// 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";
136151 const MAGIC_V8: &[u8] = b"edith 8";
137152 const MAGIC_V7: &[u8] = b"edith 7";
138153 const MAGIC_V6: &[u8] = b"edith 6";
@@ -169,6 +184,11 @@ pub struct Document {
169184 /// The master limiter. Off for every dialect before v9, and for a v9 file
170185 /// that leaves the line out.
171186 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>)>,
172192 /// The timeline's frame rate. `None` for every dialect before v9 and for a
173193 /// v9 file that leaves it out, which both mean "whatever the scaffolding
174194 /// source runs at" -- the inference a project of nothing but stills and
@@ -188,6 +208,7 @@ pub fn save(
188208 sources: &[Source],
189209 lanes: &[(LaneKind, Vec<Clip>)],
190210 gains: &[f32],
211+ subtitles: &[SubtitleTrack],
191212 eq: &[EqParams],
192213 color: &[ColorParams],
193214 resolution: (u32, u32),
@@ -206,7 +227,8 @@ pub fn save(
206227 let result = std::fs::File::create(&part)
207228 .and_then(|mut f| {
208229 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,
210232 ))?;
211233 f.sync_all()
212234 })
@@ -243,6 +265,7 @@ fn emit(
243265 sources: &[Source],
244266 lanes: &[(LaneKind, Vec<Clip>)],
245267 gains: &[f32],
268+ subtitles: &[SubtitleTrack],
246269 eq: &[EqParams],
247270 color: &[ColorParams],
248271 resolution: (u32, u32),
@@ -280,6 +303,16 @@ fn emit(
280303 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
281304 out.push(b'\n');
282305 }
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+ }
283316 // Before the clips, for the reason the sources are: a clip names one by the
284317 // position of its line, so the line has to be there first.
285318 for params in eq {
@@ -379,9 +412,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
379412 // The dialects that wrote a source line without its stream field. Reading
380413 // one is the whole of what "an old project still opens" means here.
381414 let streamless = v1 || first == MAGIC_V2;
382- // The one that carries the mix -- lane volumes, the master limiter and the
383- // rate the timeline was cut at...
384- let v9 = first == MAGIC;
415+ // The one that carries subtitle tracks...
416+ let v10 = 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;
385420 // ...the ones that carry a per-clip speed...
386421 let v8 = v9 || first == MAGIC_V8;
387422 // ...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> {
418453 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
419454 // no limiter, and the rate inferred from the scaffold as it always was.
420455 gains: Vec::new(),
456+ // Nothing before v10 shows a subtitle.
457+ subtitles: Vec::new(),
421458 limiter: Limiter::default(),
422459 fps: None,
423460 playhead: 0,
@@ -528,6 +565,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
528565 doc.gains.resize(doc.lanes.len(), 0.0);
529566 doc.gains[at] = float(f[2], n)?;
530567 }
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+ }
531593 b"source" => {
532594 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
533595 return Err(format!("line {n}: source after a clip").into());
@@ -963,6 +1025,7 @@ mod tests {
9631025 sources,
9641026 lanes,
9651027 &[],
1028+ &[],
9661029 eq,
9671030 color,
9681031 resolution,
@@ -972,6 +1035,84 @@ mod tests {
9721035 )
9731036 }
9741037
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+
9751116 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
9761117 Clip {
9771118 start,
@@ -1032,7 +1173,7 @@ mod tests {
10321173 let bytes = flat(&dir, &sources, &lanes, 12);
10331174 assert_eq!(
10341175 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\
10361177 source 2 /elsewhere/b.mp4\n\
10371178 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
10381179 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1069,7 +1210,7 @@ mod tests {
10691210 let bytes = flat(&dir, &sources, &lanes, 7);
10701211 assert_eq!(
10711212 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\
10731214 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
10741215 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
10751216 "an empty lane is a line of its own; everything else is its clips"
@@ -1177,7 +1318,7 @@ mod tests {
11771318 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
11781319 assert_eq!(
11791320 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\
11811322 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
11821323 eq 16777215.0:-0.1:3.918315e-39:hs\n\
11831324 eq\n\
@@ -1281,7 +1422,7 @@ mod tests {
12811422 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
12821423 assert_eq!(
12831424 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\
12851426 color 0.1:1.2:0.9:-0.3\n\
12861427 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
12871428 color 0.0:1.0:1.0:0.0\n\
@@ -1346,7 +1487,7 @@ mod tests {
13461487 (1280, 720),
13471488 old.playhead
13481489 )),
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\
13501491 eq 80.0:-3.0:0.707:ls\n\
13511492 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
13521493 );
@@ -1384,7 +1525,7 @@ mod tests {
13841525 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
13851526 assert_eq!(
13861527 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\
13881529 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
13891530 audio 1 0 0 30 0 - - - fit 2000\n",
13901531 "the rate is the clip line's last field, in thousandths"
@@ -1413,7 +1554,7 @@ mod tests {
14131554 (1280, 720),
14141555 old.playhead
14151556 )),
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\
14171558 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
14181559 );
14191560 // A rate outside what the editor can set is a corrupt line, by name.
@@ -1450,6 +1591,7 @@ mod tests {
14501591 &[0.0, 3.0, -6.5],
14511592 &[],
14521593 &[],
1594+ &[],
14531595 (1280, 720),
14541596 Some(23.976023976023978),
14551597 limiter,
@@ -1457,7 +1599,7 @@ mod tests {
14571599 );
14581600 assert_eq!(
14591601 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\
14611603 limiter -1.5 on\nsource 0 a.mp4\n\
14621604 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
14631605 audio 2 0 0 30 0 - - - fit 1000\n\
@@ -1489,7 +1631,7 @@ mod tests {
14891631 (1280, 720),
14901632 old.playhead
14911633 )),
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\
14931635 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
14941636 );
14951637
@@ -1653,7 +1795,7 @@ mod tests {
16531795 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
16541796 assert_eq!(
16551797 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\
16571799 source 2 /elsewhere/b.mp4\n\
16581800 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
16591801 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -1706,7 +1848,7 @@ mod tests {
17061848 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
17071849 assert_eq!(
17081850 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\
17101852 source 0 /elsewhere/b.mp4\n\
17111853 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
17121854 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1738,7 +1880,7 @@ mod tests {
17381880 // Saved again it is the current version, which round-trips to the
17391881 // same document.
17401882 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"));
17421884 let again = parse(&v5, &dir).expect("v5 parses");
17431885 assert_eq!(again.lanes, back.lanes);
17441886 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1834,6 +1976,7 @@ mod tests {
18341976 &[],
18351977 &[],
18361978 &[],
1979+ &[],
18371980 (1280, 720),
18381981 None,
18391982 Limiter::default(),
@@ -1843,7 +1986,7 @@ mod tests {
18431986 let bytes = std::fs::read(&path).expect("read back");
18441987 assert_eq!(
18451988 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\
18471990 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
18481991 );
18491992 // Loading rejoins the *given* directory, so the file is reached by the
@@ -1888,10 +2031,10 @@ mod tests {
18882031 #[test]
18892032 fn a_wrong_first_line_is_refused_by_name() {
18902033 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)
18922035 .unwrap_err()
18932036 .to_string();
1894- assert_eq!(err, "line 1: unsupported version 10");
2037+ assert_eq!(err, "line 1: unsupported version 11");
18952038 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
18962039 assert_eq!(
18972040 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/lib.rsmodified+1 -0
@@ -17,6 +17,7 @@ pub mod playback;
1717 pub mod project;
1818 pub mod scale;
1919 pub mod silence;
20+pub mod subtitle;
2021 pub mod waveform;
2122
2223 pub use audio::{
crates/engine/src/playback.rsmodified+118 -28
@@ -673,8 +673,19 @@ impl PlaybackSession {
673673 }
674674
675675 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();
676686 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);
678689 let span = project.composite_span_at(0);
679690 // Last, because it is the one thing here that cannot be taken back: the
680691 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -755,6 +766,47 @@ impl PlaybackSession {
755766 self.project.sources()
756767 }
757768
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+
758810 /// Writes the timeline to `path` as a `.edith`, atomically (see
759811 /// [`crate::edith`]). Sources no clip plays from are left out, and the
760812 /// playhead is saved with it so a reopened project resumes where it stood.
@@ -780,6 +832,9 @@ impl PlaybackSession {
780832 // project's, not this machine's (the monitoring volume is not
781833 // written and never will be).
782834 &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(),
783838 &eq,
784839 &color,
785840 (self.meta.width, self.meta.height),
@@ -1604,8 +1659,9 @@ impl PlaybackSession {
16041659 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
16051660 /// back, and nothing reseeks.
16061661 ///
1607- /// Refused unless it can join the timeline -- same codec, same audio
1608- /// parameters or both silent; the `Err` names the property that disagrees,
1662+ /// Refused unless it can join the timeline -- a decoder this machine can
1663+ /// open, and audio parameters that agree or none at all; the `Err` names
1664+ /// the property that disagrees,
16091665 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
16101666 /// its own is not a refusal: the clip is placed on the project canvas by its
16111667 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
@@ -1732,6 +1788,25 @@ impl PlaybackSession {
17321788 }
17331789 }
17341790
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+
17351810 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
17361811 /// one knob, because muting and turning it down are the same thing to the
17371812 /// device, and *which* the user meant is a question only the UI can answer
@@ -1944,8 +2019,9 @@ impl Drop for PlaybackSession {
19442019 }
19452020
19462021 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
1947-/// parameters are `timeline` and whose audio probes as `first`: same codec,
1948-/// same audio parameters or both silent, and a frame rate that can be named
2022+/// parameters are `timeline` and whose audio probes as `first`: a decoder this
2023+/// machine can open, audio parameters that agree (or no audio at all), and a
2024+/// frame rate that can be named
19492025 /// against the timeline's. The [`Rate`] it will be read at comes back with the
19502026 /// answer, so the number the check was decided on is the number it plays by.
19512027 ///
@@ -1954,7 +2030,9 @@ impl Drop for PlaybackSession {
19542030 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
19552031 /// letterboxed clip rather than a refusal, and so is a frame rate of its own:
19562032 /// 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.
19582036 ///
19592037 /// The `Err` names the property that disagrees, and those strings are what a
19602038 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1966,18 +2044,22 @@ fn matches_timeline(
19662044 timeline: &VideoMeta,
19672045 first: &Option<crate::AudioProbe>,
19682046 ) -> crate::Result<Rate> {
1969- // Codec first: one timeline is one kind of source. Mixing them would decode
1970- // (every clip opens its own decoder) but on a machine without the VA-API
1971- // plugin the VP9 half would be black frames with the refusal only on
1972- // stderr, which is exactly what a front-end cannot show.
1973- if meta.codec != timeline.codec {
1974- return Err(format!(
1975- "{} does not match the timeline's {}",
1976- meta.codec.name(),
1977- timeline.codec.name()
1978- )
1979- .into());
1980- }
2047+ // The codec is *not* held to the timeline's -- every clip opens its own
2048+ // decoder, so an H.264 take and an HEVC one play on one timeline. What the
2049+ // codec gate was really protecting against stays, in the one place that can
2050+ // actually answer it: on a machine without the VA-API plugin an HEVC or VP9
2051+ // clip would be black frames with the refusal on stderr alone, so the file
2052+ // is asked for a decoder *here*, at the door, where the `Err` is still
2053+ // something a front-end can show. A zero-length range probes and starts no
2054+ // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
2055+ // only enters VA-API off that path.
2056+ DecodeSession::open_worker(
2057+ &source.path,
2058+ 0,
2059+ 0,
2060+ ColorParams::default(),
2061+ Composer::passthrough(),
2062+ )?;
19812063 // The frame rate is *not* a refusal any more: a file shot at another rate is
19822064 // placed for the seconds it lasts and read through [`Rate`] at the
19832065 // decoder's door, so it plays at the speed it was shot at on a timeline
@@ -1995,8 +2077,9 @@ fn matches_timeline(
19952077 }
19962078
19972079 /// 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 one
1999-/// exported track is all there is, and no resampler.
2080+/// `first`: same rate, same layout -- or no audio of its own at all, which is
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.
20002083 ///
20012084 /// The audio half of [`matches_timeline`], which a stream placed on its own
20022085 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
@@ -2014,9 +2097,9 @@ fn matches_timeline(
20142097 /// `Ok(None)` for a timeline whose first such source is silent, and for one of
20152098 /// nothing but stills. That is a silent timeline, and a file with sound is
20162099 /// 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* as
2018-/// source 0 has always given. This function widens which source is asked, not
2019-/// what the answer means.
2100+/// has audio, the timeline is silent") -- the device was opened on source 0's
2101+/// track and there is none to open. This function widens which source is asked,
2102+/// not what the answer means.
20202103 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
20212104 match audio_source_of(sources) {
20222105 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
@@ -2045,12 +2128,19 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R
20452128 if probe == *first {
20462129 return Ok(());
20472130 }
2048- Err(match (probe, first) {
2049- (None, _) => "the file is silent, the timeline has audio".to_string(),
2050- (_, None) => "the file has audio, the timeline is silent".to_string(),
2051- (Some(a), Some(b)) => format!(
2131+ // ...and a *silent* file joins whatever the timeline is: it contributes
2132+ // silence over its span, which is the very thing both audio paths already
2133+ // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
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!(
20522142 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
2053- a.sample_rate, a.channels, b.sample_rate, b.channels
2143+ probe.sample_rate, probe.channels, b.sample_rate, b.channels
20542144 ),
20552145 }
20562146 .into())
crates/engine/src/project.rsmodified+38 -0
@@ -68,6 +68,7 @@ use crate::color::ColorParams;
6868 use crate::eq::EqParams;
6969 use crate::limiter::{Limiter, db_to_linear};
7070 use crate::scale::FitPolicy;
71+use crate::subtitle::SubtitleTrack;
7172
7273 /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
7374 /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
@@ -618,6 +619,12 @@ pub struct Project {
618619 /// Never rolled back by an undo: an id retired by an undone split must not
619620 /// come back and group two clips that were never together.
620621 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>,
621628 /// The master limiter every lane's sound is summed *through*
622629 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
623630 /// is what the history snapshots hold: it is a setting on the mix, like the
@@ -652,6 +659,7 @@ impl Project {
652659 color: Vec::new(),
653660 history: Vec::new(),
654661 next_link: 1,
662+ subtitles: Vec::new(),
655663 limiter: Limiter::default(),
656664 }
657665 }
@@ -760,6 +768,7 @@ impl Project {
760768 color,
761769 history: Vec::new(),
762770 next_link,
771+ subtitles: Vec::new(),
763772 limiter: Limiter::default(),
764773 })
765774 }
@@ -1128,6 +1137,35 @@ impl Project {
11281137 self
11291138 }
11301139
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+
11311169 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
11321170 /// lanes is multiplied by on its way into the mix: the same lanes in the
11331171 /// 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;
1515 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
1616 /// straddles zero, so silence draws as a flat line.
1717 ///
18-/// Decoding the whole file runs at ~1700x realtime, but it is still linear in
19-/// source length: callers cache the result per source *and stream* — two
20-/// streams of one file are two different envelopes, and a cache keyed on the
21-/// path alone would draw the first one under both.
18+/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
19+/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but
20+/// it is linear in source length either way: callers cache the result per source
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.
2230 pub fn peaks(
2331 path: impl AsRef<Path>,
2432 stream: usize,
@@ -141,6 +149,33 @@ mod tests {
141149 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
142150 }
143151
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+
144179 #[test]
145180 fn video_only_source_has_no_peaks() {
146181 assert!(
crates/engine/tests/audio_decode.rsmodified+134 -0
@@ -160,6 +160,103 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
160160 }
161161 }
162162
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+
163260 /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the
164261 /// *copy* path names it and hands the export on to the re-encode (which decodes
165262 /// 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() {
175272 "unhelpful refusal: {err}"
176273 );
177274 }
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() {
511511 assert!(!part_path(&out).exists(), "no half-written .part either");
512512 }
513513
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+
514575 /// A silent timeline cannot become an audio file, and says so rather than
515576 /// writing zero samples that a user would take for a broken microphone.
516577 #[test]
crates/engine/tests/audio_multi.rsmodified+67 -7
@@ -250,18 +250,19 @@ fn the_join_carries_no_second_priming_packet() {
250250 }
251251
252252 #[test]
253-fn a_source_without_the_timeline_audio_is_refused() {
254- // Import refuses these up front (same rate, same layout, or both silent);
253+fn a_source_that_disagrees_on_rate_or_layout_is_refused() {
254+ // Import refuses these up front (one output device, one set of parameters);
255255 // the copy and the decode paths refuse them again rather than mislabel one
256- // esds for two different tracks.
257- let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];
256+ // esds for two different tracks. Stream 1 of the multi-audio fixture is
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)];
258259 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
259260 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)
260261 for e in [
261- AudioSession::copy_multi_segments(&mixed, &segs).err(),
262- AudioSession::open_multi_segments(&mixed, &segs).err(),
262+ AudioSession::copy_multi_streams(&mixed, &segs).err(),
263+ AudioSession::open_multi_streams(&mixed, &segs).err(),
263264 ]
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"))
265266 {
266267 let msg = e.to_string();
267268 assert!(msg.contains("source 1"), "{msg}");
@@ -270,3 +271,62 @@ fn a_source_without_the_timeline_audio_is_refused() {
270271 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
271272 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
272273 }
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() {
5757 assert_eq!(vp9.codec, Codec::Vp9);
5858 }
5959
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+
6077 /// The delivered audio scope, as an assert: a Matroska file's AAC track is read
6178 /// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its
6279 /// *picture* being AV1 changes nothing about it.
@@ -138,17 +155,27 @@ fn the_software_path_refuses_av1_by_name() {
138155 assert!(refused.contains("plugin"), "{refused}");
139156 }
140157
141-/// A timeline is refused a source coded differently, in the same words a
142-/// resolution mismatch is refused in: a front-end shows the string as it is.
158+/// A timeline is *not* refused a source coded differently -- every clip opens
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.
143162 #[test]
144-fn a_timeline_refuses_the_other_codec() {
163+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
145164 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") };
146168 let refused = session
147169 .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")
149171 .to_string();
150- assert!(refused.contains("AV1"), "{refused}");
151- assert!(refused.contains("H.264"), "{refused}");
172+ unsafe { std::env::remove_var("VE_SW") };
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");
152179 }
153180
154181 /// 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() {
181208 );
182209 }
183210
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+
184242 /// A seek into the second GOP hands back that very frame, not the keyframe it
185243 /// had to restart from: the demuxer's sync index and the plugin's skip count
186244 /// 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() {
112112 assert!(h264, "software H.264 decode still opens");
113113 }
114114
115-/// A timeline is refused a source coded differently, in the same words a
116-/// resolution mismatch is refused in: a front-end shows the string as it is.
115+/// A timeline is *not* refused a source coded differently -- every clip opens
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.
117120 #[test]
118-fn a_timeline_refuses_the_other_codec() {
121+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
119122 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") };
120127 let refused = session
121128 .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")
123130 .to_string();
124- assert!(refused.contains("HEVC"), "{refused}");
125- assert!(refused.contains("H.264"), "{refused}");
131+ unsafe { std::env::remove_var("VE_SW") };
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+ }
126144 }
127145
128146 /// 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() {
155173 );
156174 }
157175
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+
158235 /// Export re-encodes to H.264 whatever the source was coded with: the packet
159236 /// copy path is audio-only, so no HEVC byte can reach an `avc1` track.
160237 #[test]
crates/engine/tests/lanes.rsmodified+9 -4
@@ -52,8 +52,13 @@ fn out_path(name: &str, ext: &str) -> PathBuf {
5252 /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle
5353 /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`.
5454 /// Exactly the file a user would write by hand, parsed by the real loader.
55-fn three_lane_file() -> PathBuf {
56- let path = out_path("project", "edith");
55+///
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");
5762 // `source <audio stream> <path>`: the number is which audio track of the
5863 // file plays, not the source index -- both of these are on their first.
5964 let text = format!(
@@ -143,7 +148,7 @@ fn frame_of(session: &mut PlaybackSession, timeline: u32) -> Vec<u8> {
143148 #[test]
144149 fn playback_shows_the_topmost_video_lane() {
145150 pin_software();
146- let project = three_lane_file();
151+ let project = three_lane_file("playback");
147152 let mut session = PlaybackSession::open_project(&project).expect("open the project");
148153 session.set_gain(0.0);
149154 assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS);
@@ -164,7 +169,7 @@ fn playback_shows_the_topmost_video_lane() {
164169 #[test]
165170 fn export_writes_the_same_composite() {
166171 pin_software();
167- let file = three_lane_file();
172+ let file = three_lane_file("export");
168173 let session = PlaybackSession::open_project(&file).expect("open the project");
169174 let out = out_path("composite", "mp4");
170175
crates/engine/tests/playback.rsmodified+60 -25
@@ -13,7 +13,7 @@ use std::time::{Duration, Instant};
1313
1414 use engine::export::{ExportSettings, Format};
1515 use engine::project::Lane;
16-use engine::{DecodeSession, Frame, PlaybackSession};
16+use engine::{Codec, DecodeSession, Frame, PlaybackSession};
1717
1818 fn asset(name: &str) -> PathBuf {
1919 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -788,30 +788,31 @@ fn the_first_import_opens_a_library_over_an_empty_timeline() {
788788 assert_eq!(session.sources().len(), 1, "the row survives the undo");
789789 }
790790
791-/// One timeline, one set of parameters: everything else is refused by name and
792-/// changes nothing.
791+/// One timeline, one frame rate and one set of audio parameters: what is left
792+/// is refused by name and changes nothing.
793793 #[test]
794794 fn import_refuses_what_does_not_match() {
795795 let mut session = open(asset("test_av.mp4"));
796796
797- // A different *codec* cannot join: one timeline is one kind of source.
798- let err = session
799- .import(&asset("test_vp9.mp4"))
800- .expect_err("VP9 must be refused")
801- .to_string();
802- assert!(err.contains("VP9"), "refusal must name the codec: {err}");
797+ // A different *codec* is not among them any more -- every clip opens its
798+ // own decoder. The only refusal left on that axis is a decoder this machine
799+ // cannot open, and it is the plugin's own words, not the timeline's.
800+ match session.import(&asset("test_vp9.mp4")) {
801+ Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"),
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();
803809
804810 // 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.
806- let err = session
811+ // the project canvas instead -- and neither is a file with no sound: it
812+ // contributes silence over its span.
813+ session
807814 .import(&asset("test_mismatch.mp4"))
808- .expect_err("a silent file must be refused")
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+ .expect("a silent 640x360 file joins a timeline with sound");
815816
816817 // A frame rate of its own is no longer a refusal either: 25 fps joins a
817818 // 30 fps timeline and is read at `Rate` against it -- see
@@ -823,22 +824,32 @@ fn import_refuses_what_does_not_match() {
823824 .remove_source(&asset("test_25fps.mp4"), 0)
824825 .expect("...and the row it made comes back off");
825826
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.
827829 let err = session
828- .import(&asset("test_baseline.mp4"))
829- .expect_err("a silent file must be refused")
830+ .import(&asset("test_ac3.mp4"))
831+ .expect_err("a mono track cannot join a stereo timeline")
830832 .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+ );
832837
833838 assert!(
834839 session.import(&asset("no_such_file.mp4")).is_err(),
835840 "a missing file is an error, not a panic"
836841 );
837- assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");
838- assert_eq!(session.sources().len(), 1, "a refusal left a library row");
842+ assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
843+ assert_eq!(
844+ session.sources().len(),
845+ rows + 1,
846+ "only the silent file was taken in"
847+ );
839848 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
840849
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.
842853 let mut silent = open(asset("test_baseline.mp4"));
843854 let err = silent
844855 .import(&asset("test_av.mp4"))
@@ -847,6 +858,30 @@ fn import_refuses_what_does_not_match() {
847858 assert!(err.contains("audio"), "refusal must name the audio: {err}");
848859 }
849860
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+
850885 /// The user-facing point of a project resolution: media of two sizes on one
851886 /// timeline, each composed onto the project's own canvas.
852887 ///
crates/engine/tests/saveload.rsmodified+14 -11
@@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
209209 let v2 = dir.join("new.edith");
210210 loaded.save_project(&v2).expect("save");
211211 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}");
213213 assert!(
214214 text.contains("\nresolution 1280 720\n"),
215215 "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() {
297297 loaded.save_project(&again).expect("save");
298298 assert_eq!(
299299 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\
301301 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
302302 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
303303 "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() {
327327 loaded.save_project(&again).expect("save");
328328 assert_eq!(
329329 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\
331331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
332332 eq 12000.0:6.25:0.5:hs\n\
333333 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() {
362362 loaded.save_project(&again).expect("save");
363363 assert_eq!(
364364 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\
366366 eq 80.0:-3.0:0.707:ls\n\
367367 color 0.1:1.2:0.9:-0.3\n\
368368 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() {
412412 loaded.save_project(&again).expect("save");
413413 assert_eq!(
414414 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\
416416 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
417417 audio 1 0 0 60 0 - - - fit 1000\n",
418418 "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() {
670670
671671 for (text, want) in [
672672 (
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",
674674 "line 1",
675675 ),
676676 // 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() {
733733 fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
734734 let dir = scratch("mismatch");
735735 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");
737737 let path = dir.join("swapped.edith");
738738 std::fs::write(
739739 &path,
@@ -745,12 +745,15 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
745745 .expect("a source that stopped matching must not open")
746746 .to_string();
747747 // The suffix is `import`'s own refusal, word for word. The substitute is
748- // 640x360 *and* silent; only the second of those is a refusal now -- a
749- // resolution of its own is placed on the project canvas.
748+ // mono, which is the shape of what is left: one output device means one
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.
750753 assert_eq!(
751754 err,
752755 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",
754757 dir.join("test_av2.mp4").display()
755758 )
756759 );
@@ -806,7 +809,7 @@ fn a_song_only_project_comes_back_at_the_rate_it_names() {
806809 let path = dir.join("song.edith");
807810 std::fs::write(
808811 &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\
810813 video 1\naudio 1 0 0 24 0 - - - fit 1000\n",
811814 )
812815 .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() {
365365 &sources,
366366 &lanes,
367367 &p.lane_gains(),
368+ p.subtitles(),
368369 &eq,
369370 &color,
370371 (1920, 1080),
@@ -375,7 +376,7 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
375376 .expect("save");
376377 let text = std::fs::read_to_string(&file).expect("read it back");
377378 assert!(
378- text.starts_with("edith 9"),
379+ text.starts_with("edith 10"),
379380 "{:?}",
380381 &text[..16.min(text.len())]
381382 );
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() {
7676 assert!(h264, "software H.264 decode still opens");
7777 }
7878
79-/// A VP9 timeline is refused a source coded differently, in the same words a
80-/// resolution mismatch is refused in: a front-end shows the string as it is.
79+/// A timeline is *not* refused a source coded differently -- every clip opens
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.
8183 #[test]
82-fn a_timeline_refuses_the_other_codec() {
84+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
8385 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") };
8489 let refused = session
8590 .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")
8792 .to_string();
88- assert!(refused.contains("VP9"), "{refused}");
89- assert!(refused.contains("H.264"), "{refused}");
93+ unsafe { std::env::remove_var("VE_SW") };
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+ }
90106 }
91107
92108 /// 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 \
103103 # at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as
104104 # the others so the tests measure the codec and nothing else -- but `-g 30` is
105105 # not a preference: it puts a second keyframe at frame 30, which is what the
106-# sync index and the seek test are checked against. 8-bit Main profile, because
107-# the plugin's NV12 read-back cannot carry 10-bit. Its AAC track is deliberate
108-# too: Matroska audio is not wired to the decoder yet, and the notice that says
109-# so needs a track to name.
106+# sync index and the seek test are checked against. 8-bit Main profile here; the
107+# 10-bit twin is below. Its AAC track is deliberate too: it is the AAC a Matroska
108+# file's sound is read out of through symphonia, beside the AC-3 fixtures further
109+# down that no symphonia version decodes.
110110 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
111111 -f lavfi -i "sine=frequency=440:duration=2" \
112112 -f lavfi -i "sine=frequency=880:duration=2" \
113113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115115 -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
116154 # HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as
117155 # test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for
118156 # 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 \
139177 -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \
140178 -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \
141179 -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
142198 # Sync fixture: one flash and one beep, at the same instant. Black picture with
143199 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
144200 # stretch — so a test can find each of them and say how far apart they came out.
vendor/rusty_aac/src/dsp.rsmodified+87 -49
@@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
3535 if n == 0 {
3636 return Vec::new();
3737 }
38- // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below --
39- // the same numbers, looked up instead of called for.
40- if let Some(matrix) = imdct_matrix(n) {
41- let mut out = vec![0f32; n];
42- for (i, o) in out.iter_mut().enumerate() {
43- let row = &matrix[i * half..(i + 1) * half];
44- let mut acc = 0f32;
45- for (k, &s) in spec.iter().enumerate() {
46- acc += s * row[k];
38+ // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 +
39+ // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i +
40+ // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT --
41+ // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is
42+ // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L).
43+ if half >= 2 && half.is_power_of_two() {
44+ let owned;
45+ let tw = match mdct_twiddles(n) {
46+ Some(t) => t,
47+ None => {
48+ owned = MdctTwiddles::build(n);
49+ &owned
4750 }
48- *o = acc;
49- }
50- return out;
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();
5168 }
69+ imdct_direct(spec)
70+}
71+
72+/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its
73+/// test measures against and as the path for sizes the fast one does not take.
74+fn imdct_direct(spec: &[f32]) -> Vec<f32> {
75+ let half = spec.len();
76+ let n = half * 2;
5277 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2
5378 let scale = 2.0 / n as f64;
5479 let w = 2.0 * PI / n as f64;
@@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
6489 out
6590 }
6691
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-
9792 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate
9893 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).
9994 /// `N` time samples → `N/2` coefficients.
@@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
236231 if n < 4 {
237232 return mdct(x); // tiny sizes: fall back to the direct oracle
238233 }
239- let (l, m) = (n / 2, n / 4);
234+ let l = n / 2;
240235 let owned;
241236 let tw = match mdct_twiddles(n) {
242237 Some(t) => t,
@@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
254249 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)
255250 }
256251 };
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;
258266 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);
259267 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));
261269 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];
262270 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];
263271 }
264272 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.
266- let mut out = vec![0f32; l];
273+ let mut out = vec![0f64; l];
267274 for p in 0..m {
268275 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;
270- out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32;
276+ out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p];
277+ out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p];
271278 }
272279 out
273280 }
@@ -346,6 +353,37 @@ mod tests {
346353 }
347354 }
348355
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+
349387 #[test]
350388 fn dequant_matches_spec_curve() {
351389 assert_eq!(dequant(0), 0.0);