🔀 merge(B3): the snap says where the edge lands, the fit says what the box is
Browse files at this commit6 changed files +1298 -262
- crates/app/src/keymap.rs +14 -3
- crates/app/src/main.rs +774 -197
- crates/engine/src/audio.rs +270 -39
- crates/engine/src/demux.rs +122 -21
- crates/engine/tests/audio_decode.rs +97 -0
- scripts/gen_fixtures.sh +21 -2
crates/app/src/keymap.rsmodified+14 -3
| @@ -78,13 +78,14 @@ pub enum ActionId { | |||
| 78 | Speed, | 78 | Speed, |
| 79 | Silence, | 79 | Silence, |
| 80 | Mix, | 80 | Mix, |
| 81 | + ToggleSnap, | ||
| 81 | CancelExport, | 82 | CancelExport, |
| 82 | } | 83 | } |
| 83 | 84 | ||
| 84 | impl ActionId { | 85 | impl ActionId { |
| 85 | /// Display order everywhere -- the editor lists them in it and | 86 | /// Display order everywhere -- the editor lists them in it and |
| 86 | /// [`Keymap::defaults`] binds them in it. | 87 | /// [`Keymap::defaults`] binds them in it. |
| 87 | - pub const ALL: [ActionId; 39] = [ | 88 | + pub const ALL: [ActionId; 40] = [ |
| 88 | ActionId::Play, | 89 | ActionId::Play, |
| 89 | ActionId::StepBack, | 90 | ActionId::StepBack, |
| 90 | ActionId::StepForward, | 91 | ActionId::StepForward, |
| @@ -123,6 +124,7 @@ impl ActionId { | |||
| 123 | ActionId::Speed, | 124 | ActionId::Speed, |
| 124 | ActionId::Silence, | 125 | ActionId::Silence, |
| 125 | ActionId::Mix, | 126 | ActionId::Mix, |
| 127 | + ActionId::ToggleSnap, | ||
| 126 | ActionId::CancelExport, | 128 | ActionId::CancelExport, |
| 127 | ]; | 129 | ]; |
| 128 | 130 | ||
| @@ -167,6 +169,7 @@ impl ActionId { | |||
| 167 | ActionId::Speed => "Speed (tape)…", | 169 | ActionId::Speed => "Speed (tape)…", |
| 168 | ActionId::Silence => "Silences: cut or speed up…", | 170 | ActionId::Silence => "Silences: cut or speed up…", |
| 169 | ActionId::Mix => "Mix: track volumes and the limiter…", | 171 | ActionId::Mix => "Mix: track volumes and the limiter…", |
| 172 | + ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)", | ||
| 170 | ActionId::CancelExport => "Cancel export", | 173 | ActionId::CancelExport => "Cancel export", |
| 171 | } | 174 | } |
| 172 | } | 175 | } |
| @@ -213,6 +216,7 @@ impl ActionId { | |||
| 213 | ActionId::Speed => "speed", | 216 | ActionId::Speed => "speed", |
| 214 | ActionId::Silence => "silence", | 217 | ActionId::Silence => "silence", |
| 215 | ActionId::Mix => "mix", | 218 | ActionId::Mix => "mix", |
| 219 | + ActionId::ToggleSnap => "toggle-snap", | ||
| 216 | ActionId::CancelExport => "cancel-export", | 220 | ActionId::CancelExport => "cancel-export", |
| 217 | } | 221 | } |
| 218 | } | 222 | } |
| @@ -265,6 +269,9 @@ impl ActionId { | |||
| 265 | | ActionId::AddVideoLane | 269 | | ActionId::AddVideoLane |
| 266 | | ActionId::AddAudioLane | 270 | | ActionId::AddAudioLane |
| 267 | | ActionId::RemoveVideoLane | 271 | | ActionId::RemoveVideoLane |
| 272 | + // Not a view setting despite being a pointer aid: it decides where | ||
| 273 | + // a drag actually lands, which is an edit and not a magnification. | ||
| 274 | + | ActionId::ToggleSnap | ||
| 268 | | ActionId::RemoveAudioLane => Category::Editing, | 275 | | ActionId::RemoveAudioLane => Category::Editing, |
| 269 | ActionId::ToggleMute | 276 | ActionId::ToggleMute |
| 270 | | ActionId::VolumeUp | 277 | | ActionId::VolumeUp |
| @@ -645,6 +652,9 @@ impl Keymap { | |||
| 645 | // machine's volume and not the project's -- two things one key | 652 | // machine's volume and not the project's -- two things one key |
| 646 | // must not mean. | 653 | // must not mean. |
| 647 | b(ActionId::Mix, "f", false), | 654 | b(ActionId::Mix, "f", false), |
| 655 | + // The snap takes "n", which is what every other editor toggles | ||
| 656 | + // it with: free here, and nowhere near the two keys that delete. | ||
| 657 | + b(ActionId::ToggleSnap, "n", false), | ||
| 648 | b(ActionId::CancelExport, "escape", false), | 658 | b(ActionId::CancelExport, "escape", false), |
| 649 | ], | 659 | ], |
| 650 | } | 660 | } |
| @@ -907,7 +917,7 @@ mod tests { | |||
| 907 | #[test] | 917 | #[test] |
| 908 | fn every_default_stroke_reaches_its_action() { | 918 | fn every_default_stroke_reaches_its_action() { |
| 909 | let k = Keymap::defaults(); | 919 | let k = Keymap::defaults(); |
| 910 | - assert_eq!(k.entries().len(), 41); | 920 | + assert_eq!(k.entries().len(), 42); |
| 911 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); | 921 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); |
| 912 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two | 922 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two |
| 913 | // ends of the timeline. | 923 | // ends of the timeline. |
| @@ -1141,7 +1151,8 @@ mod tests { | |||
| 1141 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); | 1151 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); |
| 1142 | // The label is the editor's column, and never the file's word for it. | 1152 | // The label is the editor's column, and never the file's word for it. |
| 1143 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); | 1153 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); |
| 1144 | - assert_eq!(ActionId::ALL.len(), 39); | 1154 | + assert_eq!(ActionId::ALL.len(), 40); |
| 1155 | + assert_eq!(k.display(ActionId::ToggleSnap), "n"); | ||
| 1145 | assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); | 1156 | assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); |
| 1146 | } | 1157 | } |
| 1147 | 1158 | ||
crates/app/src/main.rsmodified+774 -197
| @@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed}; | |||
| 19 | use engine::scale::FitPolicy; | 19 | use engine::scale::FitPolicy; |
| 20 | use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; | 20 | use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; |
| 21 | use gpui::{ | 21 | use gpui::{ |
| 22 | - AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, | 22 | + AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent, |
| 23 | - KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, | 23 | + FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, |
| 24 | - Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, | 24 | + PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, |
| 25 | - TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, | 25 | + Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, |
| 26 | - relative, rgb, rgba, size, | 26 | + point, prelude::*, px, relative, rgb, rgba, size, |
| 27 | }; | 27 | }; |
| 28 | 28 | ||
| 29 | /// Editor chrome: three grays and one accent, all darker than the picture so the | 29 | /// Editor chrome: three grays and one accent, all darker than the picture so the |
| @@ -420,6 +420,47 @@ const MENU_ITEMS: [ActionId; 14] = [ | |||
| 420 | ActionId::ToggleMute, | 420 | ActionId::ToggleMute, |
| 421 | ]; | 421 | ]; |
| 422 | 422 | ||
| 423 | +/// One row of the actions card, in the order it lists them: a heading, then | ||
| 424 | +/// every action the registry files under it, then the strokes the modal cards | ||
| 425 | +/// answer themselves. | ||
| 426 | +/// | ||
| 427 | +/// A list rather than a loop inside the render, so the card and | ||
| 428 | +/// `every_action_is_on_the_actions_card` read the *same* order: an action that | ||
| 429 | +/// reaches no row fails a test instead of quietly becoming pointer-unreachable. | ||
| 430 | +enum KeyRow { | ||
| 431 | + Head(keymap::Category), | ||
| 432 | + /// Click its label to do it, click its stroke to change that stroke. | ||
| 433 | + Act(ActionId), | ||
| 434 | + /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may | ||
| 435 | + /// unbind the way out of a card. | ||
| 436 | + Fixed(usize), | ||
| 437 | +} | ||
| 438 | + | ||
| 439 | +/// Every action, under its heading, and the card-local strokes beside them. | ||
| 440 | +/// Generated from the registry -- [`ActionId::ALL`] in its own order, under | ||
| 441 | +/// [`keymap::Category::ALL`] -- so an action added there is on the card the | ||
| 442 | +/// moment it exists and there is no second list here to forget. | ||
| 443 | +fn keys_rows() -> Vec<KeyRow> { | ||
| 444 | + let mut rows = Vec::new(); | ||
| 445 | + for category in keymap::Category::ALL { | ||
| 446 | + rows.push(KeyRow::Head(category)); | ||
| 447 | + rows.extend( | ||
| 448 | + ActionId::ALL | ||
| 449 | + .into_iter() | ||
| 450 | + .filter(|a| a.category() == category) | ||
| 451 | + .map(KeyRow::Act), | ||
| 452 | + ); | ||
| 453 | + rows.extend( | ||
| 454 | + keymap::FIXED | ||
| 455 | + .iter() | ||
| 456 | + .enumerate() | ||
| 457 | + .filter(|(_, f)| f.category == category) | ||
| 458 | + .map(|(i, _)| KeyRow::Fixed(i)), | ||
| 459 | + ); | ||
| 460 | + } | ||
| 461 | + rows | ||
| 462 | +} | ||
| 463 | + | ||
| 423 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. | 464 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. |
| 424 | /// A short list of the sizes people name; the media's own is cycled in beside | 465 | /// A short list of the sizes people name; the media's own is cycled in beside |
| 425 | /// them, which is what makes the trip round come back to where it started. | 466 | /// them, which is what makes the trip round come back to where it started. |
| @@ -763,6 +804,16 @@ struct Player { | |||
| 763 | /// the value being dragged, and stale between drags, which costs nothing -- | 804 | /// the value being dragged, and stale between drags, which costs nothing -- |
| 764 | /// no drag starts without a press on the box it moves. | 805 | /// no drag starts without a press on the box it moves. |
| 765 | grab: u32, | 806 | grab: u32, |
| 807 | + /// Whether a drag or a trim is pulled onto the edges near it. On by | ||
| 808 | + /// default, because clips meeting exactly is what a timeline is for, and off | ||
| 809 | + /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement | ||
| 810 | + /// no magnet may take away. | ||
| 811 | + snap: bool, | ||
| 812 | + /// The frame the live gesture is about to land on, or `None` while it is | ||
| 813 | + /// over open bed: the line every lane draws so the snap is seen before it | ||
| 814 | + /// happens rather than discovered after the release. Stale between gestures, | ||
| 815 | + /// which costs nothing -- it is drawn only while one is live. | ||
| 816 | + snap_cue: Option<u32>, | ||
| 766 | last_scrub: Instant, | 817 | last_scrub: Instant, |
| 767 | last_target: u32, | 818 | last_target: u32, |
| 768 | /// The running export. While it owns the UI the editor is read-only. | 819 | /// The running export. While it owns the UI the editor is read-only. |
| @@ -1106,12 +1157,51 @@ impl Player { | |||
| 1106 | ActionId::Speed => self.open_speed(cx), | 1157 | ActionId::Speed => self.open_speed(cx), |
| 1107 | ActionId::Silence => self.open_silence(cx), | 1158 | ActionId::Silence => self.open_silence(cx), |
| 1108 | ActionId::Mix => self.open_mix(None, cx), | 1159 | ActionId::Mix => self.open_mix(None, cx), |
| 1160 | + ActionId::ToggleSnap => self.toggle_snap(cx), | ||
| 1109 | // Nothing to cancel while nothing is exporting; the export guard in | 1161 | // Nothing to cancel while nothing is exporting; the export guard in |
| 1110 | // the key handler is what answers this one while there is. | 1162 | // the key handler is what answers this one while there is. |
| 1111 | ActionId::CancelExport => {} | 1163 | ActionId::CancelExport => {} |
| 1112 | } | 1164 | } |
| 1113 | } | 1165 | } |
| 1114 | 1166 | ||
| 1167 | + /// The magnet off and on again, in words: a snap that stops working | ||
| 1168 | + /// silently reads as a bug, and one that starts working silently reads as | ||
| 1169 | + /// one too. The line goes with it -- nothing is being promised any more. | ||
| 1170 | + fn toggle_snap(&mut self, cx: &mut Context<Self>) { | ||
| 1171 | + self.snap = !self.snap; | ||
| 1172 | + self.snap_cue = None; | ||
| 1173 | + self.notice = Some(match self.snap { | ||
| 1174 | + true => "SNAP ON — drags land on clip edges, the playhead and the start".into(), | ||
| 1175 | + false => "SNAP OFF — drags land exactly where the hand leaves them".into(), | ||
| 1176 | + }); | ||
| 1177 | + cx.notify(); | ||
| 1178 | + } | ||
| 1179 | + | ||
| 1180 | + /// Whether the editor can be asked for `action` right now, and why not when | ||
| 1181 | + /// it cannot. `on` is the clip the question is about -- the one a clip menu | ||
| 1182 | + /// was opened on -- and `None` asks about the marked clip instead, which is | ||
| 1183 | + /// what a menu that hangs over no clip in particular means by "this one". | ||
| 1184 | + /// | ||
| 1185 | + /// The player's half of [`enable`]: it reads the state, the table decides. | ||
| 1186 | + fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable { | ||
| 1187 | + let Some(session) = &self.session else { | ||
| 1188 | + return enable(action, Ctx::default()); | ||
| 1189 | + }; | ||
| 1190 | + let clip = on | ||
| 1191 | + .or(self.selected) | ||
| 1192 | + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane))); | ||
| 1193 | + enable( | ||
| 1194 | + action, | ||
| 1195 | + Ctx { | ||
| 1196 | + clip, | ||
| 1197 | + playhead: frame_at(session.now(), self.fps), | ||
| 1198 | + timeline: true, | ||
| 1199 | + clipboard: self.clipboard.is_some(), | ||
| 1200 | + exporting: self.exporting().is_some(), | ||
| 1201 | + }, | ||
| 1202 | + ) | ||
| 1203 | + } | ||
| 1204 | + | ||
| 1115 | /// The one place a clip becomes *the* selected one: a click, a right-click | 1205 | /// The one place a clip becomes *the* selected one: a click, a right-click |
| 1116 | /// that opens the menu, and every selection key go through here, so what a | 1206 | /// that opens the menu, and every selection key go through here, so what a |
| 1117 | /// keyboard marks and what a pointer marks are the same state marked the | 1207 | /// keyboard marks and what a pointer marks are the same state marked the |
| @@ -2392,8 +2482,8 @@ impl Player { | |||
| 2392 | if self.exporting().is_some() { | 2482 | if self.exporting().is_some() { |
| 2393 | return; | 2483 | return; |
| 2394 | } | 2484 | } |
| 2395 | - let (Some(start), Some(was)) = ( | 2485 | + let (Some((start, _)), Some(was)) = ( |
| 2396 | - self.drop_frame(from, idx, to, x), | 2486 | + self.drop_frame(from, idx, x), |
| 2397 | self.session | 2487 | self.session |
| 2398 | .as_ref() | 2488 | .as_ref() |
| 2399 | .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), | 2489 | .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), |
| @@ -2455,26 +2545,70 @@ impl Player { | |||
| 2455 | /// the scroll clamp pins the bed's right edge to the duration, and the | 2545 | /// the scroll clamp pins the bed's right edge to the duration, and the |
| 2456 | /// pointer has no pixel past it. The upgrade is to let the scroll clamp | 2546 | /// pointer has no pixel past it. The upgrade is to let the scroll clamp |
| 2457 | /// leave a screen of empty bed after the end, the way every NLE does. | 2547 | /// leave a screen of empty bed after the end, the way every NLE does. |
| 2458 | - fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> { | 2548 | + fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> { |
| 2459 | - let session = self.session.as_ref()?; | 2549 | + let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?; |
| 2460 | - let clip = session.lane_clips(from).get(idx).copied()?; | ||
| 2461 | let raw = self.frame_under(x).saturating_sub(self.grab); | 2550 | let raw = self.frame_under(x).saturating_sub(self.grab); |
| 2462 | - // The edges worth landing on: both ends of every clip already on the | 2551 | + let marks = self.snap_targets(Some((from, idx))); |
| 2463 | - // lane it is being let go over, the playhead, and the head of the | 2552 | + Some(self.snap_to(raw, clip.frames(), &marks)) |
| 2464 | - // timeline. Never the group's own boxes -- a clip does not snap to | 2553 | + } |
| 2465 | - // where it already is. | 2554 | + |
| 2466 | - let mut marks: Vec<u32> = session | 2555 | + /// Which index the clip in the hand is at *now*: [`live_idx`] against the |
| 2467 | - .lane_clips(to) | 2556 | + /// lane the drag named, since a stroke during the gesture moves the indices |
| 2468 | - .iter() | 2557 | + /// gpui froze into the payload. Both halves of a drag ask it -- the line |
| 2469 | - .enumerate() | 2558 | + /// drawn in flight and the drop that commits -- so the promise and the |
| 2470 | - .filter(|&(i, c)| { | 2559 | + /// landing are made about one clip. |
| 2471 | - (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link) | 2560 | + fn dragged(&self, drag: &ClipDrag) -> Option<usize> { |
| 2472 | - }) | 2561 | + let session = self.session.as_ref()?; |
| 2473 | - .flat_map(|(_, c)| [c.start, c.end()]) | 2562 | + live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip) |
| 2474 | - .collect(); | 2563 | + } |
| 2475 | - marks.push(frame_at(session.now(), self.fps)); | 2564 | + |
| 2476 | - marks.push(0); | 2565 | + /// The line while the clip is still in the hand: the very answer |
| 2477 | - Some(snapped(raw, clip.frames(), self.snap_frames(), &marks)) | 2566 | + /// [`Player::drop_frame`] will commit, worked out on every move of the drag, |
| 2567 | + /// so what the eye was promised is where the release puts it. A pointer that | ||
| 2568 | + /// has wandered off the bed promises nothing. | ||
| 2569 | + fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) { | ||
| 2570 | + let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue); | ||
| 2571 | + self.set_cue(cue, x, cx); | ||
| 2572 | + } | ||
| 2573 | + | ||
| 2574 | + /// The same line for a library row on its way to a lane: it goes down at | ||
| 2575 | + /// the frame it is let go on ([`Player::insert_source`]), so that frame is | ||
| 2576 | + /// what snaps and what is drawn. No length to snap by -- the file's own is | ||
| 2577 | + /// not known until the engine has placed it -- so only its head lands. | ||
| 2578 | + fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) { | ||
| 2579 | + let marks = self.snap_targets(None); | ||
| 2580 | + let cue = self.snap_to(self.frame_under(x), 0, &marks).1; | ||
| 2581 | + self.set_cue(cue, x, cx); | ||
| 2582 | + } | ||
| 2583 | + | ||
| 2584 | + /// Sets the line, or takes it away, and repaints only when it moved: a | ||
| 2585 | + /// pointer dragged off the bed (up to the library, say) is not promising a | ||
| 2586 | + /// landing any more. | ||
| 2587 | + fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) { | ||
| 2588 | + let bed = self.ruler.get(); | ||
| 2589 | + let cue = cue.filter(|_| x >= bed.left() && x <= bed.right()); | ||
| 2590 | + if cue != self.snap_cue { | ||
| 2591 | + self.snap_cue = cue; | ||
| 2592 | + cx.notify(); | ||
| 2593 | + } | ||
| 2594 | + } | ||
| 2595 | + | ||
| 2596 | + /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its | ||
| 2597 | + /// lanes, so a clip meets a take one track over as readily as one beside it. | ||
| 2598 | + fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> { | ||
| 2599 | + let Some(session) = &self.session else { | ||
| 2600 | + return Vec::new(); | ||
| 2601 | + }; | ||
| 2602 | + let lanes = session.lanes(); | ||
| 2603 | + let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect(); | ||
| 2604 | + let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx))); | ||
| 2605 | + snap_marks(&clips, skip, frame_at(session.now(), self.fps)) | ||
| 2606 | + } | ||
| 2607 | + | ||
| 2608 | + /// Where a gesture at `raw` lands and the mark that pulled it there, with | ||
| 2609 | + /// the switch honoured: snapping off, nothing moves and no line is drawn. | ||
| 2610 | + fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) { | ||
| 2611 | + snap_cue(self.snap, raw, len, self.snap_frames(), marks) | ||
| 2478 | } | 2612 | } |
| 2479 | 2613 | ||
| 2480 | /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's | 2614 | /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's |
| @@ -2538,14 +2672,25 @@ impl Player { | |||
| 2538 | /// against the same duration the boxes are drawn to, so the edge tracks the | 2672 | /// against the same duration the boxes are drawn to, so the edge tracks the |
| 2539 | /// pointer exactly. | 2673 | /// pointer exactly. |
| 2540 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { | 2674 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { |
| 2541 | - let at = self.frame_under(x); | 2675 | + let Some(trim) = self.trim else { |
| 2542 | - let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { | ||
| 2543 | return; | 2676 | return; |
| 2544 | }; | 2677 | }; |
| 2545 | - let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { | 2678 | + // The edge is pulled onto the same marks a whole clip is, by itself: |
| 2679 | + // there is no other end travelling with it, so it snaps at length zero. | ||
| 2680 | + let marks = self.snap_targets(Some((trim.lane, trim.idx))); | ||
| 2681 | + let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks); | ||
| 2682 | + let Some((lo, hi)) = self | ||
| 2683 | + .session | ||
| 2684 | + .as_ref() | ||
| 2685 | + .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge)) | ||
| 2686 | + else { | ||
| 2546 | return; | 2687 | return; |
| 2547 | }; | 2688 | }; |
| 2548 | - trim.to = at.clamp(lo, hi); | 2689 | + let to = at.clamp(lo, hi); |
| 2690 | + // The line only stands where the edge actually stopped: a mark the | ||
| 2691 | + // engine's own room clamped away was never reached. | ||
| 2692 | + self.set_cue(cue.filter(|_| to == at), x, cx); | ||
| 2693 | + self.trim = Some(Trim { to, ..trim }); | ||
| 2549 | cx.notify(); | 2694 | cx.notify(); |
| 2550 | } | 2695 | } |
| 2551 | 2696 | ||
| @@ -3803,6 +3948,26 @@ impl Render for Player { | |||
| 3803 | } | 3948 | } |
| 3804 | } | 3949 | } |
| 3805 | })) | 3950 | })) |
| 3951 | + // A drop event carries no path of its own -- gpui only tells the | ||
| 3952 | + // target that something landed -- so the line that promises where | ||
| 3953 | + // it will land is fed by the drag's own moves, which do carry the | ||
| 3954 | + // pointer (gpui div.rs:282). On the root, because a drag crosses | ||
| 3955 | + // the window: it starts on a clip or on a library row and ends over | ||
| 3956 | + // a lane, and only an ancestor of both hears all of it. | ||
| 3957 | + .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| { | ||
| 3958 | + // The clip the payload named, wherever an edit mid-drag has | ||
| 3959 | + // since put it ([`Player::dragged`]): the line has to promise a | ||
| 3960 | + // landing for the take actually in the hand. | ||
| 3961 | + let drag = *event.drag(cx); | ||
| 3962 | + if let Some(idx) = this.dragged(&drag) { | ||
| 3963 | + this.preview_drop(drag.lane, idx, event.event.position.x, cx); | ||
| 3964 | + } | ||
| 3965 | + })) | ||
| 3966 | + .on_drag_move( | ||
| 3967 | + cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| { | ||
| 3968 | + this.preview_place(event.event.position.x, cx); | ||
| 3969 | + }), | ||
| 3970 | + ) | ||
| 3806 | // Scrubbing is tracked on the root because the pointer leaves the | 3971 | // Scrubbing is tracked on the root because the pointer leaves the |
| 3807 | // 6 px ruler on the first drag and its own listeners then stop | 3972 | // 6 px ruler on the first drag and its own listeners then stop |
| 3808 | // firing; the root's hitbox is the whole window. | 3973 | // firing; the root's hitbox is the whole window. |
| @@ -4568,6 +4733,25 @@ impl Player { | |||
| 4568 | live, | 4733 | live, |
| 4569 | cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), | 4734 | cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), |
| 4570 | )) | 4735 | )) |
| 4736 | + // The magnet, beside the zoom for the zoom's own reason: it | ||
| 4737 | + // changes nothing on the timeline, it changes how the hand | ||
| 4738 | + // meets it. The label is the state, as the volume's is -- | ||
| 4739 | + // a toggle that looks the same either way says nothing. | ||
| 4740 | + .child(control( | ||
| 4741 | + "snap", | ||
| 4742 | + None, | ||
| 4743 | + if self.snap { "Snap" } else { "No snap" }, | ||
| 4744 | + format!( | ||
| 4745 | + "{} — {}", | ||
| 4746 | + key(ActionId::ToggleSnap), | ||
| 4747 | + match self.snap { | ||
| 4748 | + true => "drags and trims land on clip edges, the playhead and the start", | ||
| 4749 | + false => "drags and trims land exactly where the hand leaves them", | ||
| 4750 | + } | ||
| 4751 | + ), | ||
| 4752 | + live, | ||
| 4753 | + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)), | ||
| 4754 | + )) | ||
| 4571 | // Import is not here: it belongs to the media list it adds | 4755 | // Import is not here: it belongs to the media list it adds |
| 4572 | // to, and two doors into one action is a question about | 4756 | // to, and two doors into one action is a question about |
| 4573 | // which one is the real one. | 4757 | // which one is the real one. |
| @@ -4618,8 +4802,10 @@ impl Player { | |||
| 4618 | .child(control( | 4802 | .child(control( |
| 4619 | "keys", | 4803 | "keys", |
| 4620 | None, | 4804 | None, |
| 4621 | - "Keys", | 4805 | + "Actions", |
| 4622 | - "show and change the keybindings".to_string(), | 4806 | + // The pointer's way to every action there is, including |
| 4807 | + // the ones no button here has room for. | ||
| 4808 | + "do any action, or change the key that does it".to_string(), | ||
| 4623 | !exporting, | 4809 | !exporting, |
| 4624 | cx.listener(|this, _: &ClickEvent, _, cx| { | 4810 | cx.listener(|this, _: &ClickEvent, _, cx| { |
| 4625 | this.keys_open = !this.keys_open; | 4811 | this.keys_open = !this.keys_open; |
| @@ -4839,23 +5025,30 @@ impl Player { | |||
| 4839 | ctrl: false, | 5025 | ctrl: false, |
| 4840 | } | 5026 | } |
| 4841 | .pretty(); | 5027 | .pretty(); |
| 4842 | - // Every stroke that works, under its heading, and both halves of the | 5028 | + // Every action there is, under its heading, and the strokes the modal |
| 4843 | - // list come from the registry: one row per action -- an action with two | 5029 | + // cards answer to beside them -- `keys_rows` is the whole of the order |
| 4844 | - // strokes reads as one line ("x or delete") and a rebind replaces that | 5030 | + // and every word in it comes off the registry. |
| 4845 | - // whole set -- then the strokes the modal cards answer to, which are | 5031 | + // |
| 4846 | - // shown but not offered, because nothing may unbind the way out. | 5032 | + // A row is two targets, not one: its label *does* the action, which is |
| 5033 | + // the pointer's way to the ones no button carries, and its stroke | ||
| 5034 | + // changes that stroke. An action with two strokes reads as one line | ||
| 5035 | + // ("x or delete") and a rebind replaces that whole set. | ||
| 4847 | let mut rows: Vec<AnyElement> = Vec::new(); | 5036 | let mut rows: Vec<AnyElement> = Vec::new(); |
| 4848 | - for category in keymap::Category::ALL { | 5037 | + let row = || { |
| 4849 | - let actions = ActionId::ALL | ||
| 4850 | - .into_iter() | ||
| 4851 | - .enumerate() | ||
| 4852 | - .filter(|(_, a)| a.category() == category); | ||
| 4853 | - let fixed = keymap::FIXED.iter().filter(|f| f.category == category); | ||
| 4854 | - let mut headed = false; | ||
| 4855 | - let mut head = |rows: &mut Vec<AnyElement>| { | ||
| 4856 | - if !std::mem::replace(&mut headed, true) { | ||
| 4857 | - rows.push( | ||
| 4858 | div() | 5038 | div() |
| 5039 | + .flex() | ||
| 5040 | + // The floor, not the height: a row that needed two lines | ||
| 5041 | + // would otherwise paint over the one under it. | ||
| 5042 | + .min_h(px(KEYS_ROW_H)) | ||
| 5043 | + .items_center() | ||
| 5044 | + .justify_between() | ||
| 5045 | + .gap(px(12.)) | ||
| 5046 | + .px(px(6.)) | ||
| 5047 | + .rounded(px(3.)) | ||
| 5048 | + }; | ||
| 5049 | + for (i, key_row) in keys_rows().into_iter().enumerate() { | ||
| 5050 | + rows.push(match key_row { | ||
| 5051 | + KeyRow::Head(category) => div() | ||
| 4859 | .flex_none() | 5052 | .flex_none() |
| 4860 | .px(px(6.)) | 5053 | .px(px(6.)) |
| 4861 | .pt(px(4.)) | 5054 | .pt(px(4.)) |
| @@ -4863,59 +5056,84 @@ impl Player { | |||
| 4863 | .text_color(rgb(INK_DIM)) | 5056 | .text_color(rgb(INK_DIM)) |
| 4864 | .child(category.label()) | 5057 | .child(category.label()) |
| 4865 | .into_any_element(), | 5058 | .into_any_element(), |
| 4866 | - ); | 5059 | + KeyRow::Act(action) => { |
| 4867 | - } | ||
| 4868 | - }; | ||
| 4869 | - for (i, action) in actions { | ||
| 4870 | - head(&mut rows); | ||
| 4871 | let capturing = self.rebinding == Some(action); | 5060 | let capturing = self.rebinding == Some(action); |
| 5061 | + // Why the label half will not answer, if it will not: the | ||
| 5062 | + // registry's one answer, the same the clip menu dims by. | ||
| 5063 | + let refusal = self.enable(action, None); | ||
| 4872 | let out = out.clone(); | 5064 | let out = out.clone(); |
| 4873 | - rows.push( | 5065 | + row() |
| 5066 | + .when(capturing, |d| d.bg(rgb(SELECTED))) | ||
| 5067 | + .child( | ||
| 5068 | + div() | ||
| 5069 | + .id(("do", i)) | ||
| 5070 | + .flex_1() | ||
| 5071 | + .min_w(px(0.)) | ||
| 5072 | + .flex() | ||
| 5073 | + .min_h(px(KEYS_ROW_H)) | ||
| 5074 | + .items_center() | ||
| 5075 | + .child(action.label()) | ||
| 5076 | + // The reason rides on the label rather than in | ||
| 5077 | + // the stroke column, which the rebind half | ||
| 5078 | + // needs whatever the editor's state is: an | ||
| 5079 | + // action nobody can ask for right now is still | ||
| 5080 | + // one whose key may be changed. | ||
| 5081 | + .when_some(refusal.why(), |d, why| { | ||
| 5082 | + let why: SharedString = why.into(); | ||
| 5083 | + d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into()) | ||
| 5084 | + }) | ||
| 5085 | + .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) | ||
| 5086 | + .when(refusal.yes(), |d| { | ||
| 5087 | + d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click( | ||
| 5088 | + cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5089 | + // The card goes first: several of | ||
| 5090 | + // these open a card of their own, | ||
| 5091 | + // and every edit moves the indices | ||
| 5092 | + // the menus are holding. | ||
| 5093 | + this.keys_open = false; | ||
| 5094 | + this.rebinding = None; | ||
| 5095 | + this.act(action, cx); | ||
| 5096 | + cx.notify(); | ||
| 5097 | + }), | ||
| 5098 | + ) | ||
| 5099 | + }), | ||
| 5100 | + ) | ||
| 5101 | + .child( | ||
| 5102 | + // ponytail: the column is as wide as the stroke it | ||
| 5103 | + // prints, so a one-character chord gives this half a | ||
| 5104 | + // hit area under the 24px WCAG 2.5.8 floor -- tall | ||
| 5105 | + // enough, narrow. Upgrade: a min_w of HIT_MIN here. | ||
| 4874 | div() | 5106 | div() |
| 4875 | .id(("bind", i)) | 5107 | .id(("bind", i)) |
| 5108 | + .flex_none() | ||
| 4876 | .flex() | 5109 | .flex() |
| 4877 | - // The floor, not the height: a row that needed two lines | ||
| 4878 | - // would otherwise paint over the one under it. | ||
| 4879 | .min_h(px(KEYS_ROW_H)) | 5110 | .min_h(px(KEYS_ROW_H)) |
| 4880 | .items_center() | 5111 | .items_center() |
| 4881 | - .justify_between() | ||
| 4882 | - .gap(px(12.)) | ||
| 4883 | - .px(px(6.)) | ||
| 4884 | - .rounded(px(3.)) | ||
| 4885 | .cursor_pointer() | 5112 | .cursor_pointer() |
| 4886 | .hover(|s| s.bg(rgb(HOVER))) | 5113 | .hover(|s| s.bg(rgb(HOVER))) |
| 4887 | - .when(capturing, |d| d.bg(rgb(SELECTED))) | ||
| 4888 | .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 5114 | .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { |
| 4889 | this.rebinding = Some(action); | 5115 | this.rebinding = Some(action); |
| 4890 | cx.notify(); | 5116 | cx.notify(); |
| 4891 | })) | 5117 | })) |
| 4892 | - .child(action.label()) | ||
| 4893 | .child(if capturing { | 5118 | .child(if capturing { |
| 4894 | div() | 5119 | div() |
| 4895 | .text_color(rgb(INK_DIM)) | 5120 | .text_color(rgb(INK_DIM)) |
| 4896 | .child(format!("press a key — {out} cancels")) | 5121 | .child(format!("press a key — {out} cancels")) |
| 4897 | } else { | 5122 | } else { |
| 4898 | div().child(self.keymap.display(action)) | 5123 | div().child(self.keymap.display(action)) |
| 4899 | - }) | 5124 | + }), |
| 4900 | - .into_any_element(), | 5125 | + ) |
| 4901 | - ); | 5126 | + .into_any_element() |
| 4902 | } | 5127 | } |
| 4903 | - for f in fixed { | 5128 | + KeyRow::Fixed(f) => { |
| 4904 | - head(&mut rows); | 5129 | + let f = &keymap::FIXED[f]; |
| 4905 | - rows.push( | 5130 | + row() |
| 4906 | - div() | ||
| 4907 | - .flex() | ||
| 4908 | - .min_h(px(KEYS_ROW_H)) | ||
| 4909 | - .items_center() | ||
| 4910 | - .justify_between() | ||
| 4911 | - .gap(px(12.)) | ||
| 4912 | - .px(px(6.)) | ||
| 4913 | .child(f.label) | 5131 | .child(f.label) |
| 4914 | // Dim, and no hover: this one is not a row you can click. | 5132 | // Dim, and no hover: this one is not a row you can click. |
| 4915 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) | 5133 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) |
| 4916 | - .into_any_element(), | 5134 | + .into_any_element() |
| 4917 | - ); | ||
| 4918 | } | 5135 | } |
| 5136 | + }); | ||
| 4919 | } | 5137 | } |
| 4920 | Some( | 5138 | Some( |
| 4921 | div() | 5139 | div() |
| @@ -4942,7 +5160,7 @@ impl Player { | |||
| 4942 | // Title and instruction are two children, never one | 5160 | // Title and instruction are two children, never one |
| 4943 | // wrapping line: a fixed-height slot whose text wrapped | 5161 | // wrapping line: a fixed-height slot whose text wrapped |
| 4944 | // painted its second line over the first row. | 5162 | // painted its second line over the first row. |
| 4945 | - .child(div().flex_none().px(px(6.)).child("Keybindings")) | 5163 | + .child(div().flex_none().px(px(6.)).child("Actions & keys")) |
| 4946 | // One status line, under the title where the eye starts. | 5164 | // One status line, under the title where the eye starts. |
| 4947 | // A refusal takes it over -- it is the more urgent of the | 5165 | // A refusal takes it over -- it is the more urgent of the |
| 4948 | // two, and the notice bar it would otherwise appear in is | 5166 | // two, and the notice bar it would otherwise appear in is |
| @@ -4960,7 +5178,10 @@ impl Player { | |||
| 4960 | .child( | 5178 | .child( |
| 4961 | self.notice | 5179 | self.notice |
| 4962 | .clone() | 5180 | .clone() |
| 4963 | - .unwrap_or_else(|| "click a row, then press a key".into()), | 5181 | + .unwrap_or_else(|| { |
| 5182 | + "click an action to do it · click its key to change it" | ||
| 5183 | + .into() | ||
| 5184 | + }), | ||
| 4964 | ), | 5185 | ), |
| 4965 | ) | 5186 | ) |
| 4966 | // Capped and scrolling rather than as tall as the action | 5187 | // Capped and scrolling rather than as tall as the action |
| @@ -6499,7 +6720,6 @@ impl Player { | |||
| 6499 | let menu = self.context_menu?; | 6720 | let menu = self.context_menu?; |
| 6500 | let session = self.session.as_ref()?; | 6721 | let session = self.session.as_ref()?; |
| 6501 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; | 6722 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; |
| 6502 | - let playhead = frame_at(session.now(), self.fps); | ||
| 6503 | let source = session.sources().get(clip.source).cloned()?; | 6723 | let source = session.sources().get(clip.source).cloned()?; |
| 6504 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); | 6724 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); |
| 6505 | let row = |n: usize| { | 6725 | let row = |n: usize| { |
| @@ -6553,7 +6773,11 @@ impl Player { | |||
| 6553 | } | 6773 | } |
| 6554 | } else { | 6774 | } else { |
| 6555 | for action in MENU_ITEMS { | 6775 | for action in MENU_ITEMS { |
| 6556 | - let enabled = applicable(&clip, menu.lane, action, playhead); | 6776 | + // The registry's own answer, the same one the actions card |
| 6777 | + // dims a row with -- and a row that takes no click says *why* | ||
| 6778 | + // rather than printing a stroke that would do nothing. | ||
| 6779 | + let refusal = self.enable(action, Some((menu.lane, menu.idx))); | ||
| 6780 | + let enabled = refusal.yes(); | ||
| 6557 | // The one item that is not about this clip says so, and says it | 6781 | // The one item that is not about this clip says so, and says it |
| 6558 | // here rather than in the registry: the stroke is global too, | 6782 | // here rather than in the registry: the stroke is global too, |
| 6559 | // but its row in the keys menu is not sitting on a clip. | 6783 | // but its row in the keys menu is not sitting on a clip. |
| @@ -6565,11 +6789,20 @@ impl Player { | |||
| 6565 | rows.push( | 6789 | rows.push( |
| 6566 | row(rows.len()) | 6790 | row(rows.len()) |
| 6567 | .child(label) | 6791 | .child(label) |
| 6568 | - .child( | 6792 | + .child(match refusal.why() { |
| 6569 | - div() | 6793 | + // One truncated line, like the details side: a |
| 6794 | + // reason that wrapped would make the card taller | ||
| 6795 | + // than the height `menu_at` placed it by. | ||
| 6796 | + Some(why) => div() | ||
| 6797 | + .min_w(px(0.)) | ||
| 6798 | + .truncate() | ||
| 6799 | + .text_size(px(11.)) | ||
| 6800 | + .text_color(rgb(INK_DIM)) | ||
| 6801 | + .child(why), | ||
| 6802 | + None => div() | ||
| 6570 | .text_color(rgb(INK_DIM)) | 6803 | .text_color(rgb(INK_DIM)) |
| 6571 | .child(self.keymap.display(action)), | 6804 | .child(self.keymap.display(action)), |
| 6572 | - ) | 6805 | + }) |
| 6573 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) | 6806 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) |
| 6574 | .when(enabled, |d| { | 6807 | .when(enabled, |d| { |
| 6575 | d.cursor_pointer() | 6808 | d.cursor_pointer() |
| @@ -6705,6 +6938,14 @@ impl Player { | |||
| 6705 | // itself is clipped to this ([`visible_slice`]), because a box at a deep | 6938 | // itself is clipped to this ([`visible_slice`]), because a box at a deep |
| 6706 | // zoom is far wider than the strip it is being watched through. | 6939 | // zoom is far wider than the strip it is being watched through. |
| 6707 | let bed = f32::from(self.ruler.get().size.width); | 6940 | let bed = f32::from(self.ruler.get().size.width); |
| 6941 | + // Where the snap line stands, in the same pixels every box is placed | ||
| 6942 | + // through -- and only while a gesture is actually live: gpui drops a | ||
| 6943 | + // drag without telling anyone, so this asks whether one is in flight | ||
| 6944 | + // (`App::has_active_drag`) rather than remembering that one was. | ||
| 6945 | + let cue = self | ||
| 6946 | + .snap_cue | ||
| 6947 | + .filter(|_| self.trim.is_some() || cx.has_active_drag()) | ||
| 6948 | + .map(|frame| scale.px_at(f64::from(frame) / self.fps)); | ||
| 6708 | let clips = self | 6949 | let clips = self |
| 6709 | .session | 6950 | .session |
| 6710 | .as_ref() | 6951 | .as_ref() |
| @@ -6851,7 +7092,12 @@ impl Player { | |||
| 6851 | // the window, which took it from the release that fired | 7092 | // the window, which took it from the release that fired |
| 6852 | // this (gpui window.rs:3602). | 7093 | // this (gpui window.rs:3602). |
| 6853 | .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| { | 7094 | .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| { |
| 6854 | - let at = this.frame_under(window.mouse_position().x); | 7095 | + // Onto the edges near it, exactly as a clip carried by |
| 7096 | + // hand lands: the line drawn while it was in flight is | ||
| 7097 | + // the frame it goes down on. | ||
| 7098 | + let x = window.mouse_position().x; | ||
| 7099 | + let marks = this.snap_targets(None); | ||
| 7100 | + let (at, _) = this.snap_to(this.frame_under(x), 0, &marks); | ||
| 6855 | this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx) | 7101 | this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx) |
| 6856 | })) | 7102 | })) |
| 6857 | .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM))) | 7103 | .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM))) |
| @@ -6860,14 +7106,11 @@ impl Player { | |||
| 6860 | // to -- its own included, which is the drag that moves a | 7106 | // to -- its own included, which is the drag that moves a |
| 6861 | // take along its track. | 7107 | // take along its track. |
| 6862 | .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| { | 7108 | .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| { |
| 6863 | - // Against the lane as it is *now*, not as it was when | 7109 | + // Against the lane as it is *now* ([`Player::dragged`]), |
| 6864 | - // the hand took hold: an edit during the drag moves the | 7110 | + // and then snapped by `move_clip` like any other drop: |
| 6865 | - // indices the payload froze ([`live_idx`]). | 7111 | + // which clip is being moved and where it lands are two |
| 6866 | - let Some(idx) = this | 7112 | + // questions, and this is the first one. |
| 6867 | - .session | 7113 | + let Some(idx) = this.dragged(drag) else { |
| 6868 | - .as_ref() | ||
| 6869 | - .and_then(|s| live_idx(s.lane_clips(drag.lane), drag.idx, drag.clip)) | ||
| 6870 | - else { | ||
| 6871 | return; | 7114 | return; |
| 6872 | }; | 7115 | }; |
| 6873 | this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx) | 7116 | this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx) |
| @@ -7149,6 +7392,20 @@ impl Player { | |||
| 7149 | .bg(rgba(0x4a9effaa)) | 7392 | .bg(rgba(0x4a9effaa)) |
| 7150 | }), | 7393 | }), |
| 7151 | ) | 7394 | ) |
| 7395 | + // What the gesture in flight is about to land on, drawn on | ||
| 7396 | + // every lane so a clip lining up with a take one track over | ||
| 7397 | + // can be seen to line up with it. Under the playhead's line | ||
| 7398 | + // and in another colour, since the two mean different | ||
| 7399 | + // things and often stand on the same pixel. | ||
| 7400 | + .children(cue.map(|x| { | ||
| 7401 | + div() | ||
| 7402 | + .absolute() | ||
| 7403 | + .top_0() | ||
| 7404 | + .h_full() | ||
| 7405 | + .left(px(x)) | ||
| 7406 | + .w(px(1.)) | ||
| 7407 | + .bg(rgb(INK)) | ||
| 7408 | + })) | ||
| 7152 | // Last, so it is over the clips: the same fraction in both | 7409 | // Last, so it is over the clips: the same fraction in both |
| 7153 | // lanes, which is the playhead being one line. | 7410 | // lanes, which is the playhead being one line. |
| 7154 | .child( | 7411 | .child( |
| @@ -7397,42 +7654,132 @@ fn band_label(band: &Band) -> String { | |||
| 7397 | } | 7654 | } |
| 7398 | } | 7655 | } |
| 7399 | 7656 | ||
| 7400 | -/// Whether the clip menu offers `action` on the clip it was opened on. Two of | 7657 | +/// Whether an action can be asked for, and what to say when it cannot. Two |
| 7401 | -/// the items act on the *playhead* rather than on the clip, so a menu opened | 7658 | +/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at |
| 7402 | -/// away from it dims them instead of looking broken when they are clicked, and | 7659 | +/// -- an audio clip has no picture, so a grade is not a thing that exists for |
| 7403 | -/// one acts on sound, which only an audio lane's clip has. | 7660 | +/// it, whatever the editor does next -- and `No` is about the state of this |
| 7404 | -fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool { | 7661 | +/// moment, which the next click of the playhead can change. Both dim their row |
| 7662 | +/// today; a menu that wants to leave the class refusals out and keep the state | ||
| 7663 | +/// ones has only to match on which of the two it got. | ||
| 7664 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 7665 | +enum Enable { | ||
| 7666 | + Yes, | ||
| 7667 | + No(&'static str), | ||
| 7668 | + Hidden(&'static str), | ||
| 7669 | +} | ||
| 7670 | + | ||
| 7671 | +impl Enable { | ||
| 7672 | + /// Whether the row takes a click. | ||
| 7673 | + fn yes(self) -> bool { | ||
| 7674 | + self == Enable::Yes | ||
| 7675 | + } | ||
| 7676 | + | ||
| 7677 | + /// What the row says instead of its stroke, if it says anything. | ||
| 7678 | + fn why(self) -> Option<&'static str> { | ||
| 7679 | + match self { | ||
| 7680 | + Enable::Yes => None, | ||
| 7681 | + Enable::No(why) | Enable::Hidden(why) => Some(why), | ||
| 7682 | + } | ||
| 7683 | + } | ||
| 7684 | +} | ||
| 7685 | + | ||
| 7686 | +/// What an enablement question is asked *about*: the clip in question, if there | ||
| 7687 | +/// is one, and the little of the editor's state the answers need. Handed in | ||
| 7688 | +/// rather than read off the player, so [`enable`] is a pure function a test can | ||
| 7689 | +/// ask about a clip without building a window. | ||
| 7690 | +#[derive(Clone, Copy, Default)] | ||
| 7691 | +struct Ctx { | ||
| 7692 | + /// The clip the question is about -- the one a menu was opened on, or the | ||
| 7693 | + /// marked one. `None` means the question is about the editor as a whole, | ||
| 7694 | + /// and the clip-relative answers stand aside: those actions find their own | ||
| 7695 | + /// clip under the playhead and word their own refusal. | ||
| 7696 | + clip: Option<(Clip, Lane)>, | ||
| 7697 | + playhead: u32, | ||
| 7698 | + /// A timeline is open. | ||
| 7699 | + timeline: bool, | ||
| 7700 | + /// Something has been copied. | ||
| 7701 | + clipboard: bool, | ||
| 7702 | + exporting: bool, | ||
| 7703 | +} | ||
| 7704 | + | ||
| 7705 | +/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing | ||
| 7706 | +/// else in the editor asks the question: the clip menu dims a row with this, | ||
| 7707 | +/// the actions card dims a row with this, and the two can never come to | ||
| 7708 | +/// disagree about what an action needs -- exactly the reason [`Player::act`] is | ||
| 7709 | +/// one table too. | ||
| 7710 | +fn enable(action: ActionId, ctx: Ctx) -> Enable { | ||
| 7711 | + if !ctx.timeline { | ||
| 7712 | + return Enable::No("no timeline open"); | ||
| 7713 | + } | ||
| 7714 | + // An export is reading the edit list every other action would change, which | ||
| 7715 | + // is the rule the key handler already follows. | ||
| 7716 | + if ctx.exporting { | ||
| 7717 | + return match action { | ||
| 7718 | + ActionId::CancelExport => Enable::Yes, | ||
| 7719 | + _ => Enable::No("an export is running"), | ||
| 7720 | + }; | ||
| 7721 | + } | ||
| 7405 | match action { | 7722 | match action { |
| 7406 | - // The equalizer filters samples, and a video clip has none of its own | 7723 | + // -- class: what kind of thing the action is about. The equalizer |
| 7407 | - // here: the sound is the audio lane's, clip for clip. | 7724 | + // filters samples, and a video clip has none of its own here: the sound |
| 7408 | - ActionId::Equalizer => lane.kind == LaneKind::Audio, | 7725 | + // is the audio lane's, clip for clip. |
| 7409 | - // A grade is a picture setting and an audio clip has no picture: the | 7726 | + ActionId::Equalizer => match ctx.clip { |
| 7410 | - // item is there on every clip, and dimmed where it would mean nothing. | 7727 | + Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"), |
| 7411 | - // A fit policy is a picture setting for the same reason. | 7728 | + _ => Enable::Yes, |
| 7412 | - ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video, | 7729 | + }, |
| 7413 | - // Splits this clip only from inside it: at either edge there is nothing | 7730 | + // A grade is a picture setting and an audio clip has no picture. A fit |
| 7414 | - // to split off -- and, on a speeded clip, only at a frame its own rate | 7731 | + // policy is a picture setting for the same reason. |
| 7415 | - // can address, which is the same question `splittable` asks. | 7732 | + ActionId::Color | ActionId::Fit => match ctx.clip { |
| 7416 | - ActionId::Cut => { | 7733 | + Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"), |
| 7417 | - clip.start < playhead | 7734 | + _ => Enable::Yes, |
| 7418 | - && playhead < clip.end() | 7735 | + }, |
| 7736 | + // -- state: true of this clip now, and the next playhead click or the | ||
| 7737 | + // next selection changes the answer. Splits this clip only from inside | ||
| 7738 | + // it: at either edge there is nothing to split off -- and, on a speeded | ||
| 7739 | + // clip, only at a frame its own rate can address, which is the same | ||
| 7740 | + // question `splittable` asks. | ||
| 7741 | + ActionId::Cut => match ctx.clip { | ||
| 7742 | + Some((clip, _)) | ||
| 7743 | + if !(clip.start < ctx.playhead | ||
| 7744 | + && ctx.playhead < clip.end() | ||
| 7419 | && clip | 7745 | && clip |
| 7420 | .speed | 7746 | .speed |
| 7421 | - .split_at(clip.len(), playhead - clip.start) | 7747 | + .split_at(clip.len(), ctx.playhead - clip.start) |
| 7422 | - .is_some() | 7748 | + .is_some()) => |
| 7749 | + { | ||
| 7750 | + Enable::No("only from inside a clip") | ||
| 7423 | } | 7751 | } |
| 7424 | - // A rate applies to a clip of either kind and to its whole group, so | 7752 | + _ => Enable::Yes, |
| 7425 | - // there is no lane it means nothing on -- `_ => true` below is its | 7753 | + }, |
| 7426 | - // answer, and the engine words the one refusal there is (no room). | ||
| 7427 | // Rejoins whatever meets at the playhead, so it can mean something only | 7754 | // Rejoins whatever meets at the playhead, so it can mean something only |
| 7428 | // at an edge of this clip. Whether those two halves were ever one take | 7755 | // at an edge of this clip. Whether those two halves were ever one take |
| 7429 | // is the engine's question, and it words that refusal itself. | 7756 | // is the engine's question, and it words that refusal itself. |
| 7430 | - ActionId::Regroup => playhead == clip.start || playhead == clip.end(), | 7757 | + ActionId::Regroup => match ctx.clip { |
| 7758 | + Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => { | ||
| 7759 | + Enable::No("only where two clips meet") | ||
| 7760 | + } | ||
| 7761 | + _ => Enable::Yes, | ||
| 7762 | + }, | ||
| 7431 | // Nothing to take apart in a clip that names no group at all. Whether | 7763 | // Nothing to take apart in a clip that names no group at all. Whether |
| 7432 | // the group it names still has another half is the engine's question, | 7764 | // the group it names still has another half is the engine's question, |
| 7433 | - // like the regroup above, and it words that refusal itself. | 7765 | + // like the regroup above. |
| 7434 | - ActionId::Detach => clip.link.is_some(), | 7766 | + ActionId::Detach => match ctx.clip { |
| 7435 | - _ => true, | 7767 | + Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"), |
| 7768 | + _ => Enable::Yes, | ||
| 7769 | + }, | ||
| 7770 | + // The three that act on the marked clip and on nothing else: with none | ||
| 7771 | + // marked they would silently do nothing, which is what the Delete | ||
| 7772 | + // button's own dimming has always said. | ||
| 7773 | + ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => { | ||
| 7774 | + Enable::No("click a clip first") | ||
| 7775 | + } | ||
| 7776 | + ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"), | ||
| 7777 | + ActionId::CancelExport => Enable::No("nothing is exporting"), | ||
| 7778 | + // A rate applies to a clip of either kind and to its whole group, so | ||
| 7779 | + // there is no lane it means nothing on, and the engine words the one | ||
| 7780 | + // refusal there is (no room). Everything else is the editor's own and | ||
| 7781 | + // needs nothing but a timeline. | ||
| 7782 | + _ => Enable::Yes, | ||
| 7436 | } | 7783 | } |
| 7437 | } | 7784 | } |
| 7438 | 7785 | ||
| @@ -8889,6 +9236,56 @@ fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 { | |||
| 8889 | best.map_or(raw, |(_, start)| start) | 9236 | best.map_or(raw, |(_, start)| start) |
| 8890 | } | 9237 | } |
| 8891 | 9238 | ||
| 9239 | +/// The edges worth landing on, off *every* lane: both ends of every clip on the | ||
| 9240 | +/// timeline, less `skip` -- the clip being dragged, which does not snap to where | ||
| 9241 | +/// it already is -- and less the other halves of its group, which travel with | ||
| 9242 | +/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead | ||
| 9243 | +/// and the head of the timeline go on the end: a clip meets the cursor and the | ||
| 9244 | +/// start of the show as readily as it meets another take. | ||
| 9245 | +/// | ||
| 9246 | +/// All lanes rather than the one being dropped on, because a cut is made across | ||
| 9247 | +/// the timeline: a title on V2 lines up with the shot under it, and a sound | ||
| 9248 | +/// effect lines up with the frame it belongs to. | ||
| 9249 | +fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec<u32> { | ||
| 9250 | + let link = skip | ||
| 9251 | + .and_then(|(lane, idx)| lanes.get(lane)?.get(idx)) | ||
| 9252 | + .and_then(|clip| clip.link); | ||
| 9253 | + let mut marks: Vec<u32> = lanes | ||
| 9254 | + .iter() | ||
| 9255 | + .enumerate() | ||
| 9256 | + .flat_map(|(lane, clips)| { | ||
| 9257 | + clips | ||
| 9258 | + .iter() | ||
| 9259 | + .enumerate() | ||
| 9260 | + .filter(move |&(idx, clip)| { | ||
| 9261 | + Some((lane, idx)) != skip && !(link.is_some() && clip.link == link) | ||
| 9262 | + }) | ||
| 9263 | + .flat_map(|(_, clip)| [clip.start, clip.end()]) | ||
| 9264 | + }) | ||
| 9265 | + .collect(); | ||
| 9266 | + marks.push(playhead); | ||
| 9267 | + marks.push(0); | ||
| 9268 | + marks | ||
| 9269 | +} | ||
| 9270 | + | ||
| 9271 | +/// [`snapped`], and the mark that pulled it there -- the line the bed draws | ||
| 9272 | +/// while the hand is still moving. `None` when nothing was near enough: a line | ||
| 9273 | +/// standing over open bed would promise a landing that is not going to happen. | ||
| 9274 | +/// The head is read before the tail, exactly as [`snapped`] prefers it. | ||
| 9275 | +/// | ||
| 9276 | +/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and | ||
| 9277 | +/// draws no line at all, which is the whole point of being able to turn it off. | ||
| 9278 | +fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) { | ||
| 9279 | + if !on { | ||
| 9280 | + return (raw, None); | ||
| 9281 | + } | ||
| 9282 | + let start = snapped(raw, len, tol, marks); | ||
| 9283 | + let mark = [start, start.saturating_add(len)] | ||
| 9284 | + .into_iter() | ||
| 9285 | + .find(|mark| marks.contains(mark)); | ||
| 9286 | + (start, mark) | ||
| 9287 | +} | ||
| 9288 | + | ||
| 8892 | /// Where down an element a pointer sits, 0..1 from the top: the vertical twin | 9289 | /// Where down an element a pointer sits, 0..1 from the top: the vertical twin |
| 8893 | /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An | 9290 | /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An |
| 8894 | /// element that was never painted reads as its middle -- flat, the one answer | 9291 | /// element that was never painted reads as its middle -- flat, the one answer |
| @@ -9217,22 +9614,24 @@ fn timecode(t: f64, fps: f64) -> String { | |||
| 9217 | #[cfg(test)] | 9614 | #[cfg(test)] |
| 9218 | mod tests { | 9615 | mod tests { |
| 9219 | use super::{ | 9616 | use super::{ |
| 9220 | - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, | 9617 | + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, |
| 9221 | - EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, | 9618 | + EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, |
| 9222 | - EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, FORMATS, Format, HEADER_GAP, | 9619 | + EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS, |
| 9223 | - HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, | 9620 | + Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, |
| 9224 | - KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, | 9621 | + INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, |
| 9225 | - LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, | 9622 | + LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, |
| 9226 | - PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, | 9623 | + MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, |
| 9227 | - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume, | 9624 | + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, |
| 9228 | - WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, applicable, band_label, bitrate_refusal, can_add, | 9625 | + Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label, |
| 9229 | - cancels_export, clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, | 9626 | + bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers, |
| 9230 | - eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, format_line, | 9627 | + enable, envelope, |
| 9231 | - format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, | 9628 | + eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, |
| 9232 | - is_project, keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, | 9629 | + format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, |
| 9233 | - panel_h, project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped, | 9630 | + is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at, next_container, |
| 9234 | - source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport, | 9631 | + normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, |
| 9235 | - unseen_paths, unseen_sources, whole_take, window_title, | 9632 | + show_label, silence_rate, snap_cue, snap_marks, snapped, source_tint, span_partner, |
| 9633 | + speed_at, summary_head, summary_tail, timecode, transport, unseen_paths, unseen_sources, | ||
| 9634 | + whole_take, window_title, | ||
| 9236 | }; | 9635 | }; |
| 9237 | use super::{ | 9636 | use super::{ |
| 9238 | Edge, LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, | 9637 | Edge, LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, |
| @@ -9549,43 +9948,126 @@ mod tests { | |||
| 9549 | speed: Speed::NORMAL, | 9948 | speed: Speed::NORMAL, |
| 9550 | }; | 9949 | }; |
| 9551 | assert_eq!(clip.end(), 90); | 9950 | assert_eq!(clip.end(), 90); |
| 9552 | - // Cut splits from inside only: neither edge has anything to split off. | ||
| 9553 | let a1 = Lane::A1; | 9951 | let a1 = Lane::A1; |
| 9554 | let v1 = Lane::V1; | 9952 | let v1 = Lane::V1; |
| 9555 | - assert!(applicable(&clip, v1, ActionId::Cut, 31)); | 9953 | + // The question the clip menu asks: a timeline is open and the menu was |
| 9556 | - assert!(applicable(&clip, v1, ActionId::Cut, 89)); | 9954 | + // opened on this clip, at this playhead. |
| 9557 | - assert!(!applicable(&clip, v1, ActionId::Cut, 30)); | 9955 | + let on = |clip: &Clip, lane, action, playhead| { |
| 9558 | - assert!(!applicable(&clip, v1, ActionId::Cut, 90)); | 9956 | + enable( |
| 9559 | - assert!(!applicable(&clip, v1, ActionId::Cut, 200)); | 9957 | + action, |
| 9958 | + Ctx { | ||
| 9959 | + clip: Some((*clip, lane)), | ||
| 9960 | + playhead, | ||
| 9961 | + timeline: true, | ||
| 9962 | + ..Ctx::default() | ||
| 9963 | + }, | ||
| 9964 | + ) | ||
| 9965 | + }; | ||
| 9966 | + let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes(); | ||
| 9967 | + // Cut splits from inside only: neither edge has anything to split off. | ||
| 9968 | + assert!(offered(&clip, v1, ActionId::Cut, 31)); | ||
| 9969 | + assert!(offered(&clip, v1, ActionId::Cut, 89)); | ||
| 9970 | + assert!(!offered(&clip, v1, ActionId::Cut, 30)); | ||
| 9971 | + assert!(!offered(&clip, v1, ActionId::Cut, 90)); | ||
| 9972 | + assert!(!offered(&clip, v1, ActionId::Cut, 200)); | ||
| 9560 | // Regroup is the other way round: only where this clip meets another. | 9973 | // Regroup is the other way round: only where this clip meets another. |
| 9561 | - assert!(applicable(&clip, v1, ActionId::Regroup, 30)); | 9974 | + assert!(offered(&clip, v1, ActionId::Regroup, 30)); |
| 9562 | - assert!(applicable(&clip, v1, ActionId::Regroup, 90)); | 9975 | + assert!(offered(&clip, v1, ActionId::Regroup, 90)); |
| 9563 | - assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); | 9976 | + assert!(!offered(&clip, v1, ActionId::Regroup, 60)); |
| 9564 | // Detach is the clip's own business: nothing to take apart in one that | 9977 | // Detach is the clip's own business: nothing to take apart in one that |
| 9565 | // names no group, and whether the group still has another half is the | 9978 | // names no group, and whether the group still has another half is the |
| 9566 | // engine's question. Group is offered on every clip, for that reason. | 9979 | // engine's question. Group is offered on every clip, for that reason. |
| 9567 | - assert!(!applicable(&clip, v1, ActionId::Detach, 0)); | 9980 | + assert!(!offered(&clip, v1, ActionId::Detach, 0)); |
| 9568 | let grouped = Clip { | 9981 | let grouped = Clip { |
| 9569 | link: Some(3), | 9982 | link: Some(3), |
| 9570 | ..clip | 9983 | ..clip |
| 9571 | }; | 9984 | }; |
| 9572 | - assert!(applicable(&grouped, v1, ActionId::Detach, 60)); | 9985 | + assert!(offered(&grouped, v1, ActionId::Detach, 60)); |
| 9573 | - assert!(applicable(&clip, a1, ActionId::Group, 0)); | 9986 | + assert!(offered(&clip, a1, ActionId::Group, 0)); |
| 9574 | // The equalizer is the one item the *lane* decides: it filters samples, | 9987 | // The equalizer is the one item the *lane* decides: it filters samples, |
| 9575 | // and a video clip has none of its own. Never the playhead's business. | 9988 | // and a video clip has none of its own. Never the playhead's business. |
| 9576 | - assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); | 9989 | + assert!(offered(&clip, a1, ActionId::Equalizer, 0)); |
| 9577 | - assert!(applicable(&clip, a1, ActionId::Equalizer, 60)); | 9990 | + assert!(offered(&clip, a1, ActionId::Equalizer, 60)); |
| 9578 | - assert!(!applicable(&clip, v1, ActionId::Equalizer, 60)); | 9991 | + assert!(!offered(&clip, v1, ActionId::Equalizer, 60)); |
| 9579 | // The rest act on the clip that was clicked, so they always mean | 9992 | // The rest act on the clip that was clicked, so they always mean |
| 9580 | // something -- the engine words its own refusals. | 9993 | // something -- the engine words its own refusals. |
| 9581 | for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { | 9994 | for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { |
| 9582 | - assert!(applicable(&clip, v1, action, 0)); | 9995 | + assert!(offered(&clip, v1, action, 0)); |
| 9583 | - assert!(applicable(&clip, a1, action, 60)); | 9996 | + assert!(offered(&clip, a1, action, 60)); |
| 9584 | } | 9997 | } |
| 9585 | // Except the grade, which is a picture setting: offered on a video | 9998 | // Except the grade, which is a picture setting: offered on a video |
| 9586 | // clip wherever the playhead is, dimmed on a waveform. | 9999 | // clip wherever the playhead is, dimmed on a waveform. |
| 9587 | - assert!(applicable(&clip, v1, ActionId::Color, 0)); | 10000 | + assert!(offered(&clip, v1, ActionId::Color, 0)); |
| 9588 | - assert!(!applicable(&clip, a1, ActionId::Color, 60)); | 10001 | + assert!(!offered(&clip, a1, ActionId::Color, 60)); |
| 10002 | + // The two kinds of no, which is what the row can be told apart by: a | ||
| 10003 | + // grade on a waveform is a *class* answer -- an audio clip has no | ||
| 10004 | + // picture and never will, so a menu may leave the item out -- where a | ||
| 10005 | + // cut at the clip's edge is this moment's answer and the next click of | ||
| 10006 | + // the playhead changes it, so that one is dimmed and stays. | ||
| 10007 | + assert!(matches!( | ||
| 10008 | + on(&clip, a1, ActionId::Color, 60), | ||
| 10009 | + Enable::Hidden(_) | ||
| 10010 | + )); | ||
| 10011 | + assert!(matches!( | ||
| 10012 | + on(&clip, a1, ActionId::Fit, 60), | ||
| 10013 | + Enable::Hidden(_) | ||
| 10014 | + )); | ||
| 10015 | + assert!(matches!( | ||
| 10016 | + on(&clip, v1, ActionId::Equalizer, 60), | ||
| 10017 | + Enable::Hidden(_) | ||
| 10018 | + )); | ||
| 10019 | + assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_))); | ||
| 10020 | + assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_))); | ||
| 10021 | + assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_))); | ||
| 10022 | + // Every refusal says something, and says it short enough to sit in the | ||
| 10023 | + // menu's right-hand column beside a label. | ||
| 10024 | + for action in MENU_ITEMS { | ||
| 10025 | + for lane in [v1, a1] { | ||
| 10026 | + for playhead in [0, 30, 60, 90] { | ||
| 10027 | + if let Some(why) = on(&clip, lane, action, playhead).why() { | ||
| 10028 | + assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}"); | ||
| 10029 | + } | ||
| 10030 | + } | ||
| 10031 | + } | ||
| 10032 | + } | ||
| 10033 | + // The editor as a whole, which is how the actions card asks: with no | ||
| 10034 | + // timeline nothing is offered, an export leaves only its own cancel, | ||
| 10035 | + // and the three that act on the marked clip say so when none is. | ||
| 10036 | + let whole = |action, ctx| enable(action, ctx); | ||
| 10037 | + assert_eq!( | ||
| 10038 | + whole(ActionId::Play, Ctx::default()), | ||
| 10039 | + Enable::No("no timeline open") | ||
| 10040 | + ); | ||
| 10041 | + let live = Ctx { | ||
| 10042 | + timeline: true, | ||
| 10043 | + ..Ctx::default() | ||
| 10044 | + }; | ||
| 10045 | + assert!(whole(ActionId::Play, live).yes()); | ||
| 10046 | + assert!(!whole(ActionId::Delete, live).yes()); | ||
| 10047 | + assert!(!whole(ActionId::Paste, live).yes()); | ||
| 10048 | + assert!( | ||
| 10049 | + whole( | ||
| 10050 | + ActionId::Paste, | ||
| 10051 | + Ctx { | ||
| 10052 | + clipboard: true, | ||
| 10053 | + ..live | ||
| 10054 | + } | ||
| 10055 | + ) | ||
| 10056 | + .yes() | ||
| 10057 | + ); | ||
| 10058 | + assert!(!whole(ActionId::CancelExport, live).yes()); | ||
| 10059 | + let busy = Ctx { | ||
| 10060 | + exporting: true, | ||
| 10061 | + ..live | ||
| 10062 | + }; | ||
| 10063 | + assert!(whole(ActionId::CancelExport, busy).yes()); | ||
| 10064 | + for action in ActionId::ALL { | ||
| 10065 | + assert_eq!( | ||
| 10066 | + whole(action, busy).yes(), | ||
| 10067 | + action == ActionId::CancelExport, | ||
| 10068 | + "{action:?} while an export reads the edit list" | ||
| 10069 | + ); | ||
| 10070 | + } | ||
| 9589 | // The playhead frame is the engine's own rule, boundary included. | 10071 | // The playhead frame is the engine's own rule, boundary included. |
| 9590 | assert_eq!(frame_at(1.0, 30.), 30); | 10072 | assert_eq!(frame_at(1.0, 30.), 30); |
| 9591 | assert_eq!(frame_at(0.0, 30.), 0); | 10073 | assert_eq!(frame_at(0.0, 30.), 0); |
| @@ -9628,9 +10110,9 @@ mod tests { | |||
| 9628 | 10110 | ||
| 9629 | /// The other half of the keys menu's guarantee, and the audit this batch was | 10111 | /// The other half of the keys menu's guarantee, and the audit this batch was |
| 9630 | /// asked for kept as a test: no action may be a stroke and nothing else. | 10112 | /// asked for kept as a test: no action may be a stroke and nothing else. |
| 9631 | - /// Either the clip menu offers it, or a control in the panel does -- named | 10113 | + /// The actions card answers it for all of them at once -- its rows come off |
| 9632 | - /// here by the id [`control`] is handed, read out of this file's own source | 10114 | + /// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and |
| 9633 | - /// like `no_stroke_is_missing_from_the_keys_menu` reads the key handler. | 10115 | + /// there is no hand-written list here to fall behind. |
| 9634 | #[test] | 10116 | #[test] |
| 9635 | fn every_action_is_reachable_without_the_keyboard() { | 10117 | fn every_action_is_reachable_without_the_keyboard() { |
| 9636 | use keymap::ActionId; | 10118 | use keymap::ActionId; |
| @@ -9639,48 +10121,26 @@ mod tests { | |||
| 9639 | .next() | 10121 | .next() |
| 9640 | .unwrap(); | 10122 | .unwrap(); |
| 9641 | let element = |id: &str| source.contains(&format!("\"{id}\"")); | 10123 | let element = |id: &str| source.contains(&format!("\"{id}\"")); |
| 10124 | + let listed: Vec<ActionId> = keys_rows() | ||
| 10125 | + .iter() | ||
| 10126 | + .filter_map(|r| match r { | ||
| 10127 | + KeyRow::Act(a) => Some(*a), | ||
| 10128 | + _ => None, | ||
| 10129 | + }) | ||
| 10130 | + .collect(); | ||
| 9642 | for action in ActionId::ALL { | 10131 | for action in ActionId::ALL { |
| 9643 | - let by_pointer = MENU_ITEMS.contains(&action) | 10132 | + assert_eq!( |
| 9644 | - || match action { | 10133 | + listed.iter().filter(|a| **a == action).count(), |
| 9645 | - ActionId::Play => element("transport"), | 10134 | + 1, |
| 9646 | - // One slot, two states: it starts an export and stops the | 10135 | + "{action:?} is reachable by keyboard only" |
| 9647 | - // one it started. | 10136 | + ); |
| 9648 | - ActionId::Export | ActionId::CancelExport => element("export"), | ||
| 9649 | - ActionId::Save => element("save"), | ||
| 9650 | - ActionId::Undo => element("undo"), | ||
| 9651 | - ActionId::Resolution => element("resolution"), | ||
| 9652 | - // Three buttons beside it, and the ctrl+wheel on the bar. | ||
| 9653 | - ActionId::ZoomIn => element("zoom-in"), | ||
| 9654 | - ActionId::ZoomOut => element("zoom-out"), | ||
| 9655 | - ActionId::ZoomFit => element("zoom-fit"), | ||
| 9656 | - ActionId::AddVideoLane => element("add-video-lane"), | ||
| 9657 | - ActionId::AddAudioLane => element("add-audio-lane"), | ||
| 9658 | - // The × in a lane's own header, which takes any track and | ||
| 9659 | - // not only the last one. | ||
| 9660 | - ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => { | ||
| 9661 | - source.contains("this.remove_lane(lane, cx)") | ||
| 9662 | - } | ||
| 9663 | - ActionId::ToggleMute => element("volume"), | ||
| 9664 | - // The fader on every audio track's own header, which is | ||
| 9665 | - // also what opens the card the limiter is on. | ||
| 9666 | - ActionId::Mix => element("mix-lane"), | ||
| 9667 | - ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"), | ||
| 9668 | - // The ruler seeks anywhere the pointer points; the frame and | ||
| 9669 | - // the second are the keyboard's finer grain of that move. | ||
| 9670 | - ActionId::StepBack | ||
| 9671 | - | ActionId::StepForward | ||
| 9672 | - | ActionId::JumpBack | ||
| 9673 | - | ActionId::JumpForward | ||
| 9674 | - | ActionId::GoStart | ||
| 9675 | - | ActionId::GoEnd => element("ruler"), | ||
| 9676 | - // A press on a clip is the selection, group and all. | ||
| 9677 | - ActionId::Select | ActionId::SelectNext | ActionId::SelectPrev => { | ||
| 9678 | - source.contains("this.select((lane, i), cx)") | ||
| 9679 | - } | ||
| 9680 | - _ => false, | ||
| 9681 | - }; | ||
| 9682 | - assert!(by_pointer, "{action:?} is reachable by keyboard only"); | ||
| 9683 | } | 10137 | } |
| 10138 | + // The snap has a door of its own as well as its row on the card: the | ||
| 10139 | + // button beside the zoom, which says which way it is set as well as | ||
| 10140 | + // setting it. | ||
| 10141 | + assert!(element("snap"), "no snap button beside the zoom"); | ||
| 10142 | + // And the card is a door the pointer can open: the panel's own button. | ||
| 10143 | + assert!(element("keys"), "no way to open the actions card"); | ||
| 9684 | // The card-local strokes have the same rule, and each of them is a thing | 10144 | // The card-local strokes have the same rule, and each of them is a thing |
| 9685 | // on its card: the graph and its two buttons, the colour bars and their | 10145 | // on its card: the graph and its two buttons, the colour bars and their |
| 9686 | // reset, the speed bar and its presets, and the silence card's rows -- | 10146 | // reset, the speed bar and its presets, and the silence card's rows -- |
| @@ -10361,6 +10821,62 @@ mod tests { | |||
| 10361 | assert_eq!(snapped(2, 40, 4, &marks), 0); | 10821 | assert_eq!(snapped(2, 40, 4, &marks), 0); |
| 10362 | } | 10822 | } |
| 10363 | 10823 | ||
| 10824 | + /// Where those edges come from: every lane, not the one being dropped on -- | ||
| 10825 | + /// and never the clip in the hand or the half of it one track down. | ||
| 10826 | + #[test] | ||
| 10827 | + fn the_marks_are_every_lane_the_playhead_and_the_start() { | ||
| 10828 | + let clip = |start: u32, frames: u32, link| Clip { | ||
| 10829 | + start, | ||
| 10830 | + in_frame: 0, | ||
| 10831 | + out_frame: frames, | ||
| 10832 | + source: 0, | ||
| 10833 | + link, | ||
| 10834 | + eq: None, | ||
| 10835 | + color: None, | ||
| 10836 | + fit: Default::default(), | ||
| 10837 | + speed: Default::default(), | ||
| 10838 | + }; | ||
| 10839 | + // A grouped take across two lanes at 100..160, and a lone one on the | ||
| 10840 | + // audio lane at 400..430. | ||
| 10841 | + let video = [clip(100, 60, Some(7))]; | ||
| 10842 | + let audio = [clip(100, 60, Some(7)), clip(400, 30, None)]; | ||
| 10843 | + let lanes: [&[Clip]; 2] = [&video, &audio]; | ||
| 10844 | + | ||
| 10845 | + // Nothing in the hand: both lanes' edges, the playhead, and 0. | ||
| 10846 | + let mut all = snap_marks(&lanes, None, 300); | ||
| 10847 | + all.sort_unstable(); | ||
| 10848 | + assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]); | ||
| 10849 | + | ||
| 10850 | + // The video half in the hand: its own edges are gone, and so are its | ||
| 10851 | + // group's on the other lane -- both boxes travel with the drag. The | ||
| 10852 | + // lone audio clip is still a target, which is the whole point: a take | ||
| 10853 | + // being carried on V1 lands flush with a sound on A1. | ||
| 10854 | + let mut carried = snap_marks(&lanes, Some((0, 0)), 300); | ||
| 10855 | + carried.sort_unstable(); | ||
| 10856 | + assert_eq!(carried, [0, 300, 400, 430]); | ||
| 10857 | + | ||
| 10858 | + // An index that names no clip skips nothing and still answers. | ||
| 10859 | + assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]); | ||
| 10860 | + } | ||
| 10861 | + | ||
| 10862 | + /// The line the bed draws, and the switch that turns the whole thing off. | ||
| 10863 | + #[test] | ||
| 10864 | + fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() { | ||
| 10865 | + let marks = [100, 160, 300, 0]; | ||
| 10866 | + // Pulled by the tail: the clip lands at 60 and the line stands on the | ||
| 10867 | + // edge its *tail* met, 100 -- not on the head it happens to have. | ||
| 10868 | + assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100))); | ||
| 10869 | + // Pulled by the head: line and landing are the same frame. | ||
| 10870 | + assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160))); | ||
| 10871 | + // A trim carries no length, so only its own edge lands. | ||
| 10872 | + assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300))); | ||
| 10873 | + // Open bed: nothing moves and nothing is drawn. | ||
| 10874 | + assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None)); | ||
| 10875 | + // Switched off, a gesture that would have snapped lands raw and draws | ||
| 10876 | + // no line -- the frame-by-frame placement the toggle is for. | ||
| 10877 | + assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None)); | ||
| 10878 | + } | ||
| 10879 | + | ||
| 10364 | #[test] | 10880 | #[test] |
| 10365 | fn timecode_counts_frames_inside_the_second() { | 10881 | fn timecode_counts_frames_inside_the_second() { |
| 10366 | assert_eq!(timecode(0., 30.), "00:00:00:00"); | 10882 | assert_eq!(timecode(0., 30.), "00:00:00:00"); |
| @@ -10785,6 +11301,65 @@ mod tests { | |||
| 10785 | } | 11301 | } |
| 10786 | } | 11302 | } |
| 10787 | 11303 | ||
| 11304 | + /// The whole point of the card: there is no action a pointer cannot reach. | ||
| 11305 | + /// It renders [`keys_rows`] and nothing else, so this reads the same list | ||
| 11306 | + /// the card does -- add an `ActionId` and forget to surface it and this | ||
| 11307 | + /// fails, which is the only way that stays true as the editor grows. | ||
| 11308 | + #[test] | ||
| 11309 | + fn every_action_is_on_the_actions_card() { | ||
| 11310 | + use keymap::{ActionId, Category, Keymap}; | ||
| 11311 | + let rows = keys_rows(); | ||
| 11312 | + let listed: Vec<ActionId> = rows | ||
| 11313 | + .iter() | ||
| 11314 | + .filter_map(|r| match r { | ||
| 11315 | + KeyRow::Act(a) => Some(*a), | ||
| 11316 | + _ => None, | ||
| 11317 | + }) | ||
| 11318 | + .collect(); | ||
| 11319 | + for action in ActionId::ALL { | ||
| 11320 | + assert_eq!( | ||
| 11321 | + listed.iter().filter(|a| **a == action).count(), | ||
| 11322 | + 1, | ||
| 11323 | + "{action:?} is not on the card exactly once" | ||
| 11324 | + ); | ||
| 11325 | + } | ||
| 11326 | + assert_eq!(listed.len(), ActionId::ALL.len()); | ||
| 11327 | + // Under its own heading, in the registry's order: every row after a | ||
| 11328 | + // heading belongs to that heading until the next one. | ||
| 11329 | + let mut heading = None; | ||
| 11330 | + let mut heads = 0; | ||
| 11331 | + for row in &rows { | ||
| 11332 | + match row { | ||
| 11333 | + KeyRow::Head(category) => { | ||
| 11334 | + heading = Some(*category); | ||
| 11335 | + heads += 1; | ||
| 11336 | + } | ||
| 11337 | + KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"), | ||
| 11338 | + KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading), | ||
| 11339 | + } | ||
| 11340 | + } | ||
| 11341 | + assert_eq!(heads, Category::ALL.len(), "a heading per category"); | ||
| 11342 | + // The card-local strokes are still all there beside them. | ||
| 11343 | + assert_eq!( | ||
| 11344 | + rows.iter() | ||
| 11345 | + .filter(|r| matches!(r, KeyRow::Fixed(_))) | ||
| 11346 | + .count(), | ||
| 11347 | + keymap::FIXED.len() | ||
| 11348 | + ); | ||
| 11349 | + // Both columns say something: the label does the action, the stroke | ||
| 11350 | + // beside it changes that stroke, and neither may read blank. | ||
| 11351 | + let keymap = Keymap::defaults(); | ||
| 11352 | + for action in ActionId::ALL { | ||
| 11353 | + assert!(!action.label().is_empty(), "{action:?}"); | ||
| 11354 | + assert_ne!(keymap.display(action), "unbound", "{action:?}"); | ||
| 11355 | + } | ||
| 11356 | + // The list scrolls inside a card the smallest window holds, so a | ||
| 11357 | + // thirty-fourth action costs no height at all. | ||
| 11358 | + assert!(rows.len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, "no cap needed?"); | ||
| 11359 | + // Both halves of a row are click targets, so WCAG 2.5.8 binds them. | ||
| 11360 | + assert!(KEYS_ROW_H >= HIT_MIN); | ||
| 11361 | + } | ||
| 11362 | + | ||
| 10788 | #[test] | 11363 | #[test] |
| 10789 | fn the_keybindings_card_fits_the_smallest_window() { | 11364 | fn the_keybindings_card_fits_the_smallest_window() { |
| 10790 | // The row list is capped and scrolls, so the card's height no longer | 11365 | // The row list is capped and scrolls, so the card's height no longer |
| @@ -12408,6 +12983,8 @@ fn main() { | |||
| 12408 | scrubbing: false, | 12983 | scrubbing: false, |
| 12409 | trim: None, | 12984 | trim: None, |
| 12410 | grab: 0, | 12985 | grab: 0, |
| 12986 | + snap: true, | ||
| 12987 | + snap_cue: None, | ||
| 12411 | last_scrub: Instant::now(), | 12988 | last_scrub: Instant::now(), |
| 12412 | last_target: 0, | 12989 | last_target: 0, |
| 12413 | export: None, | 12990 | export: None, |
crates/engine/src/audio.rsmodified+270 -39
| @@ -66,10 +66,6 @@ const PRE_ROLL: u32 = 2; | |||
| 66 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. | 66 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. |
| 67 | const SAMPLES_PER_PACKET: u32 = 1024; | 67 | const SAMPLES_PER_PACKET: u32 = 1024; |
| 68 | 68 | ||
| 69 | -/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks | ||
| 70 | -/// of 256), the way 1024 is fixed for AAC-LC. | ||
| 71 | -const AC3_SAMPLES_PER_FRAME: u32 = 1536; | ||
| 72 | - | ||
| 73 | /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the | 69 | /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the |
| 74 | /// 256-sample overlap-add the target frame is reconstructed with. | 70 | /// 256-sample overlap-add the target frame is reconstructed with. |
| 75 | const AC3_PRE_ROLL: u32 = 1; | 71 | const AC3_PRE_ROLL: u32 = 1; |
| @@ -541,17 +537,26 @@ impl AudioSession { | |||
| 541 | /// -- nothing to tell the user there. Header only, and only worth calling | 537 | /// -- nothing to tell the user there. Header only, and only worth calling |
| 542 | /// once the open has already returned no audio. | 538 | /// once the open has already returned no audio. |
| 543 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | 539 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| 544 | - // Matroska: AAC is read out of one ([`Track::open`]) and everything | 540 | + // Matroska: what symphonia reads out of one ([`Track::open`]) plus the |
| 545 | - // else -- Opus, AC-3, DTS, none of which symphonia decodes at any | 541 | + // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder |
| 546 | - // version -- is named rather than left playing silent with no reason | 542 | + // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here |
| 547 | - // given. A Matroska file with no audio track at all returns `None` here | 543 | + // has at any version -- is named rather than left playing silent with no |
| 548 | - // like any other silent file. | 544 | + // reason given. A Matroska file with no audio track at all returns |
| 545 | + // `None` here like any other silent file. | ||
| 549 | if crate::demux::is_matroska(path.as_ref()) { | 546 | if crate::demux::is_matroska(path.as_ref()) { |
| 550 | - return Ok( | 547 | + let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { |
| 551 | - crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { | 548 | + return Ok(None); |
| 552 | - format!("the {codec} track of this Matroska file cannot be decoded (AAC only)") | 549 | + }; |
| 553 | - }), | 550 | + // An AC-3 track that came up silent all the same is one that could |
| 554 | - ); | 551 | + // not be read -- a laced block, an unreadable syncframe -- and the |
| 552 | + // reader's own words are the ones worth showing. | ||
| 553 | + return Ok(Some(match MkvAc3Track::open(path.as_ref()) { | ||
| 554 | + Ok(Some(_)) => return Ok(None), | ||
| 555 | + Ok(None) => format!( | ||
| 556 | + "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" | ||
| 557 | + ), | ||
| 558 | + Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), | ||
| 559 | + })); | ||
| 555 | } | 560 | } |
| 556 | let file = File::open(path.as_ref())?; | 561 | let file = File::open(path.as_ref())?; |
| 557 | let size = file.metadata()?.len(); | 562 | let size = file.metadata()?.len(); |
| @@ -599,10 +604,24 @@ impl AudioSession { | |||
| 599 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { | 604 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 600 | let path = path.as_ref(); | 605 | let path = path.as_ref(); |
| 601 | // A Matroska file has exactly one readable audio stream here -- the | 606 | // A Matroska file has exactly one readable audio stream here -- the |
| 602 | - // reader's default track ([`SymTrack::open`]) -- so it lists like a | 607 | + // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one |
| 608 | + // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a | ||
| 603 | // standalone audio file rather than like an mp4, and one with no | 609 | // standalone audio file rather than like an mp4, and one with no |
| 604 | // readable track at all lists as the silent source it is. | 610 | // readable track at all lists as the silent source it is. |
| 605 | if crate::demux::is_matroska(path) { | 611 | if crate::demux::is_matroska(path) { |
| 612 | + // The AC-3 row describes what the decoder *emits*, which is the | ||
| 613 | + // stereo the §7.8 downmix hands the timeline, not the 5.1 the file | ||
| 614 | + // carries -- exactly as the mp4 AC-3 rows do. | ||
| 615 | + if let Ok(Some(track)) = MkvAc3Track::open(path) { | ||
| 616 | + return Ok(vec![StreamInfo { | ||
| 617 | + index: 0, | ||
| 618 | + codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), | ||
| 619 | + channels: track.channels, | ||
| 620 | + sample_rate: track.sample_rate, | ||
| 621 | + lang: None, | ||
| 622 | + decodable: matches!(track.channels, 1 | 2), | ||
| 623 | + }]); | ||
| 624 | + } | ||
| 606 | let Ok(track) = SymTrack::open(path) else { | 625 | let Ok(track) = SymTrack::open(path) else { |
| 607 | return Ok(Vec::new()); | 626 | return Ok(Vec::new()); |
| 608 | }; | 627 | }; |
| @@ -924,7 +943,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { | |||
| 924 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` | 943 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` |
| 925 | // sample table can hold. The export decodes it and encodes AAC, exactly | 944 | // sample table can hold. The export decodes it and encodes AAC, exactly |
| 926 | // as it does for every other source no copy reaches. | 945 | // as it does for every other source no copy reaches. |
| 927 | - Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), | 946 | + Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), |
| 928 | } | 947 | } |
| 929 | } | 948 | } |
| 930 | 949 | ||
| @@ -947,6 +966,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error { | |||
| 947 | enum Track { | 966 | enum Track { |
| 948 | Aac(AacTrack), | 967 | Aac(AacTrack), |
| 949 | Ac3(Ac3Track), | 968 | Ac3(Ac3Track), |
| 969 | + /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an | ||
| 970 | + /// mp4's sample table. | ||
| 971 | + Mkv(MkvAc3Track), | ||
| 950 | Sym(SymTrack), | 972 | Sym(SymTrack), |
| 951 | } | 973 | } |
| 952 | 974 | ||
| @@ -965,16 +987,27 @@ impl Track { | |||
| 965 | /// has exactly one, so any `stream` above 0 there is a promise the file | 987 | /// has exactly one, so any `stream` above 0 there is a promise the file |
| 966 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. | 988 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. |
| 967 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { | 989 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { |
| 968 | - // A Matroska file goes straight to symphonia, whose `mkv` reader is the | 990 | + // A Matroska file goes to symphonia, whose `mkv` reader is the one thing |
| 969 | - // one thing here that reads its packets -- neither mp4 reader can open | 991 | + // here that reads its packets -- neither mp4 reader can open the file at |
| 970 | - // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia | 992 | + // all -- except for the two codecs symphonia has no decoder for at any |
| 971 | - // has no such decoder at any version) leaves the source the silent one | 993 | + // version and this project does: AC-3 and E-AC-3 are handed to the Dolby |
| 972 | - // it always was, which `AudioSession::unsupported` puts into words, | 994 | + // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither |
| 973 | - // rather than failing the import of a file whose picture is fine. | 995 | + // one can decode (Opus, DTS) leaves the source the silent one it always |
| 996 | + // was, which `AudioSession::unsupported` puts into words, rather than | ||
| 997 | + // failing the import of a file whose picture is fine -- and so does an | ||
| 998 | + // AC-3 track that will not open, a laced block say. | ||
| 974 | if crate::demux::is_matroska(path) { | 999 | if crate::demux::is_matroska(path) { |
| 975 | if stream > 0 { | 1000 | if stream > 0 { |
| 976 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | 1001 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); |
| 977 | } | 1002 | } |
| 1003 | + match MkvAc3Track::open(path) { | ||
| 1004 | + Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), | ||
| 1005 | + Ok(None) => {} | ||
| 1006 | + // Named on the way past for the same reason symphonia's failure | ||
| 1007 | + // is, below: an AC-3 track that broke is a bug, not a codec we | ||
| 1008 | + // never had. | ||
| 1009 | + Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), | ||
| 1010 | + } | ||
| 978 | // Logged on the way past: "silent" here covers both a codec nothing | 1011 | // Logged on the way past: "silent" here covers both a codec nothing |
| 979 | // decodes and a track that genuinely broke, and only the second is a | 1012 | // decodes and a track that genuinely broke, and only the second is a |
| 980 | // bug -- with no trace at all it reaches the user as a lane that | 1013 | // bug -- with no trace at all it reaches the user as a lane that |
| @@ -1015,6 +1048,7 @@ impl Track { | |||
| 1015 | match self { | 1048 | match self { |
| 1016 | Self::Aac(t) => t.sample_rate, | 1049 | Self::Aac(t) => t.sample_rate, |
| 1017 | Self::Ac3(t) => t.sample_rate, | 1050 | Self::Ac3(t) => t.sample_rate, |
| 1051 | + Self::Mkv(t) => t.sample_rate, | ||
| 1018 | Self::Sym(t) => t.sample_rate, | 1052 | Self::Sym(t) => t.sample_rate, |
| 1019 | } | 1053 | } |
| 1020 | } | 1054 | } |
| @@ -1030,6 +1064,11 @@ impl Track { | |||
| 1030 | 1 | 2 => Ok(t.channels), | 1064 | 1 | 2 => Ok(t.channels), |
| 1031 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | 1065 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| 1032 | }, | 1066 | }, |
| 1067 | + // Downmixed by the very same decoder, out of a Matroska file. | ||
| 1068 | + Self::Mkv(t) => match t.channels { | ||
| 1069 | + 1 | 2 => Ok(t.channels), | ||
| 1070 | + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | ||
| 1071 | + }, | ||
| 1033 | Self::Sym(t) => match t.channels { | 1072 | Self::Sym(t) => match t.channels { |
| 1034 | 1 | 2 => Ok(t.channels), | 1073 | 1 | 2 => Ok(t.channels), |
| 1035 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | 1074 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| @@ -1042,6 +1081,7 @@ impl Track { | |||
| 1042 | match self { | 1081 | match self { |
| 1043 | Self::Aac(t) => t.total_samples, | 1082 | Self::Aac(t) => t.total_samples, |
| 1044 | Self::Ac3(t) => t.total_samples, | 1083 | Self::Ac3(t) => t.total_samples, |
| 1084 | + Self::Mkv(t) => t.total_samples, | ||
| 1045 | Self::Sym(t) => t.total_samples, | 1085 | Self::Sym(t) => t.total_samples, |
| 1046 | } | 1086 | } |
| 1047 | } | 1087 | } |
| @@ -1051,6 +1091,9 @@ impl Track { | |||
| 1051 | match self { | 1091 | match self { |
| 1052 | Self::Aac(t) => t.priming, | 1092 | Self::Aac(t) => t.priming, |
| 1053 | Self::Ac3(t) => t.priming, | 1093 | Self::Ac3(t) => t.priming, |
| 1094 | + // Matroska writes no edit list and AC-3 has no encoder delay: | ||
| 1095 | + // block 0 is sample 0. | ||
| 1096 | + Self::Mkv(_) => 0, | ||
| 1054 | Self::Sym(t) => t.priming, | 1097 | Self::Sym(t) => t.priming, |
| 1055 | } | 1098 | } |
| 1056 | } | 1099 | } |
| @@ -1061,6 +1104,7 @@ impl Track { | |||
| 1061 | match self { | 1104 | match self { |
| 1062 | Self::Aac(t) => t.segment(source, start_secs, end_secs), | 1105 | Self::Aac(t) => t.segment(source, start_secs, end_secs), |
| 1063 | Self::Ac3(t) => t.segment(source, start_secs, end_secs), | 1106 | Self::Ac3(t) => t.segment(source, start_secs, end_secs), |
| 1107 | + Self::Mkv(t) => t.segment(source, start_secs, end_secs), | ||
| 1064 | Self::Sym(t) => { | 1108 | Self::Sym(t) => { |
| 1065 | let media_target = t.media(start_secs); | 1109 | let media_target = t.media(start_secs); |
| 1066 | Segment { | 1110 | Segment { |
| @@ -1082,7 +1126,10 @@ impl Track { | |||
| 1082 | AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; | 1126 | AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; |
| 1083 | } | 1127 | } |
| 1084 | Self::Ac3(t) => { | 1128 | Self::Ac3(t) => { |
| 1085 | - ac3_decoder(t.requested)?; | 1129 | + ac3_decoder("ac3", t.requested)?; |
| 1130 | + } | ||
| 1131 | + Self::Mkv(t) => { | ||
| 1132 | + ac3_decoder(t.mkv.codec, t.requested)?; | ||
| 1086 | } | 1133 | } |
| 1087 | Self::Sym(t) => { | 1134 | Self::Sym(t) => { |
| 1088 | t.decoder()?; | 1135 | t.decoder()?; |
| @@ -1335,9 +1382,9 @@ impl Ac3Track { | |||
| 1335 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? | 1382 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? |
| 1336 | .nfchans; | 1383 | .nfchans; |
| 1337 | let requested = (nfchans > 1).then_some(2); | 1384 | let requested = (nfchans > 1).then_some(2); |
| 1338 | - let mut decoder = ac3_decoder(requested)?; | 1385 | + let mut decoder = ac3_decoder("ac3", requested)?; |
| 1339 | let channels = decode_ac3(&mut decoder, &first.bytes)? | 1386 | let channels = decode_ac3(&mut decoder, &first.bytes)? |
| 1340 | - .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16) | 1387 | + .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) |
| 1341 | .filter(|&c| c > 0) | 1388 | .filter(|&c| c > 0) |
| 1342 | .ok_or("the first AC-3 syncframe decoded to nothing")?; | 1389 | .ok_or("the first AC-3 syncframe decoded to nothing")?; |
| 1343 | 1390 | ||
| @@ -1382,6 +1429,101 @@ impl Ac3Track { | |||
| 1382 | } | 1429 | } |
| 1383 | } | 1430 | } |
| 1384 | 1431 | ||
| 1432 | +/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same | ||
| 1433 | +/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of | ||
| 1434 | +/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux | ||
| 1435 | +/// therefore arrives on the timeline as an ordinary stereo source, exactly as | ||
| 1436 | +/// the mp4 path's does, and the mono passthrough quirk is the same one. | ||
| 1437 | +/// | ||
| 1438 | +/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side | ||
| 1439 | +/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): | ||
| 1440 | +/// one block is one packet, one packet is one syncframe, and a seek lands on | ||
| 1441 | +/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in | ||
| 1442 | +/// front of it. | ||
| 1443 | +struct MkvAc3Track { | ||
| 1444 | + mkv: crate::demux::MkvAudio, | ||
| 1445 | + sample_rate: u32, | ||
| 1446 | + /// What comes *out* of the decoder, measured on the first frame — 2 for | ||
| 1447 | + /// anything from stereo to 5.1, 1 for a mono track (see `requested`). | ||
| 1448 | + channels: u16, | ||
| 1449 | + total_samples: Option<u64>, | ||
| 1450 | + /// What the decoder is asked to hand out, from this track's own layout: | ||
| 1451 | + /// `Some(2)` for anything with more than one front channel, `None` for a | ||
| 1452 | + /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's. | ||
| 1453 | + requested: Option<u16>, | ||
| 1454 | +} | ||
| 1455 | + | ||
| 1456 | +impl MkvAc3Track { | ||
| 1457 | + /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 — | ||
| 1458 | + /// that mkv is the silent source it has always been. An `Err` is a track | ||
| 1459 | + /// that is one and could not be read, which | ||
| 1460 | + /// [`AudioSession::unsupported`] quotes back to the user. | ||
| 1461 | + fn open(path: &Path) -> crate::Result<Option<Self>> { | ||
| 1462 | + let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else { | ||
| 1463 | + return Ok(None); | ||
| 1464 | + }; | ||
| 1465 | + let first = mkv | ||
| 1466 | + .frame(0)? | ||
| 1467 | + .ok_or("the AC-3 track of this Matroska file has no blocks")?; | ||
| 1468 | + // Rate and layout come out of the bit stream, which is where AC-3 | ||
| 1469 | + // states them: Matroska's `Audio` element repeats them and muxers get | ||
| 1470 | + // that wrong often enough that the frame is the better source. | ||
| 1471 | + // `nfchans` excludes the LFE in both syntaxes, which is what the | ||
| 1472 | + // downmix decision wants. | ||
| 1473 | + let (sample_rate, nfchans) = if mkv.codec == "eac3" { | ||
| 1474 | + // Annex E's BSI starts right after the 16-bit syncword. | ||
| 1475 | + let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) | ||
| 1476 | + .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; | ||
| 1477 | + (bsi.sample_rate, bsi.nfchans) | ||
| 1478 | + } else { | ||
| 1479 | + let sync = oxideav_ac3::syncinfo::parse(&first) | ||
| 1480 | + .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; | ||
| 1481 | + let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) | ||
| 1482 | + .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; | ||
| 1483 | + (sync.sample_rate, bsi.nfchans) | ||
| 1484 | + }; | ||
| 1485 | + let requested = (nfchans > 1).then_some(2); | ||
| 1486 | + let mut decoder = ac3_decoder(mkv.codec, requested)?; | ||
| 1487 | + let (pcm, samples) = | ||
| 1488 | + decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; | ||
| 1489 | + let channels = (pcm.len() as u64 / samples.max(1)) as u16; | ||
| 1490 | + if channels == 0 { | ||
| 1491 | + return Err("the first AC-3 syncframe decoded to nothing".into()); | ||
| 1492 | + } | ||
| 1493 | + // The track runs to the last block's timestamp plus that block's own | ||
| 1494 | + // frame -- a container that indexes nothing states no duration either, | ||
| 1495 | + // and every frame of a syncframe stream is the same length. | ||
| 1496 | + let last = mkv.secs(mkv.blocks().saturating_sub(1)); | ||
| 1497 | + Ok(Some(Self { | ||
| 1498 | + total_samples: Some((last * f64::from(sample_rate)) as u64 + samples), | ||
| 1499 | + sample_rate, | ||
| 1500 | + channels, | ||
| 1501 | + requested, | ||
| 1502 | + mkv, | ||
| 1503 | + })) | ||
| 1504 | + } | ||
| 1505 | + | ||
| 1506 | + /// `secs` on this source's timeline into media samples. No priming: the | ||
| 1507 | + /// container carries no edit list and AC-3 no encoder delay. | ||
| 1508 | + fn media(&self, secs: f64) -> u64 { | ||
| 1509 | + (secs.max(0.0) * f64::from(self.sample_rate)) as u64 | ||
| 1510 | + } | ||
| 1511 | + | ||
| 1512 | + /// One `[start, end)` window, resolved to blocks and media samples — | ||
| 1513 | + /// [`Ac3Track::segment`] against block timestamps instead of an `stts`. | ||
| 1514 | + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { | ||
| 1515 | + let media_target = self.media(start_secs); | ||
| 1516 | + let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize); | ||
| 1517 | + Segment { | ||
| 1518 | + source: Some(source), | ||
| 1519 | + start_id: start_id as u32, | ||
| 1520 | + start_pos: self.media(self.mkv.secs(start_id)), | ||
| 1521 | + media_target, | ||
| 1522 | + media_end: self.media(end_secs).max(media_target), | ||
| 1523 | + } | ||
| 1524 | + } | ||
| 1525 | +} | ||
| 1526 | + | ||
| 1385 | /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own | 1527 | /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own |
| 1386 | /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a | 1528 | /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a |
| 1387 | /// 5.1 track at all. Fresh per segment for the same reason every other decoder | 1529 | /// 5.1 track at all. Fresh per segment for the same reason every other decoder |
| @@ -1392,32 +1534,47 @@ impl Ac3Track { | |||
| 1392 | /// mono track asks for no downmix at all and stays the mono source it is. The | 1534 | /// mono track asks for no downmix at all and stays the mono source it is. The |
| 1393 | /// upgrade path is `Some(2)` unconditionally once the library duplicates the | 1535 | /// upgrade path is `Some(2)` unconditionally once the library duplicates the |
| 1394 | /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. | 1536 | /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. |
| 1395 | -fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | 1537 | +/// |
| 1538 | +/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers | ||
| 1539 | +/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct | ||
| 1540 | +/// behind both dispatches per packet on `bsid` in any case, so what this picks | ||
| 1541 | +/// is the capability set, not the syntax. | ||
| 1542 | +fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | ||
| 1396 | let mut registry = CodecRegistry::new(); | 1543 | let mut registry = CodecRegistry::new(); |
| 1397 | oxideav_ac3::register_codecs(&mut registry); | 1544 | oxideav_ac3::register_codecs(&mut registry); |
| 1398 | - let mut params = CodecParameters::audio(CodecId::new("ac3")); | 1545 | + let mut params = CodecParameters::audio(CodecId::new(codec)); |
| 1399 | params.channels = channels; | 1546 | params.channels = channels; |
| 1400 | registry | 1547 | registry |
| 1401 | .first_decoder(¶ms) | 1548 | .first_decoder(¶ms) |
| 1402 | .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) | 1549 | .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) |
| 1403 | } | 1550 | } |
| 1404 | 1551 | ||
| 1405 | -/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the | 1552 | +/// One syncframe in, one buffer of interleaved f32 out and the frames per |
| 1406 | -/// decoder wants more input before it can hand a frame back, which is not an | 1553 | +/// channel it holds. `Ok(None)` when the decoder wants more input before it can |
| 1407 | -/// error. The library speaks S16 little-endian; `/32768` is the whole | 1554 | +/// hand a frame back, which is not an error. The library speaks S16 |
| 1408 | -/// conversion, and it lands in the `[-1, 1)` every other reader here emits. | 1555 | +/// little-endian; `/32768` is the whole conversion, and it lands in the |
| 1409 | -fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> { | 1556 | +/// `[-1, 1)` every other reader here emits. |
| 1557 | +/// | ||
| 1558 | +/// The frame count comes back beside the samples because an E-AC-3 frame is not | ||
| 1559 | +/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 | ||
| 1560 | +/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the | ||
| 1561 | +/// channel count and every media position after it out. | ||
| 1562 | +fn decode_ac3( | ||
| 1563 | + decoder: &mut Box<dyn Decoder>, | ||
| 1564 | + bytes: &[u8], | ||
| 1565 | +) -> crate::Result<Option<(Vec<f32>, u64)>> { | ||
| 1410 | let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); | 1566 | let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); |
| 1411 | decoder | 1567 | decoder |
| 1412 | .send_packet(&packet) | 1568 | .send_packet(&packet) |
| 1413 | .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; | 1569 | .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; |
| 1414 | match decoder.receive_frame() { | 1570 | match decoder.receive_frame() { |
| 1415 | - Ok(Frame::Audio(audio)) => Ok(Some( | 1571 | + Ok(Frame::Audio(audio)) => Ok(Some(( |
| 1416 | audio.data[0] | 1572 | audio.data[0] |
| 1417 | .chunks_exact(2) | 1573 | .chunks_exact(2) |
| 1418 | .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) | 1574 | .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) |
| 1419 | .collect(), | 1575 | .collect(), |
| 1420 | - )), | 1576 | + u64::from(audio.samples), |
| 1577 | + ))), | ||
| 1421 | Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), | 1578 | Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), |
| 1422 | Err(oxideav_core::Error::NeedMore) => Ok(None), | 1579 | Err(oxideav_core::Error::NeedMore) => Ok(None), |
| 1423 | Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), | 1580 | Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), |
| @@ -2035,6 +2192,21 @@ fn run(mut w: Worker) { | |||
| 2035 | } | 2192 | } |
| 2036 | continue; | 2193 | continue; |
| 2037 | } | 2194 | } |
| 2195 | + Track::Mkv(track) => { | ||
| 2196 | + if !run_mkv_ac3( | ||
| 2197 | + track, | ||
| 2198 | + seg, | ||
| 2199 | + eq.as_mut(), | ||
| 2200 | + speed, | ||
| 2201 | + channels, | ||
| 2202 | + &mut timeline, | ||
| 2203 | + &w.tx, | ||
| 2204 | + ) || !settle(speed, channels, &mut timeline, &w.tx) | ||
| 2205 | + { | ||
| 2206 | + return; // consumer went away | ||
| 2207 | + } | ||
| 2208 | + continue; | ||
| 2209 | + } | ||
| 2038 | Track::Ac3(track) => { | 2210 | Track::Ac3(track) => { |
| 2039 | if !run_ac3( | 2211 | if !run_ac3( |
| 2040 | track, | 2212 | track, |
| @@ -2200,7 +2372,7 @@ fn run_ac3( | |||
| 2200 | timeline: &mut u64, | 2372 | timeline: &mut u64, |
| 2201 | tx: &SyncSender<AudioChunk>, | 2373 | tx: &SyncSender<AudioChunk>, |
| 2202 | ) -> bool { | 2374 | ) -> bool { |
| 2203 | - let mut decoder = match ac3_decoder(track.requested) { | 2375 | + let mut decoder = match ac3_decoder("ac3", track.requested) { |
| 2204 | Ok(decoder) => decoder, | 2376 | Ok(decoder) => decoder, |
| 2205 | Err(e) => { | 2377 | Err(e) => { |
| 2206 | eprintln!("audio decoder init failed: {e}"); | 2378 | eprintln!("audio decoder init failed: {e}"); |
| @@ -2209,7 +2381,6 @@ fn run_ac3( | |||
| 2209 | }; | 2381 | }; |
| 2210 | let mut pos = seg.start_pos; | 2382 | let mut pos = seg.start_pos; |
| 2211 | for id in seg.start_id..=track.sample_count { | 2383 | for id in seg.start_id..=track.sample_count { |
| 2212 | - let mut interleaved; | ||
| 2213 | if pos >= seg.media_end { | 2384 | if pos >= seg.media_end { |
| 2214 | return true; // segment done, on to the next one | 2385 | return true; // segment done, on to the next one |
| 2215 | } | 2386 | } |
| @@ -2221,15 +2392,75 @@ fn run_ac3( | |||
| 2221 | return true; | 2392 | return true; |
| 2222 | } | 2393 | } |
| 2223 | }; | 2394 | }; |
| 2224 | - match decode_ac3(&mut decoder, &sample.bytes) { | 2395 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) { |
| 2225 | - Ok(Some(pcm)) => interleaved = pcm, | 2396 | + Ok(Some(decoded)) => decoded, |
| 2226 | Ok(None) => continue, // the decoder wants another frame first | 2397 | Ok(None) => continue, // the decoder wants another frame first |
| 2227 | Err(e) => { | 2398 | Err(e) => { |
| 2228 | eprintln!("audio decode error at sample {id}: {e}"); | 2399 | eprintln!("audio decode error at sample {id}: {e}"); |
| 2229 | return true; | 2400 | return true; |
| 2230 | } | 2401 | } |
| 2402 | + }; | ||
| 2403 | + let next = pos + samples; | ||
| 2404 | + if !emit( | ||
| 2405 | + &mut interleaved, | ||
| 2406 | + channels, | ||
| 2407 | + seg, | ||
| 2408 | + eq.as_deref_mut(), | ||
| 2409 | + speed.as_mut(), | ||
| 2410 | + pos, | ||
| 2411 | + next, | ||
| 2412 | + timeline, | ||
| 2413 | + tx, | ||
| 2414 | + ) { | ||
| 2415 | + return false; | ||
| 2416 | + } | ||
| 2417 | + pos = next; | ||
| 2231 | } | 2418 | } |
| 2232 | - let next = pos + (interleaved.len() / channels) as u64; | 2419 | + true |
| 2420 | +} | ||
| 2421 | + | ||
| 2422 | +/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks | ||
| 2423 | +/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the | ||
| 2424 | +/// stereo downmix are the same ones; only where a packet comes from differs. | ||
| 2425 | +/// `false` means the consumer went away. | ||
| 2426 | +fn run_mkv_ac3( | ||
| 2427 | + track: &mut MkvAc3Track, | ||
| 2428 | + seg: &Segment, | ||
| 2429 | + mut eq: Option<&mut EqState>, | ||
| 2430 | + speed: &mut Option<Resample>, | ||
| 2431 | + channels: usize, | ||
| 2432 | + timeline: &mut u64, | ||
| 2433 | + tx: &SyncSender<AudioChunk>, | ||
| 2434 | +) -> bool { | ||
| 2435 | + let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { | ||
| 2436 | + Ok(decoder) => decoder, | ||
| 2437 | + Err(e) => { | ||
| 2438 | + eprintln!("audio decoder init failed: {e}"); | ||
| 2439 | + return true; | ||
| 2440 | + } | ||
| 2441 | + }; | ||
| 2442 | + let mut pos = seg.start_pos; | ||
| 2443 | + for id in seg.start_id as usize.. { | ||
| 2444 | + if pos >= seg.media_end { | ||
| 2445 | + return true; // segment done, on to the next one | ||
| 2446 | + } | ||
| 2447 | + let block = match track.mkv.frame(id) { | ||
| 2448 | + Ok(Some(bytes)) => bytes, | ||
| 2449 | + Ok(None) => return true, // end of the track | ||
| 2450 | + Err(e) => { | ||
| 2451 | + eprintln!("audio demux error at block {id}: {e}"); | ||
| 2452 | + return true; | ||
| 2453 | + } | ||
| 2454 | + }; | ||
| 2455 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) { | ||
| 2456 | + Ok(Some(decoded)) => decoded, | ||
| 2457 | + Ok(None) => continue, // the decoder wants another frame first | ||
| 2458 | + Err(e) => { | ||
| 2459 | + eprintln!("audio decode error at block {id}: {e}"); | ||
| 2460 | + return true; | ||
| 2461 | + } | ||
| 2462 | + }; | ||
| 2463 | + let next = pos + samples; | ||
| 2233 | if !emit( | 2464 | if !emit( |
| 2234 | &mut interleaved, | 2465 | &mut interleaved, |
| 2235 | channels, | 2466 | channels, |
crates/engine/src/demux.rsmodified+122 -21
| @@ -329,15 +329,18 @@ impl Mp4Demuxer { | |||
| 329 | } | 329 | } |
| 330 | } | 330 | } |
| 331 | 331 | ||
| 332 | -/// One Matroska block of the video track: where its bytes are and whether a | 332 | +/// One Matroska block of an indexed track: where its bytes are, whether a |
| 333 | -/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7 | 333 | +/// decoder may start on it, and when it is presented (in `TimestampScale` |
| 334 | -/// MB of index -- the price of knowing the frame count and the sync points of a | 334 | +/// ticks, which is what a sound track seeks against -- Matroska indexes no |
| 335 | +/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of | ||
| 336 | +/// index -- the price of knowing the frame count and the sync points of a | ||
| 335 | /// container that indexes neither. | 337 | /// container that indexes neither. |
| 336 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 338 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 337 | struct Block { | 339 | struct Block { |
| 338 | at: u64, | 340 | at: u64, |
| 339 | len: usize, | 341 | len: usize, |
| 340 | key: bool, | 342 | key: bool, |
| 343 | + ts: i64, | ||
| 341 | } | 344 | } |
| 342 | 345 | ||
| 343 | /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). | 346 | /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). |
| @@ -378,7 +381,7 @@ impl MkvDemuxer { | |||
| 378 | let mut file = File::open(path)?; | 381 | let mut file = File::open(path)?; |
| 379 | let end = file.metadata()?.len(); | 382 | let end = file.metadata()?.len(); |
| 380 | let segment = mkv_segment(&mut file, end)?; | 383 | let segment = mkv_segment(&mut file, end)?; |
| 381 | - let (video, _, other) = mkv_tracks(&mut file, segment)?; | 384 | + let (video, _, other, _) = mkv_tracks(&mut file, segment)?; |
| 382 | let video = match video { | 385 | let video = match video { |
| 383 | Some(video) => video, | 386 | Some(video) => video, |
| 384 | // Named, because "no video track" is a lie about a file that has one | 387 | // Named, because "no video track" is a lie about a file that has one |
| @@ -487,13 +490,99 @@ impl MkvDemuxer { | |||
| 487 | 490 | ||
| 488 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or | 491 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or |
| 489 | /// `None` for a Matroska file with no sound at all. Header only, and only worth | 492 | /// `None` for a Matroska file with no sound at all. Header only, and only worth |
| 490 | -/// calling once a session has come up silent: no audio track of a Matroska file | 493 | +/// calling once a session has come up silent: a Matroska file's sound is read |
| 491 | -/// is decoded yet, so this exists to say which one is being left out. | 494 | +/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and |
| 495 | +/// this exists to say which codec neither of them took. | ||
| 492 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { | 496 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { |
| 493 | let mut file = File::open(path)?; | 497 | let mut file = File::open(path)?; |
| 494 | let end = file.metadata()?.len(); | 498 | let end = file.metadata()?.len(); |
| 495 | let segment = mkv_segment(&mut file, end)?; | 499 | let segment = mkv_segment(&mut file, end)?; |
| 496 | - 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 | + } | ||
| 497 | } | 586 | } |
| 498 | 587 | ||
| 499 | /// What the `Tracks` element says about the video track. | 588 | /// What the `Tracks` element says about the video track. |
| @@ -543,17 +632,19 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { | |||
| 543 | Err("no Segment element: not a Matroska file".into()) | 632 | Err("no Segment element: not a Matroska file".into()) |
| 544 | } | 633 | } |
| 545 | 634 | ||
| 546 | -/// The video track of `segment`, the codec id of its first audio track, and the | 635 | +/// The video track of `segment`, the number and codec id of its first audio |
| 547 | -/// codec id of a video track this cannot read -- the last two are what tell a | 636 | +/// track, the codec id of a video track this cannot read, and the segment's |
| 548 | -/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`]) | 637 | +/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a |
| 549 | -/// or refuses to open at all. | 638 | +/// sound track from; it and the other codec id are what tell a user why a file |
| 639 | +/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to | ||
| 640 | +/// open at all. | ||
| 550 | /// | 641 | /// |
| 551 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful | 642 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful |
| 552 | /// of seeks whatever the file weighs. | 643 | /// of seeks whatever the file weighs. |
| 553 | fn mkv_tracks( | 644 | fn mkv_tracks( |
| 554 | file: &mut File, | 645 | file: &mut File, |
| 555 | segment: (u64, u64), | 646 | segment: (u64, u64), |
| 556 | -) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> { | 647 | +) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> { |
| 557 | let (mut video, mut audio, mut other) = (None, None, None); | 648 | let (mut video, mut audio, mut other) = (None, None, None); |
| 558 | let mut timestamp_scale = 1_000_000; | 649 | let mut timestamp_scale = 1_000_000; |
| 559 | let mut at = segment.0; | 650 | let mut at = segment.0; |
| @@ -576,7 +667,9 @@ fn mkv_tracks( | |||
| 576 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { | 667 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { |
| 577 | MkvEntry::Video(track) if video.is_none() => video = Some(track), | 668 | MkvEntry::Video(track) if video.is_none() => video = Some(track), |
| 578 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), | 669 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), |
| 579 | - 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 | + } | ||
| 580 | _ => {} | 673 | _ => {} |
| 581 | } | 674 | } |
| 582 | } | 675 | } |
| @@ -587,7 +680,7 @@ fn mkv_tracks( | |||
| 587 | } | 680 | } |
| 588 | at = stop; | 681 | at = stop; |
| 589 | } | 682 | } |
| 590 | - Ok((video, audio, other)) | 683 | + Ok((video, audio, other, timestamp_scale)) |
| 591 | } | 684 | } |
| 592 | 685 | ||
| 593 | /// What one `TrackEntry` turned out to be. | 686 | /// What one `TrackEntry` turned out to be. |
| @@ -595,8 +688,9 @@ enum MkvEntry { | |||
| 595 | Video(MkvVideo), | 688 | Video(MkvVideo), |
| 596 | /// A video track in a codec this does not read, by the name it gives itself. | 689 | /// A video track in a codec this does not read, by the name it gives itself. |
| 597 | OtherVideo(String), | 690 | OtherVideo(String), |
| 598 | - /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...). | 691 | + /// An audio track: its track number, which is what [`MkvAudio`] indexes the |
| 599 | - Audio(String), | 692 | + /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). |
| 693 | + Audio(u64, String), | ||
| 600 | /// Subtitles, buttons: nobody's here. | 694 | /// Subtitles, buttons: nobody's here. |
| 601 | Other, | 695 | Other, |
| 602 | } | 696 | } |
| @@ -658,7 +752,7 @@ fn mkv_track_entry( | |||
| 658 | (Codec::H264, nal_length, sets, 8) | 752 | (Codec::H264, nal_length, sets, 8) |
| 659 | } | 753 | } |
| 660 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), | 754 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), |
| 661 | - (2, _) => return Ok(MkvEntry::Audio(codec)), | 755 | + (2, _) => return Ok(MkvEntry::Audio(number, codec)), |
| 662 | _ => return Ok(MkvEntry::Other), | 756 | _ => return Ok(MkvEntry::Other), |
| 663 | }; | 757 | }; |
| 664 | Ok(MkvEntry::Video(MkvVideo { | 758 | Ok(MkvEntry::Video(MkvVideo { |
| @@ -807,11 +901,17 @@ fn mkv_blocks( | |||
| 807 | if block.number != number { | 901 | if block.number != number { |
| 808 | continue; | 902 | continue; |
| 809 | } | 903 | } |
| 810 | - // Lacing packs several frames into one block. Audio muxers use it, | 904 | + // Lacing packs several frames into one block, behind a header of |
| 811 | - // video ones do not, and guessing at frame boundaries inside a laced | 905 | + // frame sizes this does not read. Video muxers write none; an audio |
| 812 | - // block is not something to do silently. | 906 | + // muxer may, and guessing at frame boundaries inside a laced block |
| 907 | + // is not something to do silently. | ||
| 908 | + // | ||
| 909 | + // ponytail: a laced audio track is refused by name rather than | ||
| 910 | + // played. The upgrade path is the three lace headers of the spec | ||
| 911 | + // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg, | ||
| 912 | + // which writes the fixtures and most remuxes, laces nothing. | ||
| 813 | if block.flags & 0x06 != 0 { | 913 | if block.flags & 0x06 != 0 { |
| 814 | - return Err("laced video blocks are not supported".into()); | 914 | + return Err("laced Matroska blocks are not supported".into()); |
| 815 | } | 915 | } |
| 816 | let ts = cluster_ts + i64::from(block.rel); | 916 | let ts = cluster_ts + i64::from(block.rel); |
| 817 | span = Some(match span { | 917 | span = Some(match span { |
| @@ -822,6 +922,7 @@ fn mkv_blocks( | |||
| 822 | at: block.at, | 922 | at: block.at, |
| 823 | len: block.len, | 923 | len: block.len, |
| 824 | key, | 924 | key, |
| 925 | + ts, | ||
| 825 | }); | 926 | }); |
| 826 | } | 927 | } |
| 827 | } | 928 | } |
crates/engine/tests/audio_decode.rsmodified+97 -0
| @@ -160,6 +160,103 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { | |||
| 160 | } | 160 | } |
| 161 | } | 161 | } |
| 162 | 162 | ||
| 163 | +/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and | ||
| 164 | +/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" | ||
| 165 | +/// refusal used to fire on -- both come out of the blocks, both arrive as the | ||
| 166 | +/// stereo the §7.8 downmix hands the timeline, and neither owes the session an | ||
| 167 | +/// excuse any more. | ||
| 168 | +#[test] | ||
| 169 | +fn matroska_ac3_and_eac3_decode_out_of_the_blocks() { | ||
| 170 | + for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] { | ||
| 171 | + let path = asset(name); | ||
| 172 | + let (meta, rx) = AudioSession::open(&path) | ||
| 173 | + .expect("open") | ||
| 174 | + .expect("Matroska AC-3 decodes now"); | ||
| 175 | + assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}"); | ||
| 176 | + let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 177 | + let secs = (samples.len() / 2) as f64 / 48000.0; | ||
| 178 | + assert!( | ||
| 179 | + (1.9..2.1).contains(&secs), | ||
| 180 | + "{name} is two seconds, decoded {secs:.3}s" | ||
| 181 | + ); | ||
| 182 | + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() | ||
| 183 | + / samples.len() as f64) | ||
| 184 | + .sqrt(); | ||
| 185 | + assert!( | ||
| 186 | + (0.005..0.75).contains(&rms), | ||
| 187 | + "{name}: RMS {rms:.6} is not a sine at a sane level" | ||
| 188 | + ); | ||
| 189 | + assert!( | ||
| 190 | + samples.iter().all(|s| s.abs() <= 1.0), | ||
| 191 | + "{name}: the decode must not leave the device's range" | ||
| 192 | + ); | ||
| 193 | + // The user-facing half: the session comes up with sound and no notice, | ||
| 194 | + // and the file's one audio stream is offered by the name it is in. | ||
| 195 | + let session = engine::PlaybackSession::open(&path).expect("open for playback"); | ||
| 196 | + assert_eq!( | ||
| 197 | + session.audio_disabled_reason(), | ||
| 198 | + None, | ||
| 199 | + "{name}: a track that decodes owes no excuse" | ||
| 200 | + ); | ||
| 201 | + let streams = AudioSession::probe_streams(&path).expect("streams"); | ||
| 202 | + assert_eq!(streams.len(), 1, "{name}: one audio track, one row"); | ||
| 203 | + assert_eq!(streams[0].codec, codec, "{name}"); | ||
| 204 | + assert!(streams[0].decodable, "{name}"); | ||
| 205 | + assert_eq!( | ||
| 206 | + AudioSession::unsupported(&path).expect("unsupported"), | ||
| 207 | + None, | ||
| 208 | + "{name}: nothing to excuse when it plays" | ||
| 209 | + ); | ||
| 210 | + } | ||
| 211 | + // The invariant, stated as an assert: the AAC track of a Matroska file is | ||
| 212 | + // still symphonia's, listed and decoded exactly as it was. | ||
| 213 | + let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams"); | ||
| 214 | + assert_eq!(streams.len(), 1); | ||
| 215 | + assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this"); | ||
| 216 | + assert!( | ||
| 217 | + AudioSession::open(asset("test_av1.mkv")) | ||
| 218 | + .expect("open") | ||
| 219 | + .is_some(), | ||
| 220 | + "AAC in an mkv still decodes" | ||
| 221 | + ); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block | ||
| 225 | +/// a decode starts on is found by the blocks' own timestamps -- and getting that | ||
| 226 | +/// wrong is a tail that is the wrong length or lands in the wrong place. It is | ||
| 227 | +/// the same check `audio_seek` makes of the mp4 path, on the container that has | ||
| 228 | +/// no sample table. | ||
| 229 | +#[test] | ||
| 230 | +fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() { | ||
| 231 | + let path = asset("test_eac3.mkv"); | ||
| 232 | + let full: Vec<f32> = AudioSession::open(&path) | ||
| 233 | + .expect("open") | ||
| 234 | + .expect("audio") | ||
| 235 | + .1 | ||
| 236 | + .into_iter() | ||
| 237 | + .flat_map(|c| c.samples) | ||
| 238 | + .collect(); | ||
| 239 | + let start = 48_000u64; // one second in, in frames per channel | ||
| 240 | + let mut next = start; | ||
| 241 | + let mut tail = Vec::new(); | ||
| 242 | + for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 { | ||
| 243 | + assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek"); | ||
| 244 | + next += (chunk.samples.len() / 2) as u64; | ||
| 245 | + tail.extend(chunk.samples); | ||
| 246 | + } | ||
| 247 | + let want = &full[start as usize * 2..]; | ||
| 248 | + assert_eq!(tail.len(), want.len(), "the seeked run is a different length"); | ||
| 249 | + let diff = tail | ||
| 250 | + .iter() | ||
| 251 | + .zip(want) | ||
| 252 | + .map(|(a, b)| (a - b).abs()) | ||
| 253 | + .fold(0.0f32, f32::max); | ||
| 254 | + // One syncframe of pre-roll is what the 256-sample overlap-add needs, so | ||
| 255 | + // this is exact in practice; the tolerance is for a decoder that carries | ||
| 256 | + // more state than the frame before, not for a wrong block. | ||
| 257 | + assert!(diff < 1e-3, "max abs diff {diff} after the seek"); | ||
| 258 | +} | ||
| 259 | + | ||
| 163 | /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the | 260 | /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the |
| 164 | /// *copy* path names it and hands the export on to the re-encode (which decodes | 261 | /// *copy* path names it and hands the export on to the re-encode (which decodes |
| 165 | /// this very source: the downmix above is what it encodes). Named either way -- | 262 | /// this very source: the downmix above is what it encodes). Named either way -- |
scripts/gen_fixtures.shmodified+21 -2
| @@ -104,8 +104,9 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 104 | # the others so the tests measure the codec and nothing else -- but `-g 30` is | 104 | # the others so the tests measure the codec and nothing else -- but `-g 30` is |
| 105 | # not a preference: it puts a second keyframe at frame 30, which is what the | 105 | # not a preference: it puts a second keyframe at frame 30, which is what the |
| 106 | # sync index and the seek test are checked against. 8-bit Main profile here; the | 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: Matroska audio is not | 107 | +# 10-bit twin is below. Its AAC track is deliberate too: it is the AAC a Matroska |
| 108 | -# wired to the decoder yet, and the notice that says so needs a track to name. | 108 | +# file's sound is read out of through symphonia, beside the AC-3 fixtures further |
| 109 | +# down that no symphonia version decodes. | ||
| 109 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | 110 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ |
| 110 | -f lavfi -i "sine=frequency=440:duration=2" \ | 111 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 111 | -f lavfi -i "sine=frequency=880:duration=2" \ | 112 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| @@ -176,6 +177,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 176 | -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ | 177 | -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ |
| 177 | -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ | 178 | -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ |
| 178 | -c:a aac -b:a 384k assets/test_hevc10.mkv | 179 | -c:a aac -b:a 384k assets/test_hevc10.mkv |
| 180 | +# Matroska sound: the two Dolby codecs that arrive in one and are read straight | ||
| 181 | +# out of its blocks (`demux::MkvAudio`). Stereo AC-3 for the plain syntax and | ||
| 182 | +# **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must | ||
| 183 | +# come down to stereo through the same A/52 7.8 downmix the mp4 path uses. | ||
| 184 | +# 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small | ||
| 185 | +# H.264 picture on purpose: these two are about the sound, and the software | ||
| 186 | +# decoder reads that one, so an audio test needs no VA-API plugin to open a | ||
| 187 | +# session on them. | ||
| 188 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 189 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 190 | + -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ | ||
| 191 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \ | ||
| 192 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 193 | + -c:a ac3 -b:a 192k assets/test_ac3.mkv | ||
| 194 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 195 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 196 | + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 197 | + -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv | ||
| 179 | # Sync fixture: one flash and one beep, at the same instant. Black picture with | 198 | # Sync fixture: one flash and one beep, at the same instant. Black picture with |
| 180 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that | 199 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that |
| 181 | # stretch — so a test can find each of them and say how far apart they came out. | 200 | # stretch — so a test can find each of them and say how far apart they came out. |