forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(A5): main (b10235a) into the import-policy branch

Browse files at this commit

685d4e69e69238687528d71a9757c09272a0a78bAhmet Kaan GümüşParent: cbb0f6275d536b
Clean: A1's Track::open rework routes codecs (MkvAc3Track before symphonia)
and A5 handles absent tracks -- the two compose, and git merged them
without touching either. C1's main.rs churn moved the refusal test's
neighbourhood, not the test.
crates/app/src/main.rsmodified+1211 -519

Diff too large; view file

@@ -406,6 +406,47 @@ const MENU_ITEMS: [ActionId; 14] = [
406406 ActionId::ToggleMute,
407407 ];
408408
409+/// One row of the actions card, in the order it lists them: a heading, then
410+/// every action the registry files under it, then the strokes the modal cards
411+/// answer themselves.
412+///
413+/// A list rather than a loop inside the render, so the card and
414+/// `every_action_is_on_the_actions_card` read the *same* order: an action that
415+/// reaches no row fails a test instead of quietly becoming pointer-unreachable.
416+enum KeyRow {
417+ Head(keymap::Category),
418+ /// Click its label to do it, click its stroke to change that stroke.
419+ Act(ActionId),
420+ /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may
421+ /// unbind the way out of a card.
422+ Fixed(usize),
423+}
424+
425+/// Every action, under its heading, and the card-local strokes beside them.
426+/// Generated from the registry -- [`ActionId::ALL`] in its own order, under
427+/// [`keymap::Category::ALL`] -- so an action added there is on the card the
428+/// moment it exists and there is no second list here to forget.
429+fn keys_rows() -> Vec<KeyRow> {
430+ let mut rows = Vec::new();
431+ for category in keymap::Category::ALL {
432+ rows.push(KeyRow::Head(category));
433+ rows.extend(
434+ ActionId::ALL
435+ .into_iter()
436+ .filter(|a| a.category() == category)
437+ .map(KeyRow::Act),
438+ );
439+ rows.extend(
440+ keymap::FIXED
441+ .iter()
442+ .enumerate()
443+ .filter(|(_, f)| f.category == category)
444+ .map(|(i, _)| KeyRow::Fixed(i)),
445+ );
446+ }
447+ rows
448+}
449+
409450 /// The project resolutions [`Player::cycle_resolution`] offers, largest first.
410451 /// A short list of the sizes people name; the media's own is cycled in beside
411452 /// them, which is what makes the trip round come back to where it started.
@@ -618,6 +659,48 @@ const HIST_H: f32 = 96.;
618659 /// counts, lightened enough to read on the dark box.
619660 const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
620661
662+/// Where the transport is. The one answer the button's glyph, its label, its
663+/// enablement, the play key and the repaint loop all read -- there is no play
664+/// flag anywhere else, because a second one is a second answer.
665+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
666+enum Transport {
667+ /// No timeline open. Nothing to play and the transport is dimmed.
668+ Stopped,
669+ Playing,
670+ Paused,
671+ /// Played out: the last frame is on screen, the decoder is finished, and the
672+ /// clock is still running past it -- which is exactly why "is the clock
673+ /// going" is not the same question as "is this playing".
674+ Ended,
675+}
676+
677+impl Transport {
678+ /// The timeline is in motion: two bars on the button, and a repaint owed
679+ /// every vsync.
680+ fn is_playing(self) -> bool {
681+ matches!(self, Transport::Playing)
682+ }
683+
684+ /// The play key and the transport button start over from the top rather
685+ /// than toggling -- the end of a timeline is where every NLE does this, and
686+ /// the button does it because the key already did.
687+ fn restarts(self) -> bool {
688+ matches!(self, Transport::Ended)
689+ }
690+}
691+
692+/// What a session's own two answers mean: the clock, unless the timeline has
693+/// been played out -- `played_out` is the engine's end of stream with no frame
694+/// still waiting on the pump, and it wins, because past the end a running clock
695+/// is measuring wall time and not a picture.
696+fn transport(playing: bool, played_out: bool) -> Transport {
697+ match (played_out, playing) {
698+ (true, _) => Transport::Ended,
699+ (_, true) => Transport::Playing,
700+ (_, false) => Transport::Paused,
701+ }
702+}
703+
621704 struct Player {
622705 /// The timeline, once there is one. A run with no file opens without it and
623706 /// waits: the first media import or project load is what fills it, and
@@ -629,21 +712,20 @@ struct Player {
629712 name: SharedString,
630713 image: Option<Arc<RenderImage>>,
631714 /// A frame that arrived before its time; shown on the tick it comes due.
715+ /// The pump's buffer, not transport state -- but a frame waiting here is
716+ /// what keeps a finished decoder from reading as [`Transport::Ended`] one
717+ /// tick early. See [`Player::transport`].
632718 held: Option<Frame>,
633- /// The decoder's channel closed. Frames may still be waiting in `held`.
634- eos: bool,
635- /// Last frame shown; nothing left to animate.
636- done: bool,
637719 /// A seek is waiting for its frame. Keeps the repaint loop alive while
638720 /// paused, which is the only way the new still ever reaches the screen.
639721 pending_seek: bool,
640722 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
641723 /// the window position and nothing else.
642724 ruler: Rc<Cell<Bounds<Pixels>>>,
643- /// How much of the timeline the ruler and the lanes are showing. Held here
725+ /// How wide a second of timeline is drawn, and from which moment. Held here
644726 /// and nowhere else: every frame-to-pixel answer in the panel comes out of
645727 /// it, so the boxes, the playhead and the pointer cannot disagree.
646- view: View,
728+ scale: Scale,
647729 /// Which clip the edit keys act on: the lane it is in and its index there.
648730 /// The *clicked* half, not the group -- a group is what gets marked on
649731 /// screen, but Lift has to know which half it was aimed at. Indices move
@@ -889,6 +971,9 @@ impl Player {
889971 /// the channel and only the last of them is shown, which *is* the
890972 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
891973 fn pump(&mut self, window: &mut Window) {
974+ // Where the transport was before this drain, so the crossing into
975+ // `Ended` can be recognised as the one transition it is.
976+ let was = self.transport();
892977 // No timeline, nothing to catch up to: the window is showing its empty
893978 // state and there is no decoder to drain.
894979 let Some(session) = &mut self.session else {
@@ -904,10 +989,7 @@ impl Player {
904989 // them apart -- `frame.index` is already a timeline index.
905990 None => match session.try_frame() {
906991 Some(frame) => frame,
907- None => {
908- self.eos = session.is_eos();
909- break;
910- }
992+ None => break,
911993 },
912994 };
913995 if f64::from(frame.index) <= target {
@@ -942,29 +1024,56 @@ impl Player {
9421024 }
9431025 }
9441026
945- if self.eos && self.held.is_none() && !self.done {
946- self.done = true;
1027+ if self.transport() == Transport::Ended {
9471028 // A seek whose worker never produced a frame (vanished file) would
948- // otherwise repaint at vsync forever.
1029+ // otherwise repaint at vsync forever. Held true for as long as the
1030+ // state does, not just on the crossing: nothing else is coming.
9491031 self.pending_seek = false;
950- let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
951- eprintln!(
952- "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
953- self.displayed,
954- self.dropped,
955- session.now()
956- );
1032+ if was != Transport::Ended {
1033+ // Ended is a *stopped* transport, so the clock stops with it,
1034+ // on the out point the timecode and the playhead have been
1035+ // showing all along. Nothing else ever stopped it: past the
1036+ // last frame wall time takes over and `now()` walks off the end
1037+ // of the timeline for as long as the window is left open -- and
1038+ // the playhead is what a cut, a paste, an insert and the
1039+ // analyser all act at, so every one of them was aiming into
1040+ // empty space (measured: a 5 s timeline recognised its end at
1041+ // clock 17.5 s under a slow renderer). End of stream is left
1042+ // set, so this is still `Ended` and the next press restarts.
1043+ if let Some(session) = &mut self.session {
1044+ session.halt_at_end();
1045+ }
1046+ let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
1047+ eprintln!(
1048+ "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
1049+ self.displayed,
1050+ self.dropped,
1051+ self.session.as_ref().map_or(0., PlaybackSession::now)
1052+ );
1053+ }
9571054 }
9581055 }
9591056
960- /// Every end-of-stream flag is app state and the engine knows nothing about
961- /// it, so clearing them after a reseek is what stops the picture from
962- /// staying frozen on the old last frame. Edits reseek inside the engine and
963- /// still owe this.
1057+ /// Where the transport is, asked of the session rather than remembered:
1058+ /// end of stream is the engine's own flag (any seek clears it, which is why
1059+ /// an edit past the end revives the picture) and so is the clock. A held
1060+ /// frame is one still owed to the screen, so the end is not the end yet.
1061+ fn transport(&self) -> Transport {
1062+ let Some(session) = &self.session else {
1063+ return Transport::Stopped;
1064+ };
1065+ transport(
1066+ session.is_playing(),
1067+ session.is_eos() && self.held.is_none(),
1068+ )
1069+ }
1070+
1071+ /// A frame owed to the screen after a reseek, and the buffered one dropped:
1072+ /// what stops the picture from staying frozen on the old last frame. The
1073+ /// end-of-stream flag itself is the engine's and its own seek clears it --
1074+ /// edits reseek inside the engine and still owe this.
9641075 fn reset_after_reseek(&mut self) {
9651076 self.held = None;
966- self.eos = false;
967- self.done = false;
9681077 self.pending_seek = true;
9691078 // An edit moves the indices a drag in flight is holding -- a stroke
9701079 // during one is exactly that -- and an edge committed against a moved
@@ -1030,6 +1139,31 @@ impl Player {
10301139 }
10311140 }
10321141
1142+ /// Whether the editor can be asked for `action` right now, and why not when
1143+ /// it cannot. `on` is the clip the question is about -- the one a clip menu
1144+ /// was opened on -- and `None` asks about the marked clip instead, which is
1145+ /// what a menu that hangs over no clip in particular means by "this one".
1146+ ///
1147+ /// The player's half of [`enable`]: it reads the state, the table decides.
1148+ fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable {
1149+ let Some(session) = &self.session else {
1150+ return enable(action, Ctx::default());
1151+ };
1152+ let clip = on
1153+ .or(self.selected)
1154+ .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane)));
1155+ enable(
1156+ action,
1157+ Ctx {
1158+ clip,
1159+ playhead: frame_at(session.now(), self.fps),
1160+ timeline: true,
1161+ clipboard: self.clipboard.is_some(),
1162+ exporting: self.exporting().is_some(),
1163+ },
1164+ )
1165+ }
1166+
10331167 /// The one place a clip becomes *the* selected one: a click, a right-click
10341168 /// that opens the menu, and every selection key go through here, so what a
10351169 /// keyboard marks and what a pointer marks are the same state marked the
@@ -1133,23 +1267,37 @@ impl Player {
11331267 cx.notify();
11341268 }
11351269
1136- /// Magnifies the timeline about a point that stays put: `anchor` is where
1137- /// along the bed to hold still (a ctrl+wheel holds the pointer), and with
1138- /// none it is the playhead -- so the frame being worked on is still the
1270+ /// The scale against the bed it is drawn on and the timeline it is drawn
1271+ /// from: every clamp, zoom and scroll is worked out through this, and the
1272+ /// bed is measured off the ruler's probe rather than remembered, so a
1273+ /// resized window is a resized view on the very next answer.
1274+ fn view(&self) -> View {
1275+ View {
1276+ scale: self.scale,
1277+ bed: f32::from(self.ruler.get().size.width),
1278+ duration: self.drawn_duration(),
1279+ fps: self.fps,
1280+ }
1281+ }
1282+
1283+ /// Magnifies the timeline about a point that stays put: `anchor` is how many
1284+ /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and
1285+ /// with none it is the playhead -- so the frame being worked on is still the
11391286 /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
1140- /// stops at the whole timeline, in at a handful of frames.
1287+ /// stops at [`ZOOM_MAX_SECONDS`] on the bed, in at a handful of frames.
11411288 fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
1142- let duration = self.drawn_duration();
1143- let at = self.playhead(duration);
1144- let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.));
1145- self.view = self.view.zoomed(factor, anchor, duration, self.fps);
1289+ let view = self.view();
1290+ let at = self.playhead(view.duration);
1291+ let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
1292+ self.scale = view.zoomed(factor, anchor);
11461293 cx.notify();
11471294 }
11481295
1149- /// All the way back out: the whole timeline across the bed, which is what
1150- /// the panel shows before anyone has zoomed at all.
1296+ /// All the way back out: the whole timeline across the bed, and the one
1297+ /// thing that reads the timeline's own length to decide how wide a second
1298+ /// is drawn.
11511299 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
1152- self.view = View::default();
1300+ self.scale = self.view().fit();
11531301 cx.notify();
11541302 }
11551303
@@ -1933,16 +2081,17 @@ impl Player {
19332081 /// door a ruler click uses -- so a step while playing keeps playing, exactly
19342082 /// as a click does. It starts from the frame the transport is showing, which
19352083 /// past the end is the last one, and that is what lets a step back off EOS
1936- /// revive the picture ([`Player::reset_after_reseek`] clears `done`). Both
2084+ /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
19372085 /// ends clamp, so the two go-to actions are this same step asked for more
19382086 /// frames than the timeline has. Selection is untouched: a seek is not an
19392087 /// edit, and nothing it does moves a clip index.
19402088 fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
2089+ let ended = self.transport() == Transport::Ended;
19412090 let Some(session) = &self.session else {
19422091 return;
19432092 };
19442093 let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
1945- let now = match self.done {
2094+ let now = match ended {
19462095 true => last,
19472096 false => i64::from(frame_at(session.now(), self.fps)),
19482097 };
@@ -2352,14 +2501,12 @@ impl Player {
23522501 /// there is no such clip to move. The engine has the last word on where it
23532502 /// may actually go -- this is the ask, not the answer.
23542503 ///
2355- /// ponytail: the bed ends where the timeline does, so a clip cannot be
2356- /// dragged *past* the last frame -- the pointer has no pixel out there to
2357- /// name and [`View::time_at`] clamps to the duration. Room to the right is
2358- /// made by pulling a tail out first ([`Player::drawn_duration`] already
2359- /// lengthens the bed for exactly that gesture). The upgrade is to draw the
2360- /// bed past the end while a clip drag is in flight, the way a trim already
2361- /// does: `drawn_duration` would take the dragged clip's length the same way
2362- /// it takes a trim's reach.
2504+ /// ponytail: the bed now runs past the last frame whenever the timeline is
2505+ /// shorter than the view ([`Scale::time_at`] clamps at the head only), so a
2506+ /// clip *can* be dragged out there. Zoomed in against the far end it cannot:
2507+ /// the scroll clamp pins the bed's right edge to the duration, and the
2508+ /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2509+ /// leave a screen of empty bed after the end, the way every NLE does.
23632510 fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> {
23642511 let session = self.session.as_ref()?;
23652512 let clip = session.lane_clips(from).get(idx).copied()?;
@@ -2382,16 +2529,11 @@ impl Player {
23822529 Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))
23832530 }
23842531
2385- /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is
2386- /// a distance on screen, so zoomed right in it is worth less than a frame
2387- /// (no snap at all, which is what a hand placing single frames wants) and
2388- /// zoomed out to the whole timeline it is worth many.
2532+ /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
2533+ /// own width drops out of it, since a pixel is now worth the same stretch of
2534+ /// timeline wherever the view sits.
23892535 fn snap_frames(&self) -> u32 {
2390- let bed = f64::from(f32::from(self.ruler.get().size.width));
2391- if bed <= 0. {
2392- return 0;
2393- }
2394- (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u32
2536+ self.scale.snap_frames(self.fps)
23952537 }
23962538
23972539 /// Opens the clip menu on the box under the pointer, from the right button
@@ -2460,14 +2602,13 @@ impl Player {
24602602 }
24612603
24622604 /// The timeline frame a pointer at window x is on: along the same bed the
2463- /// ruler is measured on, through the same [`View`] every box is drawn
2605+ /// ruler is measured on, through the same [`Scale`] every box is drawn
24642606 /// through, so a zoomed-in panel answers with the frame under the pointer
24652607 /// and not with the one that would have been there unzoomed. The one
24662608 /// question a trim, a grab and a drop all ask.
24672609 fn frame_under(&self, x: Pixels) -> u32 {
2468- let duration = self.drawn_duration();
24692610 frame_at(
2470- self.view.time_at(frac_along(x, self.ruler.get()), duration),
2611+ self.scale.time_at(px_along(x, self.ruler.get())),
24712612 self.fps,
24722613 )
24732614 }
@@ -2554,12 +2695,11 @@ impl Player {
25542695 }
25552696 }
25562697
2557- /// Where the playhead is, as the panel draws it. The clock keeps running
2558- /// after the last frame (wall time takes over at audio EOF) while the
2559- /// picture is frozen, so what the UI shows is the clamped one, pinned to
2560- /// the out-point once playback is done.
2698+ /// Where the playhead is, as the panel draws it: pinned to the out point
2699+ /// once playback is done, and clamped to the drawn duration otherwise -- a
2700+ /// tail being dragged draws past the timeline it is about to become.
25612701 fn playhead(&self, duration: f64) -> f64 {
2562- if self.done {
2702+ if self.transport() == Transport::Ended {
25632703 duration
25642704 } else {
25652705 self.session
@@ -2754,11 +2894,11 @@ impl Player {
27542894 self.export_path = PathBuf::new();
27552895 self.project_path = PathBuf::new();
27562896 self.fps = 30.;
2757- // No decoder to wait for a frame from: the hint is what shows.
2897+ // No decoder to wait for a frame from: the hint is what shows. The
2898+ // transport reads `Stopped` from the session being gone, so there is no
2899+ // end-of-stream state left to clear here.
27582900 self.reset_after_reseek();
27592901 self.pending_seek = false;
2760- self.eos = false;
2761- self.done = false;
27622902 }
27632903
27642904 /// One item of a library row's menu, done. Every one of them closes the
@@ -3127,9 +3267,12 @@ impl Player {
31273267 let Some(session) = &self.session else {
31283268 return;
31293269 };
3270+ // Clamped to the timeline here rather than in the mapping: there is bed
3271+ // past the last frame now, and a seek out there is a seek to the end.
31303272 let t = self
3131- .view
3132- .time_at(frac_along(x, self.ruler.get()), session.timeline_duration());
3273+ .scale
3274+ .time_at(px_along(x, self.ruler.get()))
3275+ .clamp(0., session.timeline_duration());
31333276 let target = (t * self.fps) as u32;
31343277 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
31353278 self.last_target = target;
@@ -3174,11 +3317,11 @@ impl Player {
31743317 return;
31753318 }
31763319 // Nothing to play is a message, not a transport state. An empty
3177- // timeline is `done` from its one black frame onward, so the restart
3178- // below would start a clock against a zero-length timeline -- and it is
3179- // `done` again by the next repaint, so no later press could ever stop
3180- // it: the button would read "Pause" and never pause. A delete can empty
3181- // the timeline mid-play, and that press must still stop it.
3320+ // timeline is [`Transport::Ended`] from its one black frame onward, so
3321+ // the restart below would start a clock against a zero-length timeline
3322+ // -- and it is Ended again by the next repaint, so no later press could
3323+ // ever stop it: the button would read "Pause" and never pause. A delete
3324+ // can empty the timeline mid-play, and that press must still stop it.
31823325 if nothing_to_play(self.session.as_ref()) {
31833326 match self.session.as_mut().filter(|s| s.is_playing()) {
31843327 Some(session) => session.pause(),
@@ -3187,15 +3330,25 @@ impl Player {
31873330 cx.notify();
31883331 return;
31893332 }
3190- if self.done {
3191- self.seek(0., cx);
3192- if let Some(session) = &mut self.session {
3193- session.play();
3333+ match self.transport() {
3334+ // Nothing open: the button is dimmed and the key says nothing.
3335+ Transport::Stopped => {}
3336+ // Back to the top and away, for the key and the button alike --
3337+ // whichever asked, the transport was showing Play.
3338+ state if state.restarts() => {
3339+ self.seek(0., cx);
3340+ if let Some(session) = &mut self.session {
3341+ session.play();
3342+ }
3343+ }
3344+ _ => {
3345+ if let Some(session) = &mut self.session {
3346+ session.toggle();
3347+ // A paused timeline animates nothing; this is the repaint
3348+ // that puts the new glyph up.
3349+ cx.notify();
3350+ }
31943351 }
3195- } else if let Some(session) = &mut self.session {
3196- session.toggle();
3197- // Past EOF nothing else asks for a repaint.
3198- cx.notify();
31993352 }
32003353 }
32013354
@@ -3412,11 +3565,9 @@ impl Render for Player {
34123565 window.set_window_title(&title);
34133566 self.titled = title;
34143567 }
3415- // No shadow flag: the clock is the only truth about play state.
3416- let playing = self
3417- .session
3418- .as_ref()
3419- .is_some_and(PlaybackSession::is_playing);
3568+ // No shadow flag: the session is the only truth about play state, and
3569+ // [`Player::transport`] is the one place it is read.
3570+ let state = self.transport();
34203571 // A paused timeline has nothing to animate; the toggle handlers notify,
34213572 // which is what starts the loop again. A paused seek keeps the loop
34223573 // running by itself until `pump` has the frame it asked for. An export
@@ -3424,7 +3575,7 @@ impl Render for Player {
34243575 // the screen on a repaint. A notice does not: it waits to be dismissed
34253576 // rather than for a clock, so keeping the loop alive for it would spin
34263577 // the GPU until someone answered it.
3427- if (playing && !self.done) || self.pending_seek || self.export.is_some() {
3578+ if state.is_playing() || self.pending_seek || self.export.is_some() {
34283579 window.request_animation_frame();
34293580 }
34303581
@@ -3437,7 +3588,7 @@ impl Render for Player {
34373588 // edit that shortens the timeline moves the far end of the view, and a
34383589 // playhead that has run off the bed pulls the view after it -- which is
34393590 // what makes a zoomed-in timeline scroll while it plays.
3440- self.view = self.view.following(position, duration, self.fps);
3591+ self.scale = self.view().following(position);
34413592
34423593 div()
34433594 .track_focus(&self.focus)
@@ -3889,7 +4040,7 @@ impl Render for Player {
38894040 // Above the panel and only when there is one to show, so it costs
38904041 // the picture nothing the rest of the time.
38914042 .children(self.notice_bar(cx))
3892- .child(self.panel(position, duration, playing, cx))
4043+ .child(self.panel(position, duration, state, cx))
38934044 // Over the panel it was opened on, and under the cards: it is only
38944045 // ever up while neither of them is (`modal`).
38954046 .children(self.context_card(window.viewport_size(), cx))
@@ -4210,21 +4361,22 @@ impl Player {
42104361 &self,
42114362 position: f64,
42124363 duration: f64,
4213- playing: bool,
4364+ state: Transport,
42144365 cx: &mut Context<Self>,
42154366 ) -> impl IntoElement {
4216- // Where the playhead is *on the bed*, which at the fit is where along
4217- // the timeline it is and zoomed in is where along the visible slice.
4218- // Clamped because it is drawn as a width as well as an offset, and the
4219- // view follows the playhead anyway, so it is never off the bed.
4220- let filled = self.view.frac_at(position, duration).clamp(0., 1.);
4367+ // Where the playhead is *on the bed*, in pixels from its left edge.
4368+ // Clamped to the bed because it is drawn as a width as well as an
4369+ // offset, and the view follows the playhead anyway, so it is never off
4370+ // the bed for long.
4371+ let bed_w = f32::from(self.ruler.get().size.width);
4372+ let filled = self.scale.px_at(position).clamp(0., bed_w);
42214373 // An export owns the hint slot and the ruler while it runs: the
42224374 // percentage and the accent bar are the same number, so the playhead
42234375 // fill doubles as the progress bar for free.
42244376 let exporting = self.exporting().is_some();
42254377 // Everything but Import and Keys needs a timeline to act on: with none
42264378 // open they are dimmed rather than silently doing nothing.
4227- let live = self.session.is_some() && !exporting;
4379+ let live = state != Transport::Stopped && !exporting;
42284380 // The project's own picture size, for the button that cycles it: read
42294381 // per render like everything else here, so a cycle shows on the button
42304382 // that made it.
@@ -4240,7 +4392,7 @@ impl Player {
42404392 // closure would hold it for as long as the iterator lives.
42414393 let mut rows = Vec::new();
42424394 for &lane in &lanes {
4243- rows.push(self.lane_row(lane, duration, filled, cx));
4395+ rows.push(self.lane_row(lane, filled, cx));
42444396 }
42454397 let (hint, filled) = if let Some(export) = self.exporting() {
42464398 let progress = export.progress();
@@ -4270,7 +4422,7 @@ impl Player {
42704422 // of this line is what a narrow window truncates.
42714423 (
42724424 join_detail(
4273- &self.live_decode(position, playing),
4425+ &self.live_decode(position, state.is_playing()),
42744426 &format!(
42754427 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
42764428 import",
@@ -4309,9 +4461,9 @@ impl Player {
43094461 .overflow_x_scroll()
43104462 .child(control(
43114463 "transport",
4312- Some(transport_glyph(playing).into_any_element()),
4313- if playing { "Pause" } else { "Play" },
4314- if nothing_to_play(self.session.as_ref()) && !playing {
4464+ Some(transport_glyph(state).into_any_element()),
4465+ if state.is_playing() { "Pause" } else { "Play" },
4466+ if nothing_to_play(self.session.as_ref()) && !state.is_playing() {
43154467 format!("{} — put a clip on a lane first", key(ActionId::Play))
43164468 } else {
43174469 key(ActionId::Play)
@@ -4321,7 +4473,7 @@ impl Player {
43214473 // against nothing (the key press answers with the
43224474 // notice). Still live while it *is* playing: a delete
43234475 // can empty the timeline mid-play and that has to stop.
4324- live && (playing || !nothing_to_play(self.session.as_ref())),
4476+ live && (state.is_playing() || !nothing_to_play(self.session.as_ref())),
43254477 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
43264478 ))
43274479 .child(separator())
@@ -4439,14 +4591,14 @@ impl Player {
44394591 // How much of the timeline the panel below is showing --
44404592 // beside the resolution, since neither of them edits
44414593 // anything: they are both what is being looked at. The
4442- // middle one reads as the state (1.0x is the whole
4443- // timeline) and is the way back to it.
4594+ // middle one says how much of it is on the bed, and is the
4595+ // way back to the whole of it.
44444596 .child(control(
44454597 "zoom-out",
44464598 None,
44474599 "−",
44484600 format!(
4449- "{} — show more of the timeline; stops at the whole of it",
4601+ "{} — show more of the timeline; stops at four hours on the bed",
44504602 key(ActionId::ZoomOut)
44514603 ),
44524604 live,
@@ -4457,13 +4609,17 @@ impl Player {
44574609 .child(control(
44584610 "zoom-fit",
44594611 None,
4460- format!("{:.1}x", self.view.zoom),
4612+ // How much timeline is on the bed, not a multiple of
4613+ // "the whole of it": the scale no longer knows what the
4614+ // whole of it is, and a number that changed on every
4615+ // import was a number that lied.
4616+ span_label(self.view().span()),
44614617 format!(
44624618 "{} — fit the whole timeline; showing {} to {}",
44634619 key(ActionId::ZoomFit),
4464- timecode(self.view.start, self.fps),
4620+ timecode(self.scale.start, self.fps),
44654621 timecode(
4466- (self.view.start + self.view.span(duration)).min(duration),
4622+ (self.scale.start + self.view().span()).min(duration),
44674623 self.fps
44684624 )
44694625 ),
@@ -4531,8 +4687,10 @@ impl Player {
45314687 .child(control(
45324688 "keys",
45334689 None,
4534- "Keys",
4535- "show and change the keybindings".to_string(),
4690+ "Actions",
4691+ // The pointer's way to every action there is, including
4692+ // the ones no button here has room for.
4693+ "do any action, or change the key that does it".to_string(),
45364694 !exporting,
45374695 cx.listener(|this, _: &ClickEvent, _, cx| {
45384696 this.keys_open = !this.keys_open;
@@ -4614,7 +4772,7 @@ impl Player {
46144772 if dy == 0. {
46154773 return;
46164774 }
4617- let anchor = frac_along(event.position.x, this.ruler.get());
4775+ let anchor = px_along(event.position.x, this.ruler.get());
46184776 let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP };
46194777 this.zoom(factor, Some(anchor), cx);
46204778 },
@@ -4636,7 +4794,7 @@ impl Player {
46364794 .child(
46374795 div()
46384796 .h_full()
4639- .w(relative(filled))
4797+ .w(px(filled))
46404798 .rounded(px(3.))
46414799 .bg(rgb(ACCENT)),
46424800 ),
@@ -4742,83 +4900,115 @@ impl Player {
47424900 ctrl: false,
47434901 }
47444902 .pretty();
4745- // Every stroke that works, under its heading, and both halves of the
4746- // list come from the registry: one row per action -- an action with two
4747- // strokes reads as one line ("x or delete") and a rebind replaces that
4748- // whole set -- then the strokes the modal cards answer to, which are
4749- // shown but not offered, because nothing may unbind the way out.
4903+ // Every action there is, under its heading, and the strokes the modal
4904+ // cards answer to beside them -- `keys_rows` is the whole of the order
4905+ // and every word in it comes off the registry.
4906+ //
4907+ // A row is two targets, not one: its label *does* the action, which is
4908+ // the pointer's way to the ones no button carries, and its stroke
4909+ // changes that stroke. An action with two strokes reads as one line
4910+ // ("x or delete") and a rebind replaces that whole set.
47504911 let mut rows: Vec<AnyElement> = Vec::new();
4751- for category in keymap::Category::ALL {
4752- let actions = ActionId::ALL
4753- .into_iter()
4754- .enumerate()
4755- .filter(|(_, a)| a.category() == category);
4756- let fixed = keymap::FIXED.iter().filter(|f| f.category == category);
4757- let mut headed = false;
4758- let mut head = |rows: &mut Vec<AnyElement>| {
4759- if !std::mem::replace(&mut headed, true) {
4760- rows.push(
4761- div()
4762- .flex_none()
4763- .px(px(6.))
4764- .pt(px(4.))
4765- .text_size(px(11.))
4766- .text_color(rgb(INK_DIM))
4767- .child(category.label())
4768- .into_any_element(),
4769- );
4770- }
4771- };
4772- for (i, action) in actions {
4773- head(&mut rows);
4774- let capturing = self.rebinding == Some(action);
4775- let out = out.clone();
4776- rows.push(
4777- div()
4778- .id(("bind", i))
4779- .flex()
4780- // The floor, not the height: a row that needed two lines
4781- // would otherwise paint over the one under it.
4782- .min_h(px(KEYS_ROW_H))
4783- .items_center()
4784- .justify_between()
4785- .gap(px(12.))
4786- .px(px(6.))
4787- .rounded(px(3.))
4788- .cursor_pointer()
4789- .hover(|s| s.bg(rgb(HOVER)))
4912+ let row = || {
4913+ div()
4914+ .flex()
4915+ // The floor, not the height: a row that needed two lines
4916+ // would otherwise paint over the one under it.
4917+ .min_h(px(KEYS_ROW_H))
4918+ .items_center()
4919+ .justify_between()
4920+ .gap(px(12.))
4921+ .px(px(6.))
4922+ .rounded(px(3.))
4923+ };
4924+ for (i, key_row) in keys_rows().into_iter().enumerate() {
4925+ rows.push(match key_row {
4926+ KeyRow::Head(category) => div()
4927+ .flex_none()
4928+ .px(px(6.))
4929+ .pt(px(4.))
4930+ .text_size(px(11.))
4931+ .text_color(rgb(INK_DIM))
4932+ .child(category.label())
4933+ .into_any_element(),
4934+ KeyRow::Act(action) => {
4935+ let capturing = self.rebinding == Some(action);
4936+ // Why the label half will not answer, if it will not: the
4937+ // registry's one answer, the same the clip menu dims by.
4938+ let refusal = self.enable(action, None);
4939+ let out = out.clone();
4940+ row()
47904941 .when(capturing, |d| d.bg(rgb(SELECTED)))
4791- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4792- this.rebinding = Some(action);
4793- cx.notify();
4794- }))
4795- .child(action.label())
4796- .child(if capturing {
4942+ .child(
47974943 div()
4798- .text_color(rgb(INK_DIM))
4799- .child(format!("press a key — {out} cancels"))
4800- } else {
4801- div().child(self.keymap.display(action))
4802- })
4803- .into_any_element(),
4804- );
4805- }
4806- for f in fixed {
4807- head(&mut rows);
4808- rows.push(
4809- div()
4810- .flex()
4811- .min_h(px(KEYS_ROW_H))
4812- .items_center()
4813- .justify_between()
4814- .gap(px(12.))
4815- .px(px(6.))
4944+ .id(("do", i))
4945+ .flex_1()
4946+ .min_w(px(0.))
4947+ .flex()
4948+ .min_h(px(KEYS_ROW_H))
4949+ .items_center()
4950+ .child(action.label())
4951+ // The reason rides on the label rather than in
4952+ // the stroke column, which the rebind half
4953+ // needs whatever the editor's state is: an
4954+ // action nobody can ask for right now is still
4955+ // one whose key may be changed.
4956+ .when_some(refusal.why(), |d, why| {
4957+ let why: SharedString = why.into();
4958+ d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into())
4959+ })
4960+ .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed())
4961+ .when(refusal.yes(), |d| {
4962+ d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click(
4963+ cx.listener(move |this, _: &ClickEvent, _, cx| {
4964+ // The card goes first: several of
4965+ // these open a card of their own,
4966+ // and every edit moves the indices
4967+ // the menus are holding.
4968+ this.keys_open = false;
4969+ this.rebinding = None;
4970+ this.act(action, cx);
4971+ cx.notify();
4972+ }),
4973+ )
4974+ }),
4975+ )
4976+ .child(
4977+ // ponytail: the column is as wide as the stroke it
4978+ // prints, so a one-character chord gives this half a
4979+ // hit area under the 24px WCAG 2.5.8 floor -- tall
4980+ // enough, narrow. Upgrade: a min_w of HIT_MIN here.
4981+ div()
4982+ .id(("bind", i))
4983+ .flex_none()
4984+ .flex()
4985+ .min_h(px(KEYS_ROW_H))
4986+ .items_center()
4987+ .cursor_pointer()
4988+ .hover(|s| s.bg(rgb(HOVER)))
4989+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
4990+ this.rebinding = Some(action);
4991+ cx.notify();
4992+ }))
4993+ .child(if capturing {
4994+ div()
4995+ .text_color(rgb(INK_DIM))
4996+ .child(format!("press a key — {out} cancels"))
4997+ } else {
4998+ div().child(self.keymap.display(action))
4999+ }),
5000+ )
5001+ .into_any_element()
5002+ }
5003+ KeyRow::Fixed(f) => {
5004+ let f = &keymap::FIXED[f];
5005+ row()
48165006 .child(f.label)
48175007 // Dim, and no hover: this one is not a row you can click.
48185008 .child(div().text_color(rgb(INK_DIM)).child(f.chord))
4819- .into_any_element(),
4820- );
4821- }
5009+ .into_any_element()
5010+ }
5011+ });
48225012 }
48235013 Some(
48245014 div()
@@ -4845,7 +5035,7 @@ impl Player {
48455035 // Title and instruction are two children, never one
48465036 // wrapping line: a fixed-height slot whose text wrapped
48475037 // painted its second line over the first row.
4848- .child(div().flex_none().px(px(6.)).child("Keybindings"))
5038+ .child(div().flex_none().px(px(6.)).child("Actions & keys"))
48495039 // One status line, under the title where the eye starts.
48505040 // A refusal takes it over -- it is the more urgent of the
48515041 // two, and the notice bar it would otherwise appear in is
@@ -4863,7 +5053,10 @@ impl Player {
48635053 .child(
48645054 self.notice
48655055 .clone()
4866- .unwrap_or_else(|| "click a row, then press a key".into()),
5056+ .unwrap_or_else(|| {
5057+ "click an action to do it · click its key to change it"
5058+ .into()
5059+ }),
48675060 ),
48685061 )
48695062 // Capped and scrolling rather than as tall as the action
@@ -6402,7 +6595,6 @@ impl Player {
64026595 let menu = self.context_menu?;
64036596 let session = self.session.as_ref()?;
64046597 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
6405- let playhead = frame_at(session.now(), self.fps);
64066598 let source = session.sources().get(clip.source).cloned()?;
64076599 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
64086600 let row = |n: usize| {
@@ -6456,7 +6648,11 @@ impl Player {
64566648 }
64576649 } else {
64586650 for action in MENU_ITEMS {
6459- let enabled = applicable(&clip, menu.lane, action, playhead);
6651+ // The registry's own answer, the same one the actions card
6652+ // dims a row with -- and a row that takes no click says *why*
6653+ // rather than printing a stroke that would do nothing.
6654+ let refusal = self.enable(action, Some((menu.lane, menu.idx)));
6655+ let enabled = refusal.yes();
64606656 // The one item that is not about this clip says so, and says it
64616657 // here rather than in the registry: the stroke is global too,
64626658 // but its row in the keys menu is not sitting on a clip.
@@ -6468,11 +6664,20 @@ impl Player {
64686664 rows.push(
64696665 row(rows.len())
64706666 .child(label)
6471- .child(
6472- div()
6667+ .child(match refusal.why() {
6668+ // One truncated line, like the details side: a
6669+ // reason that wrapped would make the card taller
6670+ // than the height `menu_at` placed it by.
6671+ Some(why) => div()
6672+ .min_w(px(0.))
6673+ .truncate()
6674+ .text_size(px(11.))
6675+ .text_color(rgb(INK_DIM))
6676+ .child(why),
6677+ None => div()
64736678 .text_color(rgb(INK_DIM))
64746679 .child(self.keymap.display(action)),
6475- )
6680+ })
64766681 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
64776682 .when(enabled, |d| {
64786683 d.cursor_pointer()
@@ -6591,21 +6796,18 @@ impl Player {
65916796 fn lane_row(
65926797 &self,
65936798 lane: Lane,
6594- duration: f64,
6799+ // Where the playhead is on the bed, in pixels: worked out once by the
6800+ // panel so the ruler's line and every lane's draw the same one.
65956801 filled: f32,
65966802 cx: &mut Context<Self>,
65976803 // Borrows nothing it was given (`use<>`): the rows are built one after
65986804 // another into a list, and a row still holding `cx` would be the only
65996805 // one that could be built.
66006806 ) -> impl IntoElement + use<> {
6601- // The bed's own width, measured last repaint off the ruler's bar: the
6602- // two are laid out identically (same header offset, same `flex_1`), so
6603- // one probe answers for both. Zero before the first paint, which only
6604- // costs the labels one frame.
6605- let bed_w = f32::from(self.ruler.get().size.width);
6606- // The slice being shown, copied out once: every box in the row is
6607- // placed through it, so all of them move together when it does.
6608- let view = self.view;
6807+ // The mapping, copied out once: every box in the row is placed through
6808+ // it, so all of them move together when it does. No bed width is needed
6809+ // to place them any more -- a second is so many pixels wherever it is.
6810+ let scale = self.scale;
66096811 let clips = self
66106812 .session
66116813 .as_ref()
@@ -6789,7 +6991,7 @@ impl Player {
67896991 .and_then(|s| sources.iter().position(|o| o.path == s.path))
67906992 .unwrap_or(clip.source),
67916993 );
6792- let width = view.width_frac(len, duration);
6994+ let width = scale.width_px(len);
67936995 let label = sources.get(clip.source).map(|s| file_name(&s.path));
67946996 let wave = sources
67956997 .get(clip.source)
@@ -6821,8 +7023,8 @@ impl Player {
68217023 // off the left edge: the bed clips what hangs out
68227024 // of it, so a half-visible clip is drawn as the
68237025 // half of itself that is on screen.
6824- .left(relative(view.frac_at(start, duration)))
6825- .w(relative(width))
7026+ .left(px(scale.px_at(start)))
7027+ .w(px(width))
68267028 .overflow_hidden()
68277029 .rounded(px(3.))
68287030 .border_1()
@@ -6965,7 +7167,7 @@ impl Player {
69657167 .child(format!("{}", clip.speed)),
69667168 )
69677169 })
6968- .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
7170+ .when_some(label.filter(|_| show_label(width)), |d, label| {
69697171 d.child(
69707172 div()
69717173 .relative()
@@ -6991,12 +7193,8 @@ impl Player {
69917193 .absolute()
69927194 .top_0()
69937195 .h_full()
6994- .left(relative(
6995- view.frac_at(f64::from(at) / self.fps, duration),
6996- ))
6997- .w(relative(
6998- view.width_frac(f64::from(len) / self.fps, duration),
6999- ))
7196+ .left(px(scale.px_at(f64::from(at) / self.fps)))
7197+ .w(px(scale.width_px(f64::from(len) / self.fps)))
70007198 .bg(rgba(0x4a9effaa))
70017199 }),
70027200 )
@@ -7007,7 +7205,7 @@ impl Player {
70077205 .absolute()
70087206 .top_0()
70097207 .h_full()
7010- .left(relative(filled))
7208+ .left(px(filled))
70117209 .w(px(1.))
70127210 .bg(rgb(ACCENT)),
70137211 ),
@@ -7248,42 +7446,132 @@ fn band_label(band: &Band) -> String {
72487446 }
72497447 }
72507448
7251-/// Whether the clip menu offers `action` on the clip it was opened on. Two of
7252-/// the items act on the *playhead* rather than on the clip, so a menu opened
7253-/// away from it dims them instead of looking broken when they are clicked, and
7254-/// one acts on sound, which only an audio lane's clip has.
7255-fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool {
7256- match action {
7257- // The equalizer filters samples, and a video clip has none of its own
7258- // here: the sound is the audio lane's, clip for clip.
7259- ActionId::Equalizer => lane.kind == LaneKind::Audio,
7260- // A grade is a picture setting and an audio clip has no picture: the
7261- // item is there on every clip, and dimmed where it would mean nothing.
7262- // A fit policy is a picture setting for the same reason.
7263- ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,
7264- // Splits this clip only from inside it: at either edge there is nothing
7265- // to split off -- and, on a speeded clip, only at a frame its own rate
7266- // can address, which is the same question `splittable` asks.
7267- ActionId::Cut => {
7268- clip.start < playhead
7269- && playhead < clip.end()
7270- && clip
7271- .speed
7272- .split_at(clip.len(), playhead - clip.start)
7273- .is_some()
7449+/// Whether an action can be asked for, and what to say when it cannot. Two
7450+/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at
7451+/// -- an audio clip has no picture, so a grade is not a thing that exists for
7452+/// it, whatever the editor does next -- and `No` is about the state of this
7453+/// moment, which the next click of the playhead can change. Both dim their row
7454+/// today; a menu that wants to leave the class refusals out and keep the state
7455+/// ones has only to match on which of the two it got.
7456+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7457+enum Enable {
7458+ Yes,
7459+ No(&'static str),
7460+ Hidden(&'static str),
7461+}
7462+
7463+impl Enable {
7464+ /// Whether the row takes a click.
7465+ fn yes(self) -> bool {
7466+ self == Enable::Yes
7467+ }
7468+
7469+ /// What the row says instead of its stroke, if it says anything.
7470+ fn why(self) -> Option<&'static str> {
7471+ match self {
7472+ Enable::Yes => None,
7473+ Enable::No(why) | Enable::Hidden(why) => Some(why),
72747474 }
7275- // A rate applies to a clip of either kind and to its whole group, so
7276- // there is no lane it means nothing on -- `_ => true` below is its
7277- // answer, and the engine words the one refusal there is (no room).
7475+ }
7476+}
7477+
7478+/// What an enablement question is asked *about*: the clip in question, if there
7479+/// is one, and the little of the editor's state the answers need. Handed in
7480+/// rather than read off the player, so [`enable`] is a pure function a test can
7481+/// ask about a clip without building a window.
7482+#[derive(Clone, Copy, Default)]
7483+struct Ctx {
7484+ /// The clip the question is about -- the one a menu was opened on, or the
7485+ /// marked one. `None` means the question is about the editor as a whole,
7486+ /// and the clip-relative answers stand aside: those actions find their own
7487+ /// clip under the playhead and word their own refusal.
7488+ clip: Option<(Clip, Lane)>,
7489+ playhead: u32,
7490+ /// A timeline is open.
7491+ timeline: bool,
7492+ /// Something has been copied.
7493+ clipboard: bool,
7494+ exporting: bool,
7495+}
7496+
7497+/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing
7498+/// else in the editor asks the question: the clip menu dims a row with this,
7499+/// the actions card dims a row with this, and the two can never come to
7500+/// disagree about what an action needs -- exactly the reason [`Player::act`] is
7501+/// one table too.
7502+fn enable(action: ActionId, ctx: Ctx) -> Enable {
7503+ if !ctx.timeline {
7504+ return Enable::No("no timeline open");
7505+ }
7506+ // An export is reading the edit list every other action would change, which
7507+ // is the rule the key handler already follows.
7508+ if ctx.exporting {
7509+ return match action {
7510+ ActionId::CancelExport => Enable::Yes,
7511+ _ => Enable::No("an export is running"),
7512+ };
7513+ }
7514+ match action {
7515+ // -- class: what kind of thing the action is about. The equalizer
7516+ // filters samples, and a video clip has none of its own here: the sound
7517+ // is the audio lane's, clip for clip.
7518+ ActionId::Equalizer => match ctx.clip {
7519+ Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"),
7520+ _ => Enable::Yes,
7521+ },
7522+ // A grade is a picture setting and an audio clip has no picture. A fit
7523+ // policy is a picture setting for the same reason.
7524+ ActionId::Color | ActionId::Fit => match ctx.clip {
7525+ Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"),
7526+ _ => Enable::Yes,
7527+ },
7528+ // -- state: true of this clip now, and the next playhead click or the
7529+ // next selection changes the answer. Splits this clip only from inside
7530+ // it: at either edge there is nothing to split off -- and, on a speeded
7531+ // clip, only at a frame its own rate can address, which is the same
7532+ // question `splittable` asks.
7533+ ActionId::Cut => match ctx.clip {
7534+ Some((clip, _))
7535+ if !(clip.start < ctx.playhead
7536+ && ctx.playhead < clip.end()
7537+ && clip
7538+ .speed
7539+ .split_at(clip.len(), ctx.playhead - clip.start)
7540+ .is_some()) =>
7541+ {
7542+ Enable::No("only from inside a clip")
7543+ }
7544+ _ => Enable::Yes,
7545+ },
72787546 // Rejoins whatever meets at the playhead, so it can mean something only
72797547 // at an edge of this clip. Whether those two halves were ever one take
72807548 // is the engine's question, and it words that refusal itself.
7281- ActionId::Regroup => playhead == clip.start || playhead == clip.end(),
7549+ ActionId::Regroup => match ctx.clip {
7550+ Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => {
7551+ Enable::No("only where two clips meet")
7552+ }
7553+ _ => Enable::Yes,
7554+ },
72827555 // Nothing to take apart in a clip that names no group at all. Whether
72837556 // the group it names still has another half is the engine's question,
7284- // like the regroup above, and it words that refusal itself.
7285- ActionId::Detach => clip.link.is_some(),
7286- _ => true,
7557+ // like the regroup above.
7558+ ActionId::Detach => match ctx.clip {
7559+ Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"),
7560+ _ => Enable::Yes,
7561+ },
7562+ // The three that act on the marked clip and on nothing else: with none
7563+ // marked they would silently do nothing, which is what the Delete
7564+ // button's own dimming has always said.
7565+ ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => {
7566+ Enable::No("click a clip first")
7567+ }
7568+ ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"),
7569+ ActionId::CancelExport => Enable::No("nothing is exporting"),
7570+ // A rate applies to a clip of either kind and to its whole group, so
7571+ // there is no lane it means nothing on, and the engine words the one
7572+ // refusal there is (no room). Everything else is the editor's own and
7573+ // needs nothing but a timeline.
7574+ _ => Enable::Yes,
72877575 }
72887576 }
72897577
@@ -8062,10 +8350,6 @@ fn panel_h(lanes: usize) -> f32 {
80628350 PANEL_H + lanes_h(lanes.clamp(2, LANES_MAX)) - lanes_h(2)
80638351 }
80648352
8065-fn width_frac(len: f64, total: f64) -> f32 {
8066- if total > 0. { (len / total) as f32 } else { 1. }
8067-}
8068-
80698353 /// One press of a zoom key, or one notch of ctrl+wheel.
80708354 const ZOOM_STEP: f32 = 1.25;
80718355
@@ -8074,118 +8358,222 @@ const ZOOM_STEP: f32 = 1.25;
80748358 /// not an edit surface.
80758359 const ZOOM_MIN_FRAMES: f64 = 8.;
80768360
8077-/// Which slice of the timeline the ruler and the lanes are showing: `zoom` is
8078-/// how many times the whole of it the bed is now worth, and `start` the moment
8079-/// at the bed's left edge. The one place frames become pixels -- every box, the
8080-/// playhead, a seek and a trim all go through it, so none of them can drift
8081-/// away from the others when the view moves.
8361+/// How much timeline the bed may be widened out to hold. The far stop, and the
8362+/// counterpart of [`ZOOM_MIN_FRAMES`]: both are measured against the bed, never
8363+/// against what is on the timeline, so neither moves when a clip is added.
8364+const ZOOM_MAX_SECONDS: f64 = 4. * 3600.;
8365+
8366+/// How wide a second of timeline is drawn before anyone zooms: a five second
8367+/// import is 200 px of a bed several times that, so a short clip reads as
8368+/// short -- the thing a bed scaled to the content's own length cannot say.
8369+/// [`View::fit`] is the one way back to "the whole timeline across the bed".
8370+const PPS_DEFAULT: f64 = 40.;
8371+
8372+/// What the zoom button says it is showing: how much timeline fits on the bed,
8373+/// in the coarsest unit that still tells two zooms apart.
8374+fn span_label(span: f64) -> String {
8375+ match span {
8376+ s if !s.is_finite() || s <= 0. => "—".to_string(),
8377+ s if s >= 600. => format!("{:.0}m", s / 60.),
8378+ s if s >= 60. => format!("{:.1}m", s / 60.),
8379+ s if s >= 10. => format!("{s:.0}s"),
8380+ s => format!("{s:.1}s"),
8381+ }
8382+}
8383+
8384+/// The mapping the whole panel is drawn and clicked through: `pps` pixels to a
8385+/// second of timeline, `start` the moment at the bed's left edge. Absolute --
8386+/// how wide a clip is drawn depends on how long the clip is and on nothing
8387+/// else, so adding a second clip does not redraw the first one narrower and
8388+/// zooming out always makes every box smaller.
80828389 ///
8083-/// [`View::default`] is the whole timeline across the bed, which is what the
8084-/// panel drew before there was a zoom at all: at zoom 1 `start` is pinned to 0
8085-/// and every fraction here is the one [`width_frac`] and `start_frac` gave.
8390+/// The one place seconds become pixels: every box, the playhead, a seek and a
8391+/// trim all go through it, so none of them can drift away from the others when
8392+/// the view moves. What clamps it -- the stops, the scroll, the fit -- needs the
8393+/// bed it is drawn on and lives on [`View`].
80868394 #[derive(Clone, Copy, Debug, PartialEq)]
8087-struct View {
8088- zoom: f32,
8395+struct Scale {
8396+ pps: f64,
80898397 start: f64,
80908398 }
80918399
8092-impl Default for View {
8400+impl Default for Scale {
80938401 fn default() -> Self {
8094- View {
8095- zoom: 1.,
8402+ Scale {
8403+ pps: PPS_DEFAULT,
80968404 start: 0.,
80978405 }
80988406 }
80998407 }
81008408
8101-impl View {
8102- /// How much of the timeline is on the bed, in seconds.
8103- fn span(self, duration: f64) -> f64 {
8104- duration / f64::from(self.zoom)
8409+impl Scale {
8410+ /// Where a moment sits on the bed, in pixels from its left edge. Negative
8411+ /// for a moment scrolled off to the left, which is exactly the offset a
8412+ /// half-visible clip is drawn at.
8413+ fn px_at(self, at: f64) -> f32 {
8414+ ((at - self.start) * self.pps) as f32
81058415 }
81068416
8107- /// The tightest this timeline may be zoomed: [`ZOOM_MIN_FRAMES`] across the
8108- /// bed. Never under 1 -- a timeline shorter than that is already at its
8109- /// floor, and a zoom that cannot fit the whole of it is not a zoom.
8110- fn max_zoom(duration: f64, fps: f64) -> f32 {
8111- let frames = duration * fps;
8112- if frames > ZOOM_MIN_FRAMES {
8113- (frames / ZOOM_MIN_FRAMES) as f32
8417+ /// How wide a stretch of `len` seconds is drawn. Wider than the bed once
8418+ /// zoomed in, which is the point of zooming in; never negative, which gpui
8419+ /// has no meaning for.
8420+ fn width_px(self, len: f64) -> f32 {
8421+ (len * self.pps).max(0.) as f32
8422+ }
8423+
8424+ /// The moment `x` pixels along the bed is pointing at: the inverse of
8425+ /// [`Scale::px_at`], and what every seek and every trim reads. Clamped at
8426+ /// the head of the timeline only -- there is bed past the last frame now,
8427+ /// and a tail dragged into it is a longer clip, not an error.
8428+ fn time_at(self, x: f32) -> f64 {
8429+ if self.pps > 0. {
8430+ (self.start + f64::from(x) / self.pps).max(0.)
81148431 } else {
8115- 1.
8432+ self.start
81168433 }
81178434 }
81188435
8119- /// Where a moment sits along the bed, 0 at its left edge and 1 at its
8120- /// right. Outside that range for a moment scrolled off the view, which is
8121- /// exactly the negative offset a half-visible clip is drawn at.
8122- fn frac_at(self, at: f64, duration: f64) -> f32 {
8123- let span = self.span(duration);
8124- if span > 0. {
8125- ((at - self.start) / span) as f32
8436+ /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: a snap
8437+ /// is a distance on screen, so zoomed right in it is worth less than a frame
8438+ /// (no snap at all, which is what a hand placing single frames wants) and
8439+ /// zoomed out it is worth many.
8440+ fn snap_frames(self, fps: f64) -> u32 {
8441+ if self.pps > 0. {
8442+ (SNAP_PX / self.pps * fps) as u32
8443+ } else {
8444+ 0
8445+ }
8446+ }
8447+}
8448+
8449+/// A [`Scale`] against the bed it is drawn on and the timeline it is drawn
8450+/// from. The bed's width is what turns a scale into "how much is on screen",
8451+/// and that is all the stops, the scroll clamp and the fit are made of.
8452+///
8453+/// Built per use out of [`Player::view`] and thrown away again -- the state is
8454+/// the `Scale`, and this is what a bed of `bed` px showing `duration` seconds
8455+/// at `fps` may do to it. So no call site can measure a moment against a bed or
8456+/// a duration that another one did not.
8457+#[derive(Clone, Copy, Debug, PartialEq)]
8458+struct View {
8459+ scale: Scale,
8460+ bed: f32,
8461+ duration: f64,
8462+ fps: f64,
8463+}
8464+
8465+impl View {
8466+ /// How much of the timeline is on the bed, in seconds.
8467+ fn span(self) -> f64 {
8468+ if self.scale.pps > 0. {
8469+ f64::from(self.bed) / self.scale.pps
81268470 } else {
81278471 0.
81288472 }
81298473 }
81308474
8131- /// How wide a stretch of `len` seconds is on the bed. More than the whole
8132- /// bed once zoomed in, which is the point of zooming in.
8133- fn width_frac(self, len: f64, duration: f64) -> f32 {
8134- width_frac(len, self.span(duration))
8475+ /// The two stops, in pixels per second: [`ZOOM_MIN_FRAMES`] across the bed
8476+ /// is as tight as it goes, [`ZOOM_MAX_SECONDS`] across it as wide. `None`
8477+ /// on a bed that was never painted -- there is nothing to measure them
8478+ /// against yet, and a stop guessed off a zero width would throw away a zoom
8479+ /// the user asked for.
8480+ fn stops(self) -> Option<(f64, f64)> {
8481+ (self.bed > 0.).then(|| {
8482+ let bed = f64::from(self.bed);
8483+ let min = bed / ZOOM_MAX_SECONDS;
8484+ (min, (bed * self.fps / ZOOM_MIN_FRAMES).max(min))
8485+ })
81358486 }
81368487
8137- /// The moment a pointer at `frac` along the bed is pointing at: the inverse
8138- /// of [`View::frac_at`], and what every seek and every trim reads.
8139- fn time_at(self, frac: f32, duration: f64) -> f64 {
8140- (self.start + f64::from(frac) * self.span(duration)).clamp(0., duration)
8488+ /// Clamped to the bed it draws on: between the two stops, and never
8489+ /// scrolled past either end of the timeline. Unlike the fractional view
8490+ /// this replaced, the *floor* is not the content -- a five second timeline
8491+ /// zooms out as far as an hour long one does.
8492+ fn settled(self) -> Scale {
8493+ let pps = match self.scale.pps.is_finite() && self.scale.pps > 0. {
8494+ true => self.scale.pps,
8495+ false => PPS_DEFAULT,
8496+ };
8497+ let start = match self.scale.start.is_finite() {
8498+ true => self.scale.start,
8499+ false => 0.,
8500+ };
8501+ let Some((min, max)) = self.stops() else {
8502+ return Scale {
8503+ pps,
8504+ start: start.max(0.),
8505+ };
8506+ };
8507+ let pps = pps.clamp(min, max);
8508+ let span = f64::from(self.bed) / pps;
8509+ Scale {
8510+ pps,
8511+ start: start.clamp(0., (self.duration - span).max(0.)),
8512+ }
81418513 }
81428514
8143- /// Zoomed by `factor` about `anchor` (0..1 along the bed): whatever moment
8515+ /// Zoomed by `factor` about `anchor` (pixels along the bed): whatever moment
81448516 /// was under that point stays under it, so a zoom magnifies what was being
81458517 /// looked at rather than throwing it off the edge.
8146- fn zoomed(self, factor: f32, anchor: f32, duration: f64, fps: f64) -> Self {
8147- let at = self.start + f64::from(anchor) * self.span(duration);
8518+ fn zoomed(self, factor: f32, anchor: f32) -> Scale {
8519+ let at = self.scale.time_at(anchor);
81488520 // Clamped *before* the offset is worked out, not after: a press that
81498521 // runs into either stop must still leave the anchor where it is, and a
8150- // start measured against a zoom the stop then took away would slide it.
8151- let zoom = (self.zoom * factor).clamp(1., Self::max_zoom(duration, fps));
8152- let start = at - f64::from(anchor) * View { zoom, start: 0. }.span(duration);
8153- View { zoom, start }.settled(duration, fps)
8154- }
8155-
8156- /// Clamped to the timeline it draws: never wider than the whole of it (the
8157- /// zoom-out floor is the fit), never tighter than [`View::max_zoom`], and
8158- /// never scrolled past either end.
8159- fn settled(self, duration: f64, fps: f64) -> Self {
8160- let zoom = if self.zoom.is_finite() {
8161- self.zoom.clamp(1., Self::max_zoom(duration, fps))
8162- } else {
8163- 1.
8522+ // start measured against a scale the stop then took away would slide it.
8523+ let raw = self.scale.pps * f64::from(factor);
8524+ let pps = match self.stops() {
8525+ Some((min, max)) => raw.clamp(min, max),
8526+ None => raw,
81648527 };
8165- let span = View { zoom, start: 0. }.span(duration);
8166- let start = if self.start.is_finite() {
8167- self.start.clamp(0., (duration - span).max(0.))
8168- } else {
8169- 0.
8528+ View {
8529+ scale: Scale {
8530+ pps,
8531+ start: at - f64::from(anchor) / pps,
8532+ },
8533+ ..self
8534+ }
8535+ .settled()
8536+ }
8537+
8538+ /// The whole timeline across the bed. The one place the content's own
8539+ /// length sets the scale, and the only one -- everywhere else a second is a
8540+ /// second -- because this is a user pressing a key that asks for exactly
8541+ /// that.
8542+ fn fit(self) -> Scale {
8543+ let pps = match self.duration > 0. && self.bed > 0. {
8544+ true => f64::from(self.bed) / self.duration,
8545+ false => PPS_DEFAULT,
81708546 };
8171- View { zoom, start }
8547+ View {
8548+ scale: Scale { pps, start: 0. },
8549+ ..self
8550+ }
8551+ .settled()
81728552 }
81738553
8174- /// The view a playhead at `at` needs: the same one while it is on the bed,
8554+ /// The scale a playhead at `at` needs: the same one while it is on the bed,
81758555 /// and one centred on it once it has run off -- which is how a zoomed-in
8176- /// timeline scrolls, during playback and after a seek alike. At the fit
8177- /// this can never fire, so an unzoomed panel is untouched by it.
8178- fn following(self, at: f64, duration: f64, fps: f64) -> Self {
8179- let view = self.settled(duration, fps);
8180- let span = view.span(duration);
8181- if at < view.start || at > view.start + span {
8556+ /// timeline scrolls, during playback and after a seek alike. With the whole
8557+ /// timeline on the bed this can never fire, so a panel showing all of it is
8558+ /// untouched by it.
8559+ fn following(self, at: f64) -> Scale {
8560+ // Nothing is drawn yet, so nothing has run off anything.
8561+ if self.bed <= 0. {
8562+ return self.scale;
8563+ }
8564+ let scale = self.settled();
8565+ let span = f64::from(self.bed) / scale.pps;
8566+ if at < scale.start || at > scale.start + span {
81828567 View {
8183- start: at - span / 2.,
8184- ..view
8568+ scale: Scale {
8569+ start: at - span / 2.,
8570+ ..scale
8571+ },
8572+ ..self
81858573 }
8186- .settled(duration, fps)
8574+ .settled()
81878575 } else {
8188- view
8576+ scale
81898577 }
81908578 }
81918579 }
@@ -8518,6 +8906,15 @@ fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
85188906 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
85198907 }
85208908
8909+/// Where along an element a click landed, in pixels from its own left edge:
8910+/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`]
8911+/// measures in pixels and not in shares of a bed. Clamped to the element -- a
8912+/// drag that slid off the end names its end -- and an element that was never
8913+/// painted reads as its start.
8914+fn px_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
8915+ f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.))
8916+}
8917+
85218918 /// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is
85228919 /// within `tol` frames of where its head -- or its tail, `len` frames along --
85238920 /// would come to rest, in which case that edge wins. The snap every timeline
@@ -8814,9 +9211,12 @@ fn empty_hint() -> impl IntoElement {
88149211 )
88159212 }
88169213
8817-/// Two bars while playing, a triangle while paused. Drawn, so there is no icon
8818-/// font and no glyph coverage to depend on.
8819-fn transport_glyph(playing: bool) -> impl IntoElement {
9214+/// Two bars while playing, a triangle in every other state -- paused, nothing
9215+/// open, and played out, where the button's next act is to start over rather
9216+/// than to stop something. Drawn, so there is no icon font and no glyph
9217+/// coverage to depend on.
9218+fn transport_glyph(state: Transport) -> impl IntoElement {
9219+ let playing = state.is_playing();
88209220 div()
88219221 .flex()
88229222 .items_center()
@@ -8865,26 +9265,26 @@ fn timecode(t: f64, fps: f64) -> String {
88659265 #[cfg(test)]
88669266 mod tests {
88679267 use super::{
8868- ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS,
8869- EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB,
8870- EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, FORMATS, Format, HEADER_GAP,
8871- HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
8872- KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W,
8873- LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE,
8874- PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS,
8875- SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS,
8876- WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export,
8877- clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y,
8878- estimated_mb, export_path, export_settings, format_key, format_line, format_refusal,
8879- fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
8880- keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h,
8881- project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped,
8882- source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, unseen_paths,
8883- unseen_sources, whole_take, width_frac, window_title,
9268+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx,
9269+ EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
9270+ EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
9271+ Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
9272+ INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
9273+ LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
9274+ MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,
9275+ SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,
9276+ Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, band_label, bitrate_refusal,
9277+ can_add, cancels_export, clipboard_after_remove, color_snap, containers, enable, envelope,
9278+ eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key,
9279+ format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,
9280+ is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at, next_container,
9281+ normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,
9282+ show_label, silence_rate, snapped, source_tint, span_partner, speed_at, summary_head,
9283+ summary_tail, timecode, transport, unseen_paths, unseen_sources, whole_take, window_title,
88849284 };
88859285 use super::{
8886- LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows,
8887- repeats, unscannable,
9286+ LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP,
9287+ file_name, file_uri, library_rows, px_along, repeats, span_label, unscannable,
88889288 };
88899289
88909290 /// What the file manager is handed: the parts a path keeps as they are, and
@@ -8909,7 +9309,7 @@ mod tests {
89099309 use gpui::{Bounds, Pixels, point, px, size};
89109310 use std::collections::HashMap;
89119311 use std::path::{Path, PathBuf};
8912- use std::time::Duration;
9312+ use std::time::{Duration, Instant};
89139313
89149314 fn asset(name: &str) -> PathBuf {
89159315 Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -9196,43 +9596,126 @@ mod tests {
91969596 speed: Speed::NORMAL,
91979597 };
91989598 assert_eq!(clip.end(), 90);
9199- // Cut splits from inside only: neither edge has anything to split off.
92009599 let a1 = Lane::A1;
92019600 let v1 = Lane::V1;
9202- assert!(applicable(&clip, v1, ActionId::Cut, 31));
9203- assert!(applicable(&clip, v1, ActionId::Cut, 89));
9204- assert!(!applicable(&clip, v1, ActionId::Cut, 30));
9205- assert!(!applicable(&clip, v1, ActionId::Cut, 90));
9206- assert!(!applicable(&clip, v1, ActionId::Cut, 200));
9601+ // The question the clip menu asks: a timeline is open and the menu was
9602+ // opened on this clip, at this playhead.
9603+ let on = |clip: &Clip, lane, action, playhead| {
9604+ enable(
9605+ action,
9606+ Ctx {
9607+ clip: Some((*clip, lane)),
9608+ playhead,
9609+ timeline: true,
9610+ ..Ctx::default()
9611+ },
9612+ )
9613+ };
9614+ let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes();
9615+ // Cut splits from inside only: neither edge has anything to split off.
9616+ assert!(offered(&clip, v1, ActionId::Cut, 31));
9617+ assert!(offered(&clip, v1, ActionId::Cut, 89));
9618+ assert!(!offered(&clip, v1, ActionId::Cut, 30));
9619+ assert!(!offered(&clip, v1, ActionId::Cut, 90));
9620+ assert!(!offered(&clip, v1, ActionId::Cut, 200));
92079621 // Regroup is the other way round: only where this clip meets another.
9208- assert!(applicable(&clip, v1, ActionId::Regroup, 30));
9209- assert!(applicable(&clip, v1, ActionId::Regroup, 90));
9210- assert!(!applicable(&clip, v1, ActionId::Regroup, 60));
9622+ assert!(offered(&clip, v1, ActionId::Regroup, 30));
9623+ assert!(offered(&clip, v1, ActionId::Regroup, 90));
9624+ assert!(!offered(&clip, v1, ActionId::Regroup, 60));
92119625 // Detach is the clip's own business: nothing to take apart in one that
92129626 // names no group, and whether the group still has another half is the
92139627 // engine's question. Group is offered on every clip, for that reason.
9214- assert!(!applicable(&clip, v1, ActionId::Detach, 0));
9628+ assert!(!offered(&clip, v1, ActionId::Detach, 0));
92159629 let grouped = Clip {
92169630 link: Some(3),
92179631 ..clip
92189632 };
9219- assert!(applicable(&grouped, v1, ActionId::Detach, 60));
9220- assert!(applicable(&clip, a1, ActionId::Group, 0));
9633+ assert!(offered(&grouped, v1, ActionId::Detach, 60));
9634+ assert!(offered(&clip, a1, ActionId::Group, 0));
92219635 // The equalizer is the one item the *lane* decides: it filters samples,
92229636 // and a video clip has none of its own. Never the playhead's business.
9223- assert!(applicable(&clip, a1, ActionId::Equalizer, 0));
9224- assert!(applicable(&clip, a1, ActionId::Equalizer, 60));
9225- assert!(!applicable(&clip, v1, ActionId::Equalizer, 60));
9637+ assert!(offered(&clip, a1, ActionId::Equalizer, 0));
9638+ assert!(offered(&clip, a1, ActionId::Equalizer, 60));
9639+ assert!(!offered(&clip, v1, ActionId::Equalizer, 60));
92269640 // The rest act on the clip that was clicked, so they always mean
92279641 // something -- the engine words its own refusals.
92289642 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
9229- assert!(applicable(&clip, v1, action, 0));
9230- assert!(applicable(&clip, a1, action, 60));
9643+ assert!(offered(&clip, v1, action, 0));
9644+ assert!(offered(&clip, a1, action, 60));
92319645 }
92329646 // Except the grade, which is a picture setting: offered on a video
92339647 // clip wherever the playhead is, dimmed on a waveform.
9234- assert!(applicable(&clip, v1, ActionId::Color, 0));
9235- assert!(!applicable(&clip, a1, ActionId::Color, 60));
9648+ assert!(offered(&clip, v1, ActionId::Color, 0));
9649+ assert!(!offered(&clip, a1, ActionId::Color, 60));
9650+ // The two kinds of no, which is what the row can be told apart by: a
9651+ // grade on a waveform is a *class* answer -- an audio clip has no
9652+ // picture and never will, so a menu may leave the item out -- where a
9653+ // cut at the clip's edge is this moment's answer and the next click of
9654+ // the playhead changes it, so that one is dimmed and stays.
9655+ assert!(matches!(
9656+ on(&clip, a1, ActionId::Color, 60),
9657+ Enable::Hidden(_)
9658+ ));
9659+ assert!(matches!(
9660+ on(&clip, a1, ActionId::Fit, 60),
9661+ Enable::Hidden(_)
9662+ ));
9663+ assert!(matches!(
9664+ on(&clip, v1, ActionId::Equalizer, 60),
9665+ Enable::Hidden(_)
9666+ ));
9667+ assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));
9668+ assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_)));
9669+ assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));
9670+ // Every refusal says something, and says it short enough to sit in the
9671+ // menu's right-hand column beside a label.
9672+ for action in MENU_ITEMS {
9673+ for lane in [v1, a1] {
9674+ for playhead in [0, 30, 60, 90] {
9675+ if let Some(why) = on(&clip, lane, action, playhead).why() {
9676+ assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");
9677+ }
9678+ }
9679+ }
9680+ }
9681+ // The editor as a whole, which is how the actions card asks: with no
9682+ // timeline nothing is offered, an export leaves only its own cancel,
9683+ // and the three that act on the marked clip say so when none is.
9684+ let whole = |action, ctx| enable(action, ctx);
9685+ assert_eq!(
9686+ whole(ActionId::Play, Ctx::default()),
9687+ Enable::No("no timeline open")
9688+ );
9689+ let live = Ctx {
9690+ timeline: true,
9691+ ..Ctx::default()
9692+ };
9693+ assert!(whole(ActionId::Play, live).yes());
9694+ assert!(!whole(ActionId::Delete, live).yes());
9695+ assert!(!whole(ActionId::Paste, live).yes());
9696+ assert!(
9697+ whole(
9698+ ActionId::Paste,
9699+ Ctx {
9700+ clipboard: true,
9701+ ..live
9702+ }
9703+ )
9704+ .yes()
9705+ );
9706+ assert!(!whole(ActionId::CancelExport, live).yes());
9707+ let busy = Ctx {
9708+ exporting: true,
9709+ ..live
9710+ };
9711+ assert!(whole(ActionId::CancelExport, busy).yes());
9712+ for action in ActionId::ALL {
9713+ assert_eq!(
9714+ whole(action, busy).yes(),
9715+ action == ActionId::CancelExport,
9716+ "{action:?} while an export reads the edit list"
9717+ );
9718+ }
92369719 // The playhead frame is the engine's own rule, boundary included.
92379720 assert_eq!(frame_at(1.0, 30.), 30);
92389721 assert_eq!(frame_at(0.0, 30.), 0);
@@ -9275,9 +9758,9 @@ mod tests {
92759758
92769759 /// The other half of the keys menu's guarantee, and the audit this batch was
92779760 /// asked for kept as a test: no action may be a stroke and nothing else.
9278- /// Either the clip menu offers it, or a control in the panel does -- named
9279- /// here by the id [`control`] is handed, read out of this file's own source
9280- /// like `no_stroke_is_missing_from_the_keys_menu` reads the key handler.
9761+ /// The actions card answers it for all of them at once -- its rows come off
9762+ /// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and
9763+ /// there is no hand-written list here to fall behind.
92819764 #[test]
92829765 fn every_action_is_reachable_without_the_keyboard() {
92839766 use keymap::ActionId;
@@ -9286,48 +9769,22 @@ mod tests {
92869769 .next()
92879770 .unwrap();
92889771 let element = |id: &str| source.contains(&format!("\"{id}\""));
9772+ let listed: Vec<ActionId> = keys_rows()
9773+ .iter()
9774+ .filter_map(|r| match r {
9775+ KeyRow::Act(a) => Some(*a),
9776+ _ => None,
9777+ })
9778+ .collect();
92899779 for action in ActionId::ALL {
9290- let by_pointer = MENU_ITEMS.contains(&action)
9291- || match action {
9292- ActionId::Play => element("transport"),
9293- // One slot, two states: it starts an export and stops the
9294- // one it started.
9295- ActionId::Export | ActionId::CancelExport => element("export"),
9296- ActionId::Save => element("save"),
9297- ActionId::Undo => element("undo"),
9298- ActionId::Resolution => element("resolution"),
9299- // Three buttons beside it, and the ctrl+wheel on the bar.
9300- ActionId::ZoomIn => element("zoom-in"),
9301- ActionId::ZoomOut => element("zoom-out"),
9302- ActionId::ZoomFit => element("zoom-fit"),
9303- ActionId::AddVideoLane => element("add-video-lane"),
9304- ActionId::AddAudioLane => element("add-audio-lane"),
9305- // The × in a lane's own header, which takes any track and
9306- // not only the last one.
9307- ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => {
9308- source.contains("this.remove_lane(lane, cx)")
9309- }
9310- ActionId::ToggleMute => element("volume"),
9311- // The fader on every audio track's own header, which is
9312- // also what opens the card the limiter is on.
9313- ActionId::Mix => element("mix-lane"),
9314- ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"),
9315- // The ruler seeks anywhere the pointer points; the frame and
9316- // the second are the keyboard's finer grain of that move.
9317- ActionId::StepBack
9318- | ActionId::StepForward
9319- | ActionId::JumpBack
9320- | ActionId::JumpForward
9321- | ActionId::GoStart
9322- | ActionId::GoEnd => element("ruler"),
9323- // A press on a clip is the selection, group and all.
9324- ActionId::Select | ActionId::SelectNext | ActionId::SelectPrev => {
9325- source.contains("this.select((lane, i), cx)")
9326- }
9327- _ => false,
9328- };
9329- assert!(by_pointer, "{action:?} is reachable by keyboard only");
9780+ assert_eq!(
9781+ listed.iter().filter(|a| **a == action).count(),
9782+ 1,
9783+ "{action:?} is reachable by keyboard only"
9784+ );
93309785 }
9786+ // And the card is a door the pointer can open: the panel's own button.
9787+ assert!(element("keys"), "no way to open the actions card");
93319788 // The card-local strokes have the same rule, and each of them is a thing
93329789 // on its card: the graph and its two buttons, the colour bars and their
93339790 // reset, the speed bar and its presets, and the silence card's rows --
@@ -9942,10 +10399,10 @@ mod tests {
994210399 assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
994310400 }
994410401
9945- /// What a drop reads: the frame under the pointer, through the same view
10402+ /// What a drop reads: the frame under the pointer, through the same scale
994610403 /// the boxes are drawn through. Zoomed in, the same pixel is a different
994710404 /// frame -- which is the whole reason `Player::frame_under` goes through
9948- /// [`View`] rather than through the duration alone.
10405+ /// [`Scale`] rather than through the duration alone.
994910406 #[test]
995010407 fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() {
995110408 // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps.
@@ -9953,29 +10410,32 @@ mod tests {
995310410 origin: point(px(12.), px(400.)),
995410411 size: size(px(200.), px(6.)),
995510412 };
9956- let (duration, fps) = (10., 30.);
10413+ let fps = 30.;
995710414 // The frame a pointer at window `x` names, exactly as `frame_under`
995810415 // composes it.
9959- let under =
9960- |view: View, x: f32| frame_at(view.time_at(frac_along(px(x), bed), duration), fps);
10416+ let under = |scale: Scale, x: f32| frame_at(scale.time_at(px_along(px(x), bed)), fps);
996110417
9962- // The whole timeline across the bed: halfway along is frame 150.
9963- let fit = View::default();
10418+ // The whole 10 s timeline across the 200 px bed: 20 px to the second,
10419+ // so halfway along is frame 150.
10420+ let fit = Scale {
10421+ pps: 20.,
10422+ start: 0.,
10423+ };
996410424 assert_eq!(under(fit, 12.), 0);
996510425 assert_eq!(under(fit, 112.), 150);
996610426 assert_eq!(under(fit, 212.), 300);
996710427
996810428 // Four times in, starting at second 5: the same middle pixel is now the
996910429 // frame in the middle of seconds 5..7.5, and the left edge is not 0.
9970- let zoomed = View {
9971- zoom: 4.,
10430+ let zoomed = Scale {
10431+ pps: 80.,
997210432 start: 5.,
997310433 };
997410434 assert_eq!(under(zoomed, 12.), 150);
997510435 assert_eq!(under(zoomed, 112.), 187);
997610436 assert_eq!(under(zoomed, 212.), 225);
9977- // ...and a drop past either end of the bed lands on the timeline, never
9978- // outside it: `time_at` clamps.
10437+ // ...and a pointer that slid off either end of the bed names an end of
10438+ // the bed, never a pixel outside it.
997910439 assert_eq!(under(zoomed, 0.), 150);
998010440 assert_eq!(under(fit, 9999.), 300);
998110441 }
@@ -10140,50 +10600,63 @@ mod tests {
1014010600 }
1014110601 }
1014210602
10603+ /// The bed the view tests are drawn on: 200 px at 30 fps, as the drop test
10604+ /// above uses.
10605+ const TEST_BED: f32 = 200.;
10606+
10607+ /// A scale against that bed and a timeline `duration` seconds long.
10608+ fn test_view(scale: Scale, duration: f64) -> View {
10609+ View {
10610+ scale,
10611+ bed: TEST_BED,
10612+ duration,
10613+ fps: 30.,
10614+ }
10615+ }
10616+
1014310617 /// The mapping the whole panel is drawn and clicked through: a moment goes
10144- /// to a fraction of the bed and comes back the same moment, at every zoom.
10145- /// The fit is the invariant that matters most -- it must be the arithmetic
10146- /// the panel did before there was a zoom at all.
10618+ /// to a pixel on the bed and comes back the same moment, at every zoom.
1014710619 #[test]
1014810620 fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() {
1014910621 let duration = 20.;
10150- // The fit: what `start_frac`/`width_frac` used to answer, exactly.
10151- let fit = View::default();
10622+ // The fit, which is the only scale the content's own length picks: 20 s
10623+ // across a 200 px bed is 10 px to the second, and a 5 s clip is a
10624+ // quarter of the bed -- the answer the fractional view gave for it.
10625+ let fit = test_view(Scale::default(), duration).fit();
10626+ assert_eq!(fit.pps, 10.);
10627+ assert_eq!(fit.width_px(5.), TEST_BED * 0.25);
1015210628 for t in [0., 5., 12.5, 20.] {
10153- assert_eq!(
10154- fit.frac_at(t, duration),
10155- (t / duration) as f32,
10156- "fit at {t}"
10157- );
10629+ assert_eq!(fit.px_at(t), (t / duration) as f32 * TEST_BED, "fit at {t}");
1015810630 }
10159- assert_eq!(fit.width_frac(5., duration), width_frac(5., duration));
10160- for view in [
10631+ for scale in [
1016110632 fit,
10162- View {
10163- zoom: 2.,
10633+ Scale {
10634+ pps: 20.,
1016410635 start: 4.,
1016510636 },
10166- View {
10167- zoom: 8.,
10637+ Scale {
10638+ pps: 80.,
1016810639 start: 12.5,
1016910640 },
10170- View {
10171- zoom: 37.5,
10641+ Scale {
10642+ pps: 375.,
1017210643 start: 19.,
1017310644 },
1017410645 ] {
10175- let view = view.settled(duration, 30.);
10176- for frac in [0., 0.25, 0.5, 1.] {
10177- let at = view.time_at(frac, duration);
10646+ let scale = test_view(scale, duration).settled();
10647+ for x in [0., 50., 100., TEST_BED] {
10648+ let at = scale.time_at(x);
1017810649 assert!(
10179- (f64::from(view.frac_at(at, duration)) - f64::from(frac)).abs() < 1e-6,
10180- "{view:?} round trip at {frac}"
10650+ (f64::from(scale.px_at(at)) - f64::from(x)).abs() < 1e-3,
10651+ "{scale:?} round trip at {x}"
1018110652 );
1018210653 }
10183- // A stretch is as wide as the share of the visible slice it takes.
10654+ // A stretch as long as what is on the bed is as wide as the bed.
1018410655 assert!(
10185- (f64::from(view.width_frac(view.span(duration), duration)) - 1.).abs() < 1e-6,
10186- "{view:?} spans the bed"
10656+ (f64::from(scale.width_px(test_view(scale, duration).span())) - f64::from(TEST_BED))
10657+ .abs()
10658+ < 1e-3,
10659+ "{scale:?} spans the bed"
1018710660 );
1018810661 }
1018910662 }
@@ -10193,70 +10666,98 @@ mod tests {
1019310666 /// ctrl+wheel.
1019410667 #[test]
1019510668 fn a_zoom_leaves_the_anchor_where_it_was_on_screen() {
10196- let (duration, fps) = (20., 30.);
10197- let mut view = View::default();
10198- for anchor in [0.5f32, 0.25, 0.9] {
10669+ let duration = 20.;
10670+ let mut scale = test_view(Scale::default(), duration).settled();
10671+ // The same three points along the bed the fractional view held: a half,
10672+ // a quarter and nine tenths of 200 px.
10673+ for anchor in [100f32, 50., 180.] {
1019910674 // Well past the zoom-in stop: the anchor holds at the clamp too,
1020010675 // which is where it used to slide (the clamp came after the offset).
1020110676 for _ in 0..30 {
10202- let at = view.time_at(anchor, duration);
10203- let zoomed = view.zoomed(ZOOM_STEP, anchor, duration, fps);
10677+ let at = scale.time_at(anchor);
10678+ let view = test_view(scale, duration);
10679+ let zoomed = view.zoomed(ZOOM_STEP, anchor);
1020410680 // Only where the anchor is not pinned by an edge of the
1020510681 // timeline: a view already against an end cannot slide further.
10206- let pinned = zoomed.start <= 0. || zoomed.start + zoomed.span(duration) >= duration;
10682+ let span = test_view(zoomed, duration).span();
10683+ let pinned = zoomed.start <= 0. || zoomed.start + span >= duration;
1020710684 if !pinned {
1020810685 assert!(
10209- (f64::from(zoomed.frac_at(at, duration)) - f64::from(anchor)).abs() < 1e-6,
10210- "{at} moved: {view:?} -> {zoomed:?}"
10686+ (f64::from(zoomed.px_at(at)) - f64::from(anchor)).abs() < 1e-3,
10687+ "{at} moved: {scale:?} -> {zoomed:?}"
1021110688 );
1021210689 }
10213- assert!(zoomed.zoom >= view.zoom, "and it did zoom in");
10214- view = zoomed;
10690+ assert!(zoomed.pps >= scale.pps, "and it did zoom in");
10691+ scale = zoomed;
1021510692 }
1021610693 }
1021710694 }
1021810695
10219- /// Both stops: out is the whole timeline (which is where the panel starts,
10220- /// so nothing regressed for anyone who never zooms), in is a handful of
10221- /// frames -- and neither can scroll off an end.
10696+ /// Both stops, and the point of the whole mapping: neither is the content's
10697+ /// own length any more. Out is [`ZOOM_MAX_SECONDS`] across the bed, in is
10698+ /// [`ZOOM_MIN_FRAMES`] across it -- so a short import can be zoomed out of
10699+ /// and a long one zoomed into, and neither can scroll off an end.
1022210700 #[test]
10223- fn zoom_stops_at_the_whole_timeline_and_at_a_handful_of_frames() {
10701+ fn zoom_stops_at_a_bedful_of_time_and_at_a_handful_of_frames() {
1022410702 let (duration, fps) = (20., 30.);
10225- let mut view = View::default();
10703+ let mut scale = Scale::default();
1022610704 for _ in 0..200 {
10227- view = view.zoomed(1. / ZOOM_STEP, 0.5, duration, fps);
10705+ scale = test_view(scale, duration).zoomed(1. / ZOOM_STEP, 100.);
1022810706 }
10229- assert_eq!(view, View::default(), "zoomed out is the fit");
10707+ assert!(
10708+ (test_view(scale, duration).span() - ZOOM_MAX_SECONDS).abs() < 1e-6,
10709+ "widest is a bedful of hours, not the 20 s that happen to be on it"
10710+ );
1023010711 for _ in 0..200 {
10231- view = view.zoomed(ZOOM_STEP, 0.5, duration, fps);
10712+ scale = test_view(scale, duration).zoomed(ZOOM_STEP, 100.);
1023210713 }
1023310714 assert_eq!(
10234- (view.span(duration) * fps).round(),
10715+ (test_view(scale, duration).span() * fps).round(),
1023510716 ZOOM_MIN_FRAMES,
1023610717 "tightest is a handful of frames"
1023710718 );
1023810719 // Against the far end, the slice still ends at the last frame.
10239- let end = View {
10240- zoom: view.zoom,
10241- start: 1e6,
10242- }
10243- .settled(duration, fps);
10244- assert!((end.start + end.span(duration) - duration).abs() < 1e-9);
10245- assert!(
10246- View {
10247- zoom: view.zoom,
10248- start: -5.
10249- }
10250- .settled(duration, fps)
10251- .start
10252- == 0.
10720+ let end = test_view(
10721+ Scale {
10722+ start: 1e6,
10723+ ..scale
10724+ },
10725+ duration,
10726+ );
10727+ let end = (end.settled(), end.span());
10728+ assert!((end.0.start + end.1 - duration).abs() < 1e-9);
10729+ assert_eq!(
10730+ test_view(
10731+ Scale {
10732+ start: -5.,
10733+ ..scale
10734+ },
10735+ duration
10736+ )
10737+ .settled()
10738+ .start,
10739+ 0.
1025310740 );
10254- // A timeline too short to zoom into, and one with no length at all,
10255- // both stay at the fit rather than dividing by nothing.
10256- assert_eq!(View::max_zoom(0.1, fps), 1.);
10257- assert_eq!(View::default().settled(0., fps), View::default());
10258- assert_eq!(View::default().frac_at(3., 0.), 0.);
10259- assert_eq!(View::default().time_at(0.5, 0.), 0.);
10741+ // The dead zone the fractional view had: a timeline of a handful of
10742+ // frames could not be zoomed at all, because its own length was the
10743+ // floor *and* the ceiling. Both keys work on it now.
10744+ let tiny = test_view(Scale::default(), 0.1);
10745+ assert!(tiny.zoomed(ZOOM_STEP, 100.).pps > PPS_DEFAULT);
10746+ assert!(tiny.zoomed(1. / ZOOM_STEP, 100.).pps < PPS_DEFAULT);
10747+ // A timeline with no length at all divides by nothing and scrolls
10748+ // nowhere; the fit of one keeps the scale it had.
10749+ let empty = test_view(Scale::default(), 0.);
10750+ assert_eq!(empty.settled(), Scale::default());
10751+ assert_eq!(empty.fit(), Scale::default());
10752+ assert_eq!(Scale::default().px_at(0.), 0.);
10753+ // A bed that was never painted clamps nothing -- there is nothing to
10754+ // clamp against, and a zoom must survive the frame before the probe.
10755+ let unpainted = View {
10756+ bed: 0.,
10757+ ..test_view(Scale { pps: 4e6, start: 3. }, duration)
10758+ };
10759+ assert_eq!(unpainted.settled().pps, 4e6);
10760+ assert_eq!(unpainted.following(19.), unpainted.scale);
1026010761 }
1026110762
1026210763 /// What makes a zoomed timeline follow the playing head: off the bed at
@@ -10264,53 +10765,96 @@ mod tests {
1026410765 /// view that jumped every frame would be unreadable.
1026510766 #[test]
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/src/audio.rsmodified+270 -39
@@ -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;
@@ -559,17 +555,26 @@ impl AudioSession {
559555 /// -- nothing to tell the user there. Header only, and only worth calling
560556 /// once the open has already returned no audio.
561557 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
562- // Matroska: AAC is read out of one ([`Track::open`]) and everything
563- // else -- Opus, AC-3, DTS, none of which symphonia decodes at any
564- // version -- is named rather than left playing silent with no reason
565- // given. A Matroska file with no audio track at all returns `None` here
566- // 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.
567564 if crate::demux::is_matroska(path.as_ref()) {
568- return Ok(
569- crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {
570- format!("the {codec} track of this Matroska file cannot be decoded (AAC only)")
571- }),
572- );
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+ }));
573578 }
574579 let file = File::open(path.as_ref())?;
575580 let size = file.metadata()?.len();
@@ -617,10 +622,24 @@ impl AudioSession {
617622 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
618623 let path = path.as_ref();
619624 // A Matroska file has exactly one readable audio stream here -- the
620- // 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
621627 // standalone audio file rather than like an mp4, and one with no
622628 // readable track at all lists as the silent source it is.
623629 if crate::demux::is_matroska(path) {
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+ }
624643 let Ok(track) = SymTrack::open(path) else {
625644 return Ok(Vec::new());
626645 };
@@ -955,7 +974,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
955974 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
956975 // sample table can hold. The export decodes it and encodes AAC, exactly
957976 // as it does for every other source no copy reaches.
958- Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),
977+ Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")),
959978 }
960979 }
961980
@@ -978,6 +997,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error {
978997 enum Track {
979998 Aac(AacTrack),
980999 Ac3(Ac3Track),
1000+ /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an
1001+ /// mp4's sample table.
1002+ Mkv(MkvAc3Track),
9811003 Sym(SymTrack),
9821004 }
9831005
@@ -996,16 +1018,27 @@ impl Track {
9961018 /// has exactly one, so any `stream` above 0 there is a promise the file
9971019 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
9981020 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
999- // A Matroska file goes straight to symphonia, whose `mkv` reader is the
1000- // one thing here that reads its packets -- neither mp4 reader can open
1001- // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia
1002- // has no such decoder at any version) leaves the source the silent one
1003- // it always was, which `AudioSession::unsupported` puts into words,
1004- // rather than failing the import of a file whose picture is fine.
1021+ // A Matroska file goes to symphonia, whose `mkv` reader is the one thing
1022+ // here that reads its packets -- neither mp4 reader can open the file at
1023+ // all -- except for the two codecs symphonia has no decoder for at any
1024+ // version and this project does: AC-3 and E-AC-3 are handed to the Dolby
1025+ // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
1026+ // one can decode (Opus, DTS) leaves the source the silent one it always
1027+ // was, which `AudioSession::unsupported` puts into words, rather than
1028+ // failing the import of a file whose picture is fine -- and so does an
1029+ // AC-3 track that will not open, a laced block say.
10051030 if crate::demux::is_matroska(path) {
10061031 if stream > 0 {
10071032 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
10081033 }
1034+ match MkvAc3Track::open(path) {
1035+ Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1036+ Ok(None) => {}
1037+ // Named on the way past for the same reason symphonia's failure
1038+ // is, below: an AC-3 track that broke is a bug, not a codec we
1039+ // never had.
1040+ Err(e) => eprintln!("matroska audio: {}: {e}", path.display()),
1041+ }
10091042 // Logged on the way past: "silent" here covers both a codec nothing
10101043 // decodes and a track that genuinely broke, and only the second is a
10111044 // bug -- with no trace at all it reaches the user as a lane that
@@ -1046,6 +1079,7 @@ impl Track {
10461079 match self {
10471080 Self::Aac(t) => t.sample_rate,
10481081 Self::Ac3(t) => t.sample_rate,
1082+ Self::Mkv(t) => t.sample_rate,
10491083 Self::Sym(t) => t.sample_rate,
10501084 }
10511085 }
@@ -1061,6 +1095,11 @@ impl Track {
10611095 1 | 2 => Ok(t.channels),
10621096 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
10631097 },
1098+ // Downmixed by the very same decoder, out of a Matroska file.
1099+ Self::Mkv(t) => match t.channels {
1100+ 1 | 2 => Ok(t.channels),
1101+ n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1102+ },
10641103 Self::Sym(t) => match t.channels {
10651104 1 | 2 => Ok(t.channels),
10661105 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
@@ -1073,6 +1112,7 @@ impl Track {
10731112 match self {
10741113 Self::Aac(t) => t.total_samples,
10751114 Self::Ac3(t) => t.total_samples,
1115+ Self::Mkv(t) => t.total_samples,
10761116 Self::Sym(t) => t.total_samples,
10771117 }
10781118 }
@@ -1082,6 +1122,9 @@ impl Track {
10821122 match self {
10831123 Self::Aac(t) => t.priming,
10841124 Self::Ac3(t) => t.priming,
1125+ // Matroska writes no edit list and AC-3 has no encoder delay:
1126+ // block 0 is sample 0.
1127+ Self::Mkv(_) => 0,
10851128 Self::Sym(t) => t.priming,
10861129 }
10871130 }
@@ -1092,6 +1135,7 @@ impl Track {
10921135 match self {
10931136 Self::Aac(t) => t.segment(source, start_secs, end_secs),
10941137 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
1138+ Self::Mkv(t) => t.segment(source, start_secs, end_secs),
10951139 Self::Sym(t) => {
10961140 let media_target = t.media(start_secs);
10971141 Segment {
@@ -1113,7 +1157,10 @@ impl Track {
11131157 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
11141158 }
11151159 Self::Ac3(t) => {
1116- ac3_decoder(t.requested)?;
1160+ ac3_decoder("ac3", t.requested)?;
1161+ }
1162+ Self::Mkv(t) => {
1163+ ac3_decoder(t.mkv.codec, t.requested)?;
11171164 }
11181165 Self::Sym(t) => {
11191166 t.decoder()?;
@@ -1366,9 +1413,9 @@ impl Ac3Track {
13661413 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
13671414 .nfchans;
13681415 let requested = (nfchans > 1).then_some(2);
1369- let mut decoder = ac3_decoder(requested)?;
1416+ let mut decoder = ac3_decoder("ac3", requested)?;
13701417 let channels = decode_ac3(&mut decoder, &first.bytes)?
1371- .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16)
1418+ .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16)
13721419 .filter(|&c| c > 0)
13731420 .ok_or("the first AC-3 syncframe decoded to nothing")?;
13741421
@@ -1413,6 +1460,101 @@ impl Ac3Track {
14131460 }
14141461 }
14151462
1463+/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same
1464+/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of
1465+/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux
1466+/// therefore arrives on the timeline as an ordinary stereo source, exactly as
1467+/// the mp4 path's does, and the mono passthrough quirk is the same one.
1468+///
1469+/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side
1470+/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]):
1471+/// one block is one packet, one packet is one syncframe, and a seek lands on
1472+/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in
1473+/// front of it.
1474+struct MkvAc3Track {
1475+ mkv: crate::demux::MkvAudio,
1476+ sample_rate: u32,
1477+ /// What comes *out* of the decoder, measured on the first frame — 2 for
1478+ /// anything from stereo to 5.1, 1 for a mono track (see `requested`).
1479+ channels: u16,
1480+ total_samples: Option<u64>,
1481+ /// What the decoder is asked to hand out, from this track's own layout:
1482+ /// `Some(2)` for anything with more than one front channel, `None` for a
1483+ /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's.
1484+ requested: Option<u16>,
1485+}
1486+
1487+impl MkvAc3Track {
1488+ /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 —
1489+ /// that mkv is the silent source it has always been. An `Err` is a track
1490+ /// that is one and could not be read, which
1491+ /// [`AudioSession::unsupported`] quotes back to the user.
1492+ fn open(path: &Path) -> crate::Result<Option<Self>> {
1493+ let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else {
1494+ return Ok(None);
1495+ };
1496+ let first = mkv
1497+ .frame(0)?
1498+ .ok_or("the AC-3 track of this Matroska file has no blocks")?;
1499+ // Rate and layout come out of the bit stream, which is where AC-3
1500+ // states them: Matroska's `Audio` element repeats them and muxers get
1501+ // that wrong often enough that the frame is the better source.
1502+ // `nfchans` excludes the LFE in both syntaxes, which is what the
1503+ // downmix decision wants.
1504+ let (sample_rate, nfchans) = if mkv.codec == "eac3" {
1505+ // Annex E's BSI starts right after the 16-bit syncword.
1506+ let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default())
1507+ .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?;
1508+ (bsi.sample_rate, bsi.nfchans)
1509+ } else {
1510+ let sync = oxideav_ac3::syncinfo::parse(&first)
1511+ .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?;
1512+ let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default())
1513+ .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?;
1514+ (sync.sample_rate, bsi.nfchans)
1515+ };
1516+ let requested = (nfchans > 1).then_some(2);
1517+ let mut decoder = ac3_decoder(mkv.codec, requested)?;
1518+ let (pcm, samples) =
1519+ decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?;
1520+ let channels = (pcm.len() as u64 / samples.max(1)) as u16;
1521+ if channels == 0 {
1522+ return Err("the first AC-3 syncframe decoded to nothing".into());
1523+ }
1524+ // The track runs to the last block's timestamp plus that block's own
1525+ // frame -- a container that indexes nothing states no duration either,
1526+ // and every frame of a syncframe stream is the same length.
1527+ let last = mkv.secs(mkv.blocks().saturating_sub(1));
1528+ Ok(Some(Self {
1529+ total_samples: Some((last * f64::from(sample_rate)) as u64 + samples),
1530+ sample_rate,
1531+ channels,
1532+ requested,
1533+ mkv,
1534+ }))
1535+ }
1536+
1537+ /// `secs` on this source's timeline into media samples. No priming: the
1538+ /// container carries no edit list and AC-3 no encoder delay.
1539+ fn media(&self, secs: f64) -> u64 {
1540+ (secs.max(0.0) * f64::from(self.sample_rate)) as u64
1541+ }
1542+
1543+ /// One `[start, end)` window, resolved to blocks and media samples —
1544+ /// [`Ac3Track::segment`] against block timestamps instead of an `stts`.
1545+ fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1546+ let media_target = self.media(start_secs);
1547+ let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize);
1548+ Segment {
1549+ source: Some(source),
1550+ start_id: start_id as u32,
1551+ start_pos: self.media(self.mkv.secs(start_id)),
1552+ media_target,
1553+ media_end: self.media(end_secs).max(media_target),
1554+ }
1555+ }
1556+}
1557+
14161558 /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
14171559 /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
14181560 /// 5.1 track at all. Fresh per segment for the same reason every other decoder
@@ -1423,32 +1565,47 @@ impl Ac3Track {
14231565 /// mono track asks for no downmix at all and stays the mono source it is. The
14241566 /// upgrade path is `Some(2)` unconditionally once the library duplicates the
14251567 /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.
1426-fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
1568+///
1569+/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers
1570+/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct
1571+/// behind both dispatches per packet on `bsid` in any case, so what this picks
1572+/// is the capability set, not the syntax.
1573+fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
14271574 let mut registry = CodecRegistry::new();
14281575 oxideav_ac3::register_codecs(&mut registry);
1429- let mut params = CodecParameters::audio(CodecId::new("ac3"));
1576+ let mut params = CodecParameters::audio(CodecId::new(codec));
14301577 params.channels = channels;
14311578 registry
14321579 .first_decoder(&params)
14331580 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
14341581 }
14351582
1436-/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the
1437-/// decoder wants more input before it can hand a frame back, which is not an
1438-/// error. The library speaks S16 little-endian; `/32768` is the whole
1439-/// conversion, and it lands in the `[-1, 1)` every other reader here emits.
1440-fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> {
1583+/// One syncframe in, one buffer of interleaved f32 out and the frames per
1584+/// channel it holds. `Ok(None)` when the decoder wants more input before it can
1585+/// hand a frame back, which is not an error. The library speaks S16
1586+/// little-endian; `/32768` is the whole conversion, and it lands in the
1587+/// `[-1, 1)` every other reader here emits.
1588+///
1589+/// The frame count comes back beside the samples because an E-AC-3 frame is not
1590+/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2
1591+/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the
1592+/// channel count and every media position after it out.
1593+fn decode_ac3(
1594+ decoder: &mut Box<dyn Decoder>,
1595+ bytes: &[u8],
1596+) -> crate::Result<Option<(Vec<f32>, u64)>> {
14411597 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
14421598 decoder
14431599 .send_packet(&packet)
14441600 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
14451601 match decoder.receive_frame() {
1446- Ok(Frame::Audio(audio)) => Ok(Some(
1602+ Ok(Frame::Audio(audio)) => Ok(Some((
14471603 audio.data[0]
14481604 .chunks_exact(2)
14491605 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
14501606 .collect(),
1451- )),
1607+ u64::from(audio.samples),
1608+ ))),
14521609 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
14531610 Err(oxideav_core::Error::NeedMore) => Ok(None),
14541611 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
@@ -2066,6 +2223,21 @@ fn run(mut w: Worker) {
20662223 }
20672224 continue;
20682225 }
2226+ Track::Mkv(track) => {
2227+ if !run_mkv_ac3(
2228+ track,
2229+ seg,
2230+ eq.as_mut(),
2231+ speed,
2232+ channels,
2233+ &mut timeline,
2234+ &w.tx,
2235+ ) || !settle(speed, channels, &mut timeline, &w.tx)
2236+ {
2237+ return; // consumer went away
2238+ }
2239+ continue;
2240+ }
20692241 Track::Ac3(track) => {
20702242 if !run_ac3(
20712243 track,
@@ -2231,7 +2403,7 @@ fn run_ac3(
22312403 timeline: &mut u64,
22322404 tx: &SyncSender<AudioChunk>,
22332405 ) -> bool {
2234- let mut decoder = match ac3_decoder(track.requested) {
2406+ let mut decoder = match ac3_decoder("ac3", track.requested) {
22352407 Ok(decoder) => decoder,
22362408 Err(e) => {
22372409 eprintln!("audio decoder init failed: {e}");
@@ -2240,7 +2412,6 @@ fn run_ac3(
22402412 };
22412413 let mut pos = seg.start_pos;
22422414 for id in seg.start_id..=track.sample_count {
2243- let mut interleaved;
22442415 if pos >= seg.media_end {
22452416 return true; // segment done, on to the next one
22462417 }
@@ -2252,15 +2423,75 @@ fn run_ac3(
22522423 return true;
22532424 }
22542425 };
2255- match decode_ac3(&mut decoder, &sample.bytes) {
2256- Ok(Some(pcm)) => interleaved = pcm,
2426+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) {
2427+ Ok(Some(decoded)) => decoded,
22572428 Ok(None) => continue, // the decoder wants another frame first
22582429 Err(e) => {
22592430 eprintln!("audio decode error at sample {id}: {e}");
22602431 return true;
22612432 }
2433+ };
2434+ let next = pos + samples;
2435+ if !emit(
2436+ &mut interleaved,
2437+ channels,
2438+ seg,
2439+ eq.as_deref_mut(),
2440+ speed.as_mut(),
2441+ pos,
2442+ next,
2443+ timeline,
2444+ tx,
2445+ ) {
2446+ return false;
22622447 }
2263- let next = pos + (interleaved.len() / channels) as u64;
2448+ pos = next;
2449+ }
2450+ true
2451+}
2452+
2453+/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
2454+/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
2455+/// stereo downmix are the same ones; only where a packet comes from differs.
2456+/// `false` means the consumer went away.
2457+fn run_mkv_ac3(
2458+ track: &mut MkvAc3Track,
2459+ seg: &Segment,
2460+ mut eq: Option<&mut EqState>,
2461+ speed: &mut Option<Resample>,
2462+ channels: usize,
2463+ timeline: &mut u64,
2464+ tx: &SyncSender<AudioChunk>,
2465+) -> bool {
2466+ let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) {
2467+ Ok(decoder) => decoder,
2468+ Err(e) => {
2469+ eprintln!("audio decoder init failed: {e}");
2470+ return true;
2471+ }
2472+ };
2473+ let mut pos = seg.start_pos;
2474+ for id in seg.start_id as usize.. {
2475+ if pos >= seg.media_end {
2476+ return true; // segment done, on to the next one
2477+ }
2478+ let block = match track.mkv.frame(id) {
2479+ Ok(Some(bytes)) => bytes,
2480+ Ok(None) => return true, // end of the track
2481+ Err(e) => {
2482+ eprintln!("audio demux error at block {id}: {e}");
2483+ return true;
2484+ }
2485+ };
2486+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
2487+ Ok(Some(decoded)) => decoded,
2488+ Ok(None) => continue, // the decoder wants another frame first
2489+ Err(e) => {
2490+ eprintln!("audio decode error at block {id}: {e}");
2491+ return true;
2492+ }
2493+ };
2494+ let next = pos + samples;
22642495 if !emit(
22652496 &mut interleaved,
22662497 channels,
crates/engine/src/demux.rsmodified+168 -45
@@ -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,15 +329,18 @@ 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
340346 /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
@@ -375,7 +381,7 @@ impl MkvDemuxer {
375381 let mut file = File::open(path)?;
376382 let end = file.metadata()?.len();
377383 let segment = mkv_segment(&mut file, end)?;
378- let (video, _, other) = mkv_tracks(&mut file, segment)?;
384+ let (video, _, other, _) = mkv_tracks(&mut file, segment)?;
379385 let video = match video {
380386 Some(video) => video,
381387 // Named, because "no video track" is a lie about a file that has one
@@ -484,13 +490,99 @@ impl MkvDemuxer {
484490
485491 /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
486492 /// `None` for a Matroska file with no sound at all. Header only, and only worth
487-/// calling once a session has come up silent: no audio track of a Matroska file
488-/// 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.
489496 pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
490497 let mut file = File::open(path)?;
491498 let end = file.metadata()?.len();
492499 let segment = mkv_segment(&mut file, end)?;
493- 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+ }
494586 }
495587
496588 /// What the `Tracks` element says about the video track.
@@ -540,17 +632,19 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
540632 Err("no Segment element: not a Matroska file".into())
541633 }
542634
543-/// The video track of `segment`, the codec id of its first audio track, and the
544-/// codec id of a video track this cannot read -- the last two are what tell a
545-/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`])
546-/// 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.
547641 ///
548642 /// Header only: the walk stops at the first `Cluster`, so this costs a handful
549643 /// of seeks whatever the file weighs.
550644 fn mkv_tracks(
551645 file: &mut File,
552646 segment: (u64, u64),
553-) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> {
647+) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> {
554648 let (mut video, mut audio, mut other) = (None, None, None);
555649 let mut timestamp_scale = 1_000_000;
556650 let mut at = segment.0;
@@ -573,7 +667,9 @@ fn mkv_tracks(
573667 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
574668 MkvEntry::Video(track) if video.is_none() => video = Some(track),
575669 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
576- 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+ }
577673 _ => {}
578674 }
579675 }
@@ -584,7 +680,7 @@ fn mkv_tracks(
584680 }
585681 at = stop;
586682 }
587- Ok((video, audio, other))
683+ Ok((video, audio, other, timestamp_scale))
588684 }
589685
590686 /// What one `TrackEntry` turned out to be.
@@ -592,8 +688,9 @@ enum MkvEntry {
592688 Video(MkvVideo),
593689 /// A video track in a codec this does not read, by the name it gives itself.
594690 OtherVideo(String),
595- /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...).
596- 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),
597694 /// Subtitles, buttons: nobody's here.
598695 Other,
599696 }
@@ -639,7 +736,10 @@ fn mkv_track_entry(
639736 // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4
640737 // sample entry carries, so it parses with the very same reader.
641738 let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) {
642- (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+ }
643743 (1, "V_MPEGH/ISO/HEVC") => {
644744 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
645745 (Codec::Hevc, nal_length, sets, bit_depth)
@@ -652,7 +752,7 @@ fn mkv_track_entry(
652752 (Codec::H264, nal_length, sets, 8)
653753 }
654754 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
655- (2, _) => return Ok(MkvEntry::Audio(codec)),
755+ (2, _) => return Ok(MkvEntry::Audio(number, codec)),
656756 _ => return Ok(MkvEntry::Other),
657757 };
658758 Ok(MkvEntry::Video(MkvVideo {
@@ -714,25 +814,33 @@ fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
714814 /// §2.3.3): four fixed bytes, then the sequence header OBU in the same
715815 /// low-overhead format the blocks are in, so it needs no reframing.
716816 ///
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+///
717822 /// An empty record is not an error -- an encoder that repeats its sequence
718-/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for
719-/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage`
720-/// read-back are 8-bit, and the upgrade path is a P010 pool.
721-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)> {
722826 if rec.is_empty() {
723- return Ok(Vec::new());
827+ return Ok((Vec::new(), 8));
724828 }
725829 let &flags = rec
726830 .get(2)
727831 .ok_or("av1C record shorter than its fixed header")?;
728- if flags & 0x40 != 0 {
729- return Err(format!(
730- "{}-bit AV1 is not supported yet — this file is not 8-bit",
731- if flags & 0x20 != 0 { 12 } else { 10 }
732- )
733- .into());
734- }
735- 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))
736844 }
737845
738846 /// Every block of track `number`, in storage order, with the presentation span
@@ -793,11 +901,17 @@ fn mkv_blocks(
793901 if block.number != number {
794902 continue;
795903 }
796- // Lacing packs several frames into one block. Audio muxers use it,
797- // video ones do not, and guessing at frame boundaries inside a laced
798- // 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.
799913 if block.flags & 0x06 != 0 {
800- return Err("laced video blocks are not supported".into());
914+ return Err("laced Matroska blocks are not supported".into());
801915 }
802916 let ts = cluster_ts + i64::from(block.rel);
803917 span = Some(match span {
@@ -808,6 +922,7 @@ fn mkv_blocks(
808922 at: block.at,
809923 len: block.len,
810924 key,
925+ ts,
811926 });
812927 }
813928 }
@@ -1517,8 +1632,9 @@ mod tests {
15171632 }
15181633
15191634 /// The `av1C` record: four fixed bytes and then the sequence header OBU,
1520- /// which is handed to the decoder as it stands. 10-bit is refused by name
1521- /// 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.
15221638 #[test]
15231639 fn reads_the_sequence_header_out_of_an_av1c_record() {
15241640 // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
@@ -1527,14 +1643,16 @@ mod tests {
15271643 rec.extend_from_slice(&[
15281644 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
15291645 ]);
1530- let config = parse_av1c(&rec).unwrap();
1646+ let (config, depth) = parse_av1c(&rec).unwrap();
15311647 assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
15321648 assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
1649+ assert_eq!(depth, 8);
15331650
15341651 let mut ten = rec.clone();
15351652 ten[2] |= 0x40; // high_bitdepth
1536- let refused = parse_av1c(&ten).unwrap_err().to_string();
1537- 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");
15381656 let mut twelve = ten.clone();
15391657 twelve[2] |= 0x20; // twelve_bit
15401658 assert!(
@@ -1543,10 +1661,15 @@ mod tests {
15431661 .to_string()
15441662 .contains("12-bit")
15451663 );
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);
15461669
15471670 // An encoder that repeats its sequence header in-band writes no record
15481671 // at all, which is not an error; a truncated one is.
1549- assert!(parse_av1c(&[]).unwrap().is_empty());
1672+ assert!(parse_av1c(&[]).unwrap().0.is_empty());
15501673 assert!(parse_av1c(&[0x81, 0x05]).is_err());
15511674 }
15521675
crates/engine/src/playback.rsmodified+19 -0
@@ -1788,6 +1788,25 @@ impl PlaybackSession {
17881788 }
17891789 }
17901790
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+
17911810 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
17921811 /// one knob, because muting and turning it down are the same thing to the
17931812 /// device, and *which* the user meant is a question only the UI can answer
crates/engine/tests/audio_decode.rsmodified+97 -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 --
crates/engine/tests/av1.rsmodified+48 -0
@@ -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.
@@ -191,6 +208,37 @@ fn the_plugin_decodes_every_av1_frame() {
191208 );
192209 }
193210
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+
194242 /// A seek into the second GOP hands back that very frame, not the keyframe it
195243 /// had to restart from: the demuxer's sync index and the plugin's skip count
196244 /// have to agree, and Matroska is where both are this crate's own doing.
scripts/gen_fixtures.shmodified+32 -4
@@ -103,16 +103,26 @@ 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
116126 # H.264 in Matroska: the same stream the mp4 fixtures carry, in the container
117127 # that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing
118128 # installed, `-g 30` for the second keyframe the sync index is checked against,
@@ -167,6 +177,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
167177 -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \
168178 -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \
169179 -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
170198 # Sync fixture: one flash and one beep, at the same instant. Black picture with
171199 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
172200 # stretch — so a test can find each of them and say how far apart they came out.