🔀 merge(B2): the snap onto C1's actions card — one row generated, one button, one line on the bed
Browse files at this commit5 changed files +1024 -253
- crates/app/src/main.rs +514 -191
- 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/main.rsmodified+514 -191
| @@ -406,6 +406,47 @@ const MENU_ITEMS: [ActionId; 14] = [ | |||
| 406 | ActionId::ToggleMute, | 406 | ActionId::ToggleMute, |
| 407 | ]; | 407 | ]; |
| 408 | 408 | ||
| 409 | +/// One row of the actions card, in the order it lists them: a heading, then | ||
| 410 | +/// every action the registry files under it, then the strokes the modal cards | ||
| 411 | +/// answer themselves. | ||
| 412 | +/// | ||
| 413 | +/// A list rather than a loop inside the render, so the card and | ||
| 414 | +/// `every_action_is_on_the_actions_card` read the *same* order: an action that | ||
| 415 | +/// reaches no row fails a test instead of quietly becoming pointer-unreachable. | ||
| 416 | +enum KeyRow { | ||
| 417 | + Head(keymap::Category), | ||
| 418 | + /// Click its label to do it, click its stroke to change that stroke. | ||
| 419 | + Act(ActionId), | ||
| 420 | + /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may | ||
| 421 | + /// unbind the way out of a card. | ||
| 422 | + Fixed(usize), | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +/// Every action, under its heading, and the card-local strokes beside them. | ||
| 426 | +/// Generated from the registry -- [`ActionId::ALL`] in its own order, under | ||
| 427 | +/// [`keymap::Category::ALL`] -- so an action added there is on the card the | ||
| 428 | +/// moment it exists and there is no second list here to forget. | ||
| 429 | +fn keys_rows() -> Vec<KeyRow> { | ||
| 430 | + let mut rows = Vec::new(); | ||
| 431 | + for category in keymap::Category::ALL { | ||
| 432 | + rows.push(KeyRow::Head(category)); | ||
| 433 | + rows.extend( | ||
| 434 | + ActionId::ALL | ||
| 435 | + .into_iter() | ||
| 436 | + .filter(|a| a.category() == category) | ||
| 437 | + .map(KeyRow::Act), | ||
| 438 | + ); | ||
| 439 | + rows.extend( | ||
| 440 | + keymap::FIXED | ||
| 441 | + .iter() | ||
| 442 | + .enumerate() | ||
| 443 | + .filter(|(_, f)| f.category == category) | ||
| 444 | + .map(|(i, _)| KeyRow::Fixed(i)), | ||
| 445 | + ); | ||
| 446 | + } | ||
| 447 | + rows | ||
| 448 | +} | ||
| 449 | + | ||
| 409 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. | 450 | /// The project resolutions [`Player::cycle_resolution`] offers, largest first. |
| 410 | /// A short list of the sizes people name; the media's own is cycled in beside | 451 | /// A short list of the sizes people name; the media's own is cycled in beside |
| 411 | /// them, which is what makes the trip round come back to where it started. | 452 | /// them, which is what makes the trip round come back to where it started. |
| @@ -1122,6 +1163,31 @@ impl Player { | |||
| 1122 | cx.notify(); | 1163 | cx.notify(); |
| 1123 | } | 1164 | } |
| 1124 | 1165 | ||
| 1166 | + /// Whether the editor can be asked for `action` right now, and why not when | ||
| 1167 | + /// it cannot. `on` is the clip the question is about -- the one a clip menu | ||
| 1168 | + /// was opened on -- and `None` asks about the marked clip instead, which is | ||
| 1169 | + /// what a menu that hangs over no clip in particular means by "this one". | ||
| 1170 | + /// | ||
| 1171 | + /// The player's half of [`enable`]: it reads the state, the table decides. | ||
| 1172 | + fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable { | ||
| 1173 | + let Some(session) = &self.session else { | ||
| 1174 | + return enable(action, Ctx::default()); | ||
| 1175 | + }; | ||
| 1176 | + let clip = on | ||
| 1177 | + .or(self.selected) | ||
| 1178 | + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane))); | ||
| 1179 | + enable( | ||
| 1180 | + action, | ||
| 1181 | + Ctx { | ||
| 1182 | + clip, | ||
| 1183 | + playhead: frame_at(session.now(), self.fps), | ||
| 1184 | + timeline: true, | ||
| 1185 | + clipboard: self.clipboard.is_some(), | ||
| 1186 | + exporting: self.exporting().is_some(), | ||
| 1187 | + }, | ||
| 1188 | + ) | ||
| 1189 | + } | ||
| 1190 | + | ||
| 1125 | /// The one place a clip becomes *the* selected one: a click, a right-click | 1191 | /// The one place a clip becomes *the* selected one: a click, a right-click |
| 1126 | /// that opens the menu, and every selection key go through here, so what a | 1192 | /// that opens the menu, and every selection key go through here, so what a |
| 1127 | /// keyboard marks and what a pointer marks are the same state marked the | 1193 | /// keyboard marks and what a pointer marks are the same state marked the |
| @@ -4724,8 +4790,10 @@ impl Player { | |||
| 4724 | .child(control( | 4790 | .child(control( |
| 4725 | "keys", | 4791 | "keys", |
| 4726 | None, | 4792 | None, |
| 4727 | - "Keys", | 4793 | + "Actions", |
| 4728 | - "show and change the keybindings".to_string(), | 4794 | + // The pointer's way to every action there is, including |
| 4795 | + // the ones no button here has room for. | ||
| 4796 | + "do any action, or change the key that does it".to_string(), | ||
| 4729 | !exporting, | 4797 | !exporting, |
| 4730 | cx.listener(|this, _: &ClickEvent, _, cx| { | 4798 | cx.listener(|this, _: &ClickEvent, _, cx| { |
| 4731 | this.keys_open = !this.keys_open; | 4799 | this.keys_open = !this.keys_open; |
| @@ -4935,83 +5003,115 @@ impl Player { | |||
| 4935 | ctrl: false, | 5003 | ctrl: false, |
| 4936 | } | 5004 | } |
| 4937 | .pretty(); | 5005 | .pretty(); |
| 4938 | - // Every stroke that works, under its heading, and both halves of the | 5006 | + // Every action there is, under its heading, and the strokes the modal |
| 4939 | - // list come from the registry: one row per action -- an action with two | 5007 | + // cards answer to beside them -- `keys_rows` is the whole of the order |
| 4940 | - // strokes reads as one line ("x or delete") and a rebind replaces that | 5008 | + // and every word in it comes off the registry. |
| 4941 | - // whole set -- then the strokes the modal cards answer to, which are | 5009 | + // |
| 4942 | - // shown but not offered, because nothing may unbind the way out. | 5010 | + // A row is two targets, not one: its label *does* the action, which is |
| 5011 | + // the pointer's way to the ones no button carries, and its stroke | ||
| 5012 | + // changes that stroke. An action with two strokes reads as one line | ||
| 5013 | + // ("x or delete") and a rebind replaces that whole set. | ||
| 4943 | let mut rows: Vec<AnyElement> = Vec::new(); | 5014 | let mut rows: Vec<AnyElement> = Vec::new(); |
| 4944 | - for category in keymap::Category::ALL { | 5015 | + let row = || { |
| 4945 | - let actions = ActionId::ALL | 5016 | + div() |
| 4946 | - .into_iter() | 5017 | + .flex() |
| 4947 | - .enumerate() | 5018 | + // The floor, not the height: a row that needed two lines |
| 4948 | - .filter(|(_, a)| a.category() == category); | 5019 | + // would otherwise paint over the one under it. |
| 4949 | - let fixed = keymap::FIXED.iter().filter(|f| f.category == category); | 5020 | + .min_h(px(KEYS_ROW_H)) |
| 4950 | - let mut headed = false; | 5021 | + .items_center() |
| 4951 | - let mut head = |rows: &mut Vec<AnyElement>| { | 5022 | + .justify_between() |
| 4952 | - if !std::mem::replace(&mut headed, true) { | 5023 | + .gap(px(12.)) |
| 4953 | - rows.push( | 5024 | + .px(px(6.)) |
| 4954 | - div() | 5025 | + .rounded(px(3.)) |
| 4955 | - .flex_none() | 5026 | + }; |
| 4956 | - .px(px(6.)) | 5027 | + for (i, key_row) in keys_rows().into_iter().enumerate() { |
| 4957 | - .pt(px(4.)) | 5028 | + rows.push(match key_row { |
| 4958 | - .text_size(px(11.)) | 5029 | + KeyRow::Head(category) => div() |
| 4959 | - .text_color(rgb(INK_DIM)) | 5030 | + .flex_none() |
| 4960 | - .child(category.label()) | 5031 | + .px(px(6.)) |
| 4961 | - .into_any_element(), | 5032 | + .pt(px(4.)) |
| 4962 | - ); | 5033 | + .text_size(px(11.)) |
| 4963 | - } | 5034 | + .text_color(rgb(INK_DIM)) |
| 4964 | - }; | 5035 | + .child(category.label()) |
| 4965 | - for (i, action) in actions { | 5036 | + .into_any_element(), |
| 4966 | - head(&mut rows); | 5037 | + KeyRow::Act(action) => { |
| 4967 | - let capturing = self.rebinding == Some(action); | 5038 | + let capturing = self.rebinding == Some(action); |
| 4968 | - let out = out.clone(); | 5039 | + // Why the label half will not answer, if it will not: the |
| 4969 | - rows.push( | 5040 | + // registry's one answer, the same the clip menu dims by. |
| 4970 | - div() | 5041 | + let refusal = self.enable(action, None); |
| 4971 | - .id(("bind", i)) | 5042 | + let out = out.clone(); |
| 4972 | - .flex() | 5043 | + row() |
| 4973 | - // The floor, not the height: a row that needed two lines | ||
| 4974 | - // would otherwise paint over the one under it. | ||
| 4975 | - .min_h(px(KEYS_ROW_H)) | ||
| 4976 | - .items_center() | ||
| 4977 | - .justify_between() | ||
| 4978 | - .gap(px(12.)) | ||
| 4979 | - .px(px(6.)) | ||
| 4980 | - .rounded(px(3.)) | ||
| 4981 | - .cursor_pointer() | ||
| 4982 | - .hover(|s| s.bg(rgb(HOVER))) | ||
| 4983 | .when(capturing, |d| d.bg(rgb(SELECTED))) | 5044 | .when(capturing, |d| d.bg(rgb(SELECTED))) |
| 4984 | - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 5045 | + .child( |
| 4985 | - this.rebinding = Some(action); | ||
| 4986 | - cx.notify(); | ||
| 4987 | - })) | ||
| 4988 | - .child(action.label()) | ||
| 4989 | - .child(if capturing { | ||
| 4990 | div() | 5046 | div() |
| 4991 | - .text_color(rgb(INK_DIM)) | 5047 | + .id(("do", i)) |
| 4992 | - .child(format!("press a key — {out} cancels")) | 5048 | + .flex_1() |
| 4993 | - } else { | 5049 | + .min_w(px(0.)) |
| 4994 | - div().child(self.keymap.display(action)) | 5050 | + .flex() |
| 4995 | - }) | 5051 | + .min_h(px(KEYS_ROW_H)) |
| 4996 | - .into_any_element(), | 5052 | + .items_center() |
| 4997 | - ); | 5053 | + .child(action.label()) |
| 4998 | - } | 5054 | + // The reason rides on the label rather than in |
| 4999 | - for f in fixed { | 5055 | + // the stroke column, which the rebind half |
| 5000 | - head(&mut rows); | 5056 | + // needs whatever the editor's state is: an |
| 5001 | - rows.push( | 5057 | + // action nobody can ask for right now is still |
| 5002 | - div() | 5058 | + // one whose key may be changed. |
| 5003 | - .flex() | 5059 | + .when_some(refusal.why(), |d, why| { |
| 5004 | - .min_h(px(KEYS_ROW_H)) | 5060 | + let why: SharedString = why.into(); |
| 5005 | - .items_center() | 5061 | + d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into()) |
| 5006 | - .justify_between() | 5062 | + }) |
| 5007 | - .gap(px(12.)) | 5063 | + .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) |
| 5008 | - .px(px(6.)) | 5064 | + .when(refusal.yes(), |d| { |
| 5065 | + d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click( | ||
| 5066 | + cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5067 | + // The card goes first: several of | ||
| 5068 | + // these open a card of their own, | ||
| 5069 | + // and every edit moves the indices | ||
| 5070 | + // the menus are holding. | ||
| 5071 | + this.keys_open = false; | ||
| 5072 | + this.rebinding = None; | ||
| 5073 | + this.act(action, cx); | ||
| 5074 | + cx.notify(); | ||
| 5075 | + }), | ||
| 5076 | + ) | ||
| 5077 | + }), | ||
| 5078 | + ) | ||
| 5079 | + .child( | ||
| 5080 | + // ponytail: the column is as wide as the stroke it | ||
| 5081 | + // prints, so a one-character chord gives this half a | ||
| 5082 | + // hit area under the 24px WCAG 2.5.8 floor -- tall | ||
| 5083 | + // enough, narrow. Upgrade: a min_w of HIT_MIN here. | ||
| 5084 | + div() | ||
| 5085 | + .id(("bind", i)) | ||
| 5086 | + .flex_none() | ||
| 5087 | + .flex() | ||
| 5088 | + .min_h(px(KEYS_ROW_H)) | ||
| 5089 | + .items_center() | ||
| 5090 | + .cursor_pointer() | ||
| 5091 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 5092 | + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5093 | + this.rebinding = Some(action); | ||
| 5094 | + cx.notify(); | ||
| 5095 | + })) | ||
| 5096 | + .child(if capturing { | ||
| 5097 | + div() | ||
| 5098 | + .text_color(rgb(INK_DIM)) | ||
| 5099 | + .child(format!("press a key — {out} cancels")) | ||
| 5100 | + } else { | ||
| 5101 | + div().child(self.keymap.display(action)) | ||
| 5102 | + }), | ||
| 5103 | + ) | ||
| 5104 | + .into_any_element() | ||
| 5105 | + } | ||
| 5106 | + KeyRow::Fixed(f) => { | ||
| 5107 | + let f = &keymap::FIXED[f]; | ||
| 5108 | + row() | ||
| 5009 | .child(f.label) | 5109 | .child(f.label) |
| 5010 | // Dim, and no hover: this one is not a row you can click. | 5110 | // Dim, and no hover: this one is not a row you can click. |
| 5011 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) | 5111 | .child(div().text_color(rgb(INK_DIM)).child(f.chord)) |
| 5012 | - .into_any_element(), | 5112 | + .into_any_element() |
| 5013 | - ); | 5113 | + } |
| 5014 | - } | 5114 | + }); |
| 5015 | } | 5115 | } |
| 5016 | Some( | 5116 | Some( |
| 5017 | div() | 5117 | div() |
| @@ -5038,7 +5138,7 @@ impl Player { | |||
| 5038 | // Title and instruction are two children, never one | 5138 | // Title and instruction are two children, never one |
| 5039 | // wrapping line: a fixed-height slot whose text wrapped | 5139 | // wrapping line: a fixed-height slot whose text wrapped |
| 5040 | // painted its second line over the first row. | 5140 | // painted its second line over the first row. |
| 5041 | - .child(div().flex_none().px(px(6.)).child("Keybindings")) | 5141 | + .child(div().flex_none().px(px(6.)).child("Actions & keys")) |
| 5042 | // One status line, under the title where the eye starts. | 5142 | // One status line, under the title where the eye starts. |
| 5043 | // A refusal takes it over -- it is the more urgent of the | 5143 | // A refusal takes it over -- it is the more urgent of the |
| 5044 | // two, and the notice bar it would otherwise appear in is | 5144 | // two, and the notice bar it would otherwise appear in is |
| @@ -5056,7 +5156,10 @@ impl Player { | |||
| 5056 | .child( | 5156 | .child( |
| 5057 | self.notice | 5157 | self.notice |
| 5058 | .clone() | 5158 | .clone() |
| 5059 | - .unwrap_or_else(|| "click a row, then press a key".into()), | 5159 | + .unwrap_or_else(|| { |
| 5160 | + "click an action to do it · click its key to change it" | ||
| 5161 | + .into() | ||
| 5162 | + }), | ||
| 5060 | ), | 5163 | ), |
| 5061 | ) | 5164 | ) |
| 5062 | // Capped and scrolling rather than as tall as the action | 5165 | // Capped and scrolling rather than as tall as the action |
| @@ -6595,7 +6698,6 @@ impl Player { | |||
| 6595 | let menu = self.context_menu?; | 6698 | let menu = self.context_menu?; |
| 6596 | let session = self.session.as_ref()?; | 6699 | let session = self.session.as_ref()?; |
| 6597 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; | 6700 | let clip = *session.lane_clips(menu.lane).get(menu.idx)?; |
| 6598 | - let playhead = frame_at(session.now(), self.fps); | ||
| 6599 | let source = session.sources().get(clip.source).cloned()?; | 6701 | let source = session.sources().get(clip.source).cloned()?; |
| 6600 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); | 6702 | let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); |
| 6601 | let row = |n: usize| { | 6703 | let row = |n: usize| { |
| @@ -6649,7 +6751,11 @@ impl Player { | |||
| 6649 | } | 6751 | } |
| 6650 | } else { | 6752 | } else { |
| 6651 | for action in MENU_ITEMS { | 6753 | for action in MENU_ITEMS { |
| 6652 | - let enabled = applicable(&clip, menu.lane, action, playhead); | 6754 | + // The registry's own answer, the same one the actions card |
| 6755 | + // dims a row with -- and a row that takes no click says *why* | ||
| 6756 | + // rather than printing a stroke that would do nothing. | ||
| 6757 | + let refusal = self.enable(action, Some((menu.lane, menu.idx))); | ||
| 6758 | + let enabled = refusal.yes(); | ||
| 6653 | // The one item that is not about this clip says so, and says it | 6759 | // The one item that is not about this clip says so, and says it |
| 6654 | // here rather than in the registry: the stroke is global too, | 6760 | // here rather than in the registry: the stroke is global too, |
| 6655 | // but its row in the keys menu is not sitting on a clip. | 6761 | // but its row in the keys menu is not sitting on a clip. |
| @@ -6661,11 +6767,20 @@ impl Player { | |||
| 6661 | rows.push( | 6767 | rows.push( |
| 6662 | row(rows.len()) | 6768 | row(rows.len()) |
| 6663 | .child(label) | 6769 | .child(label) |
| 6664 | - .child( | 6770 | + .child(match refusal.why() { |
| 6665 | - div() | 6771 | + // One truncated line, like the details side: a |
| 6772 | + // reason that wrapped would make the card taller | ||
| 6773 | + // than the height `menu_at` placed it by. | ||
| 6774 | + Some(why) => div() | ||
| 6775 | + .min_w(px(0.)) | ||
| 6776 | + .truncate() | ||
| 6777 | + .text_size(px(11.)) | ||
| 6778 | + .text_color(rgb(INK_DIM)) | ||
| 6779 | + .child(why), | ||
| 6780 | + None => div() | ||
| 6666 | .text_color(rgb(INK_DIM)) | 6781 | .text_color(rgb(INK_DIM)) |
| 6667 | .child(self.keymap.display(action)), | 6782 | .child(self.keymap.display(action)), |
| 6668 | - ) | 6783 | + }) |
| 6669 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) | 6784 | .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) |
| 6670 | .when(enabled, |d| { | 6785 | .when(enabled, |d| { |
| 6671 | d.cursor_pointer() | 6786 | d.cursor_pointer() |
| @@ -7461,42 +7576,132 @@ fn band_label(band: &Band) -> String { | |||
| 7461 | } | 7576 | } |
| 7462 | } | 7577 | } |
| 7463 | 7578 | ||
| 7464 | -/// Whether the clip menu offers `action` on the clip it was opened on. Two of | 7579 | +/// Whether an action can be asked for, and what to say when it cannot. Two |
| 7465 | -/// the items act on the *playhead* rather than on the clip, so a menu opened | 7580 | +/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at |
| 7466 | -/// away from it dims them instead of looking broken when they are clicked, and | 7581 | +/// -- an audio clip has no picture, so a grade is not a thing that exists for |
| 7467 | -/// one acts on sound, which only an audio lane's clip has. | 7582 | +/// it, whatever the editor does next -- and `No` is about the state of this |
| 7468 | -fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool { | 7583 | +/// moment, which the next click of the playhead can change. Both dim their row |
| 7469 | - match action { | 7584 | +/// today; a menu that wants to leave the class refusals out and keep the state |
| 7470 | - // The equalizer filters samples, and a video clip has none of its own | 7585 | +/// ones has only to match on which of the two it got. |
| 7471 | - // here: the sound is the audio lane's, clip for clip. | 7586 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 7472 | - ActionId::Equalizer => lane.kind == LaneKind::Audio, | 7587 | +enum Enable { |
| 7473 | - // A grade is a picture setting and an audio clip has no picture: the | 7588 | + Yes, |
| 7474 | - // item is there on every clip, and dimmed where it would mean nothing. | 7589 | + No(&'static str), |
| 7475 | - // A fit policy is a picture setting for the same reason. | 7590 | + Hidden(&'static str), |
| 7476 | - ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video, | 7591 | +} |
| 7477 | - // Splits this clip only from inside it: at either edge there is nothing | 7592 | + |
| 7478 | - // to split off -- and, on a speeded clip, only at a frame its own rate | 7593 | +impl Enable { |
| 7479 | - // can address, which is the same question `splittable` asks. | 7594 | + /// Whether the row takes a click. |
| 7480 | - ActionId::Cut => { | 7595 | + fn yes(self) -> bool { |
| 7481 | - clip.start < playhead | 7596 | + self == Enable::Yes |
| 7482 | - && playhead < clip.end() | 7597 | + } |
| 7483 | - && clip | 7598 | + |
| 7484 | - .speed | 7599 | + /// What the row says instead of its stroke, if it says anything. |
| 7485 | - .split_at(clip.len(), playhead - clip.start) | 7600 | + fn why(self) -> Option<&'static str> { |
| 7486 | - .is_some() | 7601 | + match self { |
| 7602 | + Enable::Yes => None, | ||
| 7603 | + Enable::No(why) | Enable::Hidden(why) => Some(why), | ||
| 7487 | } | 7604 | } |
| 7488 | - // A rate applies to a clip of either kind and to its whole group, so | 7605 | + } |
| 7489 | - // there is no lane it means nothing on -- `_ => true` below is its | 7606 | +} |
| 7490 | - // answer, and the engine words the one refusal there is (no room). | 7607 | + |
| 7608 | +/// What an enablement question is asked *about*: the clip in question, if there | ||
| 7609 | +/// is one, and the little of the editor's state the answers need. Handed in | ||
| 7610 | +/// rather than read off the player, so [`enable`] is a pure function a test can | ||
| 7611 | +/// ask about a clip without building a window. | ||
| 7612 | +#[derive(Clone, Copy, Default)] | ||
| 7613 | +struct Ctx { | ||
| 7614 | + /// The clip the question is about -- the one a menu was opened on, or the | ||
| 7615 | + /// marked one. `None` means the question is about the editor as a whole, | ||
| 7616 | + /// and the clip-relative answers stand aside: those actions find their own | ||
| 7617 | + /// clip under the playhead and word their own refusal. | ||
| 7618 | + clip: Option<(Clip, Lane)>, | ||
| 7619 | + playhead: u32, | ||
| 7620 | + /// A timeline is open. | ||
| 7621 | + timeline: bool, | ||
| 7622 | + /// Something has been copied. | ||
| 7623 | + clipboard: bool, | ||
| 7624 | + exporting: bool, | ||
| 7625 | +} | ||
| 7626 | + | ||
| 7627 | +/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing | ||
| 7628 | +/// else in the editor asks the question: the clip menu dims a row with this, | ||
| 7629 | +/// the actions card dims a row with this, and the two can never come to | ||
| 7630 | +/// disagree about what an action needs -- exactly the reason [`Player::act`] is | ||
| 7631 | +/// one table too. | ||
| 7632 | +fn enable(action: ActionId, ctx: Ctx) -> Enable { | ||
| 7633 | + if !ctx.timeline { | ||
| 7634 | + return Enable::No("no timeline open"); | ||
| 7635 | + } | ||
| 7636 | + // An export is reading the edit list every other action would change, which | ||
| 7637 | + // is the rule the key handler already follows. | ||
| 7638 | + if ctx.exporting { | ||
| 7639 | + return match action { | ||
| 7640 | + ActionId::CancelExport => Enable::Yes, | ||
| 7641 | + _ => Enable::No("an export is running"), | ||
| 7642 | + }; | ||
| 7643 | + } | ||
| 7644 | + match action { | ||
| 7645 | + // -- class: what kind of thing the action is about. The equalizer | ||
| 7646 | + // filters samples, and a video clip has none of its own here: the sound | ||
| 7647 | + // is the audio lane's, clip for clip. | ||
| 7648 | + ActionId::Equalizer => match ctx.clip { | ||
| 7649 | + Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"), | ||
| 7650 | + _ => Enable::Yes, | ||
| 7651 | + }, | ||
| 7652 | + // A grade is a picture setting and an audio clip has no picture. A fit | ||
| 7653 | + // policy is a picture setting for the same reason. | ||
| 7654 | + ActionId::Color | ActionId::Fit => match ctx.clip { | ||
| 7655 | + Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"), | ||
| 7656 | + _ => Enable::Yes, | ||
| 7657 | + }, | ||
| 7658 | + // -- state: true of this clip now, and the next playhead click or the | ||
| 7659 | + // next selection changes the answer. Splits this clip only from inside | ||
| 7660 | + // it: at either edge there is nothing to split off -- and, on a speeded | ||
| 7661 | + // clip, only at a frame its own rate can address, which is the same | ||
| 7662 | + // question `splittable` asks. | ||
| 7663 | + ActionId::Cut => match ctx.clip { | ||
| 7664 | + Some((clip, _)) | ||
| 7665 | + if !(clip.start < ctx.playhead | ||
| 7666 | + && ctx.playhead < clip.end() | ||
| 7667 | + && clip | ||
| 7668 | + .speed | ||
| 7669 | + .split_at(clip.len(), ctx.playhead - clip.start) | ||
| 7670 | + .is_some()) => | ||
| 7671 | + { | ||
| 7672 | + Enable::No("only from inside a clip") | ||
| 7673 | + } | ||
| 7674 | + _ => Enable::Yes, | ||
| 7675 | + }, | ||
| 7491 | // Rejoins whatever meets at the playhead, so it can mean something only | 7676 | // Rejoins whatever meets at the playhead, so it can mean something only |
| 7492 | // at an edge of this clip. Whether those two halves were ever one take | 7677 | // at an edge of this clip. Whether those two halves were ever one take |
| 7493 | // is the engine's question, and it words that refusal itself. | 7678 | // is the engine's question, and it words that refusal itself. |
| 7494 | - ActionId::Regroup => playhead == clip.start || playhead == clip.end(), | 7679 | + ActionId::Regroup => match ctx.clip { |
| 7680 | + Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => { | ||
| 7681 | + Enable::No("only where two clips meet") | ||
| 7682 | + } | ||
| 7683 | + _ => Enable::Yes, | ||
| 7684 | + }, | ||
| 7495 | // Nothing to take apart in a clip that names no group at all. Whether | 7685 | // Nothing to take apart in a clip that names no group at all. Whether |
| 7496 | // the group it names still has another half is the engine's question, | 7686 | // the group it names still has another half is the engine's question, |
| 7497 | - // like the regroup above, and it words that refusal itself. | 7687 | + // like the regroup above. |
| 7498 | - ActionId::Detach => clip.link.is_some(), | 7688 | + ActionId::Detach => match ctx.clip { |
| 7499 | - _ => true, | 7689 | + Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"), |
| 7690 | + _ => Enable::Yes, | ||
| 7691 | + }, | ||
| 7692 | + // The three that act on the marked clip and on nothing else: with none | ||
| 7693 | + // marked they would silently do nothing, which is what the Delete | ||
| 7694 | + // button's own dimming has always said. | ||
| 7695 | + ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => { | ||
| 7696 | + Enable::No("click a clip first") | ||
| 7697 | + } | ||
| 7698 | + ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"), | ||
| 7699 | + ActionId::CancelExport => Enable::No("nothing is exporting"), | ||
| 7700 | + // A rate applies to a clip of either kind and to its whole group, so | ||
| 7701 | + // there is no lane it means nothing on, and the engine words the one | ||
| 7702 | + // refusal there is (no room). Everything else is the editor's own and | ||
| 7703 | + // needs nothing but a timeline. | ||
| 7704 | + _ => Enable::Yes, | ||
| 7500 | } | 7705 | } |
| 7501 | } | 7706 | } |
| 7502 | 7707 | ||
| @@ -9240,22 +9445,23 @@ fn timecode(t: f64, fps: f64) -> String { | |||
| 9240 | #[cfg(test)] | 9445 | #[cfg(test)] |
| 9241 | mod tests { | 9446 | mod tests { |
| 9242 | use super::{ | 9447 | use super::{ |
| 9243 | - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, | 9448 | + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, |
| 9244 | - EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, | 9449 | + EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, |
| 9245 | - EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, FORMATS, Format, HEADER_GAP, | 9450 | + EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS, |
| 9246 | - HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, | 9451 | + Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, |
| 9247 | - KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, | 9452 | + INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, |
| 9248 | - LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, | 9453 | + LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, |
| 9249 | - PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, | 9454 | + MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, |
| 9250 | - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume, | 9455 | + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, |
| 9251 | - WAVE_BPS, WAVE_COL, Wave, applicable, band_label, bitrate_refusal, can_add, cancels_export, | 9456 | + Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, band_label, bitrate_refusal, |
| 9252 | - clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y, | 9457 | + can_add, cancels_export, clipboard_after_remove, color_snap, containers, enable, envelope, |
| 9253 | - estimated_mb, export_path, export_settings, format_key, format_line, format_refusal, | 9458 | + eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, |
| 9254 | - fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, | 9459 | + format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, |
| 9255 | - keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h, | 9460 | + is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at, next_container, |
| 9256 | - project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snap_cue, | 9461 | + normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, |
| 9257 | - snap_marks, snapped, source_tint, span_partner, speed_at, summary_head, summary_tail, | 9462 | + show_label, silence_rate, snap_cue, snap_marks, snapped, source_tint, span_partner, |
| 9258 | - timecode, transport, unseen_paths, unseen_sources, whole_take, window_title, | 9463 | + speed_at, summary_head, summary_tail, timecode, transport, unseen_paths, unseen_sources, |
| 9464 | + whole_take, window_title, | ||
| 9259 | }; | 9465 | }; |
| 9260 | use super::{ | 9466 | use super::{ |
| 9261 | LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, | 9467 | LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, |
| @@ -9571,43 +9777,126 @@ mod tests { | |||
| 9571 | speed: Speed::NORMAL, | 9777 | speed: Speed::NORMAL, |
| 9572 | }; | 9778 | }; |
| 9573 | assert_eq!(clip.end(), 90); | 9779 | assert_eq!(clip.end(), 90); |
| 9574 | - // Cut splits from inside only: neither edge has anything to split off. | ||
| 9575 | let a1 = Lane::A1; | 9780 | let a1 = Lane::A1; |
| 9576 | let v1 = Lane::V1; | 9781 | let v1 = Lane::V1; |
| 9577 | - assert!(applicable(&clip, v1, ActionId::Cut, 31)); | 9782 | + // The question the clip menu asks: a timeline is open and the menu was |
| 9578 | - assert!(applicable(&clip, v1, ActionId::Cut, 89)); | 9783 | + // opened on this clip, at this playhead. |
| 9579 | - assert!(!applicable(&clip, v1, ActionId::Cut, 30)); | 9784 | + let on = |clip: &Clip, lane, action, playhead| { |
| 9580 | - assert!(!applicable(&clip, v1, ActionId::Cut, 90)); | 9785 | + enable( |
| 9581 | - assert!(!applicable(&clip, v1, ActionId::Cut, 200)); | 9786 | + action, |
| 9787 | + Ctx { | ||
| 9788 | + clip: Some((*clip, lane)), | ||
| 9789 | + playhead, | ||
| 9790 | + timeline: true, | ||
| 9791 | + ..Ctx::default() | ||
| 9792 | + }, | ||
| 9793 | + ) | ||
| 9794 | + }; | ||
| 9795 | + let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes(); | ||
| 9796 | + // Cut splits from inside only: neither edge has anything to split off. | ||
| 9797 | + assert!(offered(&clip, v1, ActionId::Cut, 31)); | ||
| 9798 | + assert!(offered(&clip, v1, ActionId::Cut, 89)); | ||
| 9799 | + assert!(!offered(&clip, v1, ActionId::Cut, 30)); | ||
| 9800 | + assert!(!offered(&clip, v1, ActionId::Cut, 90)); | ||
| 9801 | + assert!(!offered(&clip, v1, ActionId::Cut, 200)); | ||
| 9582 | // Regroup is the other way round: only where this clip meets another. | 9802 | // Regroup is the other way round: only where this clip meets another. |
| 9583 | - assert!(applicable(&clip, v1, ActionId::Regroup, 30)); | 9803 | + assert!(offered(&clip, v1, ActionId::Regroup, 30)); |
| 9584 | - assert!(applicable(&clip, v1, ActionId::Regroup, 90)); | 9804 | + assert!(offered(&clip, v1, ActionId::Regroup, 90)); |
| 9585 | - assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); | 9805 | + assert!(!offered(&clip, v1, ActionId::Regroup, 60)); |
| 9586 | // Detach is the clip's own business: nothing to take apart in one that | 9806 | // Detach is the clip's own business: nothing to take apart in one that |
| 9587 | // names no group, and whether the group still has another half is the | 9807 | // names no group, and whether the group still has another half is the |
| 9588 | // engine's question. Group is offered on every clip, for that reason. | 9808 | // engine's question. Group is offered on every clip, for that reason. |
| 9589 | - assert!(!applicable(&clip, v1, ActionId::Detach, 0)); | 9809 | + assert!(!offered(&clip, v1, ActionId::Detach, 0)); |
| 9590 | let grouped = Clip { | 9810 | let grouped = Clip { |
| 9591 | link: Some(3), | 9811 | link: Some(3), |
| 9592 | ..clip | 9812 | ..clip |
| 9593 | }; | 9813 | }; |
| 9594 | - assert!(applicable(&grouped, v1, ActionId::Detach, 60)); | 9814 | + assert!(offered(&grouped, v1, ActionId::Detach, 60)); |
| 9595 | - assert!(applicable(&clip, a1, ActionId::Group, 0)); | 9815 | + assert!(offered(&clip, a1, ActionId::Group, 0)); |
| 9596 | // The equalizer is the one item the *lane* decides: it filters samples, | 9816 | // The equalizer is the one item the *lane* decides: it filters samples, |
| 9597 | // and a video clip has none of its own. Never the playhead's business. | 9817 | // and a video clip has none of its own. Never the playhead's business. |
| 9598 | - assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); | 9818 | + assert!(offered(&clip, a1, ActionId::Equalizer, 0)); |
| 9599 | - assert!(applicable(&clip, a1, ActionId::Equalizer, 60)); | 9819 | + assert!(offered(&clip, a1, ActionId::Equalizer, 60)); |
| 9600 | - assert!(!applicable(&clip, v1, ActionId::Equalizer, 60)); | 9820 | + assert!(!offered(&clip, v1, ActionId::Equalizer, 60)); |
| 9601 | // The rest act on the clip that was clicked, so they always mean | 9821 | // The rest act on the clip that was clicked, so they always mean |
| 9602 | // something -- the engine words its own refusals. | 9822 | // something -- the engine words its own refusals. |
| 9603 | for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { | 9823 | for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { |
| 9604 | - assert!(applicable(&clip, v1, action, 0)); | 9824 | + assert!(offered(&clip, v1, action, 0)); |
| 9605 | - assert!(applicable(&clip, a1, action, 60)); | 9825 | + assert!(offered(&clip, a1, action, 60)); |
| 9606 | } | 9826 | } |
| 9607 | // Except the grade, which is a picture setting: offered on a video | 9827 | // Except the grade, which is a picture setting: offered on a video |
| 9608 | // clip wherever the playhead is, dimmed on a waveform. | 9828 | // clip wherever the playhead is, dimmed on a waveform. |
| 9609 | - assert!(applicable(&clip, v1, ActionId::Color, 0)); | 9829 | + assert!(offered(&clip, v1, ActionId::Color, 0)); |
| 9610 | - assert!(!applicable(&clip, a1, ActionId::Color, 60)); | 9830 | + assert!(!offered(&clip, a1, ActionId::Color, 60)); |
| 9831 | + // The two kinds of no, which is what the row can be told apart by: a | ||
| 9832 | + // grade on a waveform is a *class* answer -- an audio clip has no | ||
| 9833 | + // picture and never will, so a menu may leave the item out -- where a | ||
| 9834 | + // cut at the clip's edge is this moment's answer and the next click of | ||
| 9835 | + // the playhead changes it, so that one is dimmed and stays. | ||
| 9836 | + assert!(matches!( | ||
| 9837 | + on(&clip, a1, ActionId::Color, 60), | ||
| 9838 | + Enable::Hidden(_) | ||
| 9839 | + )); | ||
| 9840 | + assert!(matches!( | ||
| 9841 | + on(&clip, a1, ActionId::Fit, 60), | ||
| 9842 | + Enable::Hidden(_) | ||
| 9843 | + )); | ||
| 9844 | + assert!(matches!( | ||
| 9845 | + on(&clip, v1, ActionId::Equalizer, 60), | ||
| 9846 | + Enable::Hidden(_) | ||
| 9847 | + )); | ||
| 9848 | + assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_))); | ||
| 9849 | + assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_))); | ||
| 9850 | + assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_))); | ||
| 9851 | + // Every refusal says something, and says it short enough to sit in the | ||
| 9852 | + // menu's right-hand column beside a label. | ||
| 9853 | + for action in MENU_ITEMS { | ||
| 9854 | + for lane in [v1, a1] { | ||
| 9855 | + for playhead in [0, 30, 60, 90] { | ||
| 9856 | + if let Some(why) = on(&clip, lane, action, playhead).why() { | ||
| 9857 | + assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}"); | ||
| 9858 | + } | ||
| 9859 | + } | ||
| 9860 | + } | ||
| 9861 | + } | ||
| 9862 | + // The editor as a whole, which is how the actions card asks: with no | ||
| 9863 | + // timeline nothing is offered, an export leaves only its own cancel, | ||
| 9864 | + // and the three that act on the marked clip say so when none is. | ||
| 9865 | + let whole = |action, ctx| enable(action, ctx); | ||
| 9866 | + assert_eq!( | ||
| 9867 | + whole(ActionId::Play, Ctx::default()), | ||
| 9868 | + Enable::No("no timeline open") | ||
| 9869 | + ); | ||
| 9870 | + let live = Ctx { | ||
| 9871 | + timeline: true, | ||
| 9872 | + ..Ctx::default() | ||
| 9873 | + }; | ||
| 9874 | + assert!(whole(ActionId::Play, live).yes()); | ||
| 9875 | + assert!(!whole(ActionId::Delete, live).yes()); | ||
| 9876 | + assert!(!whole(ActionId::Paste, live).yes()); | ||
| 9877 | + assert!( | ||
| 9878 | + whole( | ||
| 9879 | + ActionId::Paste, | ||
| 9880 | + Ctx { | ||
| 9881 | + clipboard: true, | ||
| 9882 | + ..live | ||
| 9883 | + } | ||
| 9884 | + ) | ||
| 9885 | + .yes() | ||
| 9886 | + ); | ||
| 9887 | + assert!(!whole(ActionId::CancelExport, live).yes()); | ||
| 9888 | + let busy = Ctx { | ||
| 9889 | + exporting: true, | ||
| 9890 | + ..live | ||
| 9891 | + }; | ||
| 9892 | + assert!(whole(ActionId::CancelExport, busy).yes()); | ||
| 9893 | + for action in ActionId::ALL { | ||
| 9894 | + assert_eq!( | ||
| 9895 | + whole(action, busy).yes(), | ||
| 9896 | + action == ActionId::CancelExport, | ||
| 9897 | + "{action:?} while an export reads the edit list" | ||
| 9898 | + ); | ||
| 9899 | + } | ||
| 9611 | // The playhead frame is the engine's own rule, boundary included. | 9900 | // The playhead frame is the engine's own rule, boundary included. |
| 9612 | assert_eq!(frame_at(1.0, 30.), 30); | 9901 | assert_eq!(frame_at(1.0, 30.), 30); |
| 9613 | assert_eq!(frame_at(0.0, 30.), 0); | 9902 | assert_eq!(frame_at(0.0, 30.), 0); |
| @@ -9650,9 +9939,9 @@ mod tests { | |||
| 9650 | 9939 | ||
| 9651 | /// The other half of the keys menu's guarantee, and the audit this batch was | 9940 | /// The other half of the keys menu's guarantee, and the audit this batch was |
| 9652 | /// asked for kept as a test: no action may be a stroke and nothing else. | 9941 | /// asked for kept as a test: no action may be a stroke and nothing else. |
| 9653 | - /// Either the clip menu offers it, or a control in the panel does -- named | 9942 | + /// The actions card answers it for all of them at once -- its rows come off |
| 9654 | - /// here by the id [`control`] is handed, read out of this file's own source | 9943 | + /// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and |
| 9655 | - /// like `no_stroke_is_missing_from_the_keys_menu` reads the key handler. | 9944 | + /// there is no hand-written list here to fall behind. |
| 9656 | #[test] | 9945 | #[test] |
| 9657 | fn every_action_is_reachable_without_the_keyboard() { | 9946 | fn every_action_is_reachable_without_the_keyboard() { |
| 9658 | use keymap::ActionId; | 9947 | use keymap::ActionId; |
| @@ -9661,51 +9950,26 @@ mod tests { | |||
| 9661 | .next() | 9950 | .next() |
| 9662 | .unwrap(); | 9951 | .unwrap(); |
| 9663 | let element = |id: &str| source.contains(&format!("\"{id}\"")); | 9952 | let element = |id: &str| source.contains(&format!("\"{id}\"")); |
| 9953 | + let listed: Vec<ActionId> = keys_rows() | ||
| 9954 | + .iter() | ||
| 9955 | + .filter_map(|r| match r { | ||
| 9956 | + KeyRow::Act(a) => Some(*a), | ||
| 9957 | + _ => None, | ||
| 9958 | + }) | ||
| 9959 | + .collect(); | ||
| 9664 | for action in ActionId::ALL { | 9960 | for action in ActionId::ALL { |
| 9665 | - let by_pointer = MENU_ITEMS.contains(&action) | 9961 | + assert_eq!( |
| 9666 | - || match action { | 9962 | + listed.iter().filter(|a| **a == action).count(), |
| 9667 | - ActionId::Play => element("transport"), | 9963 | + 1, |
| 9668 | - // One slot, two states: it starts an export and stops the | 9964 | + "{action:?} is reachable by keyboard only" |
| 9669 | - // one it started. | 9965 | + ); |
| 9670 | - ActionId::Export | ActionId::CancelExport => element("export"), | ||
| 9671 | - ActionId::Save => element("save"), | ||
| 9672 | - ActionId::Undo => element("undo"), | ||
| 9673 | - ActionId::Resolution => element("resolution"), | ||
| 9674 | - // Three buttons beside it, and the ctrl+wheel on the bar. | ||
| 9675 | - ActionId::ZoomIn => element("zoom-in"), | ||
| 9676 | - ActionId::ZoomOut => element("zoom-out"), | ||
| 9677 | - ActionId::ZoomFit => element("zoom-fit"), | ||
| 9678 | - ActionId::AddVideoLane => element("add-video-lane"), | ||
| 9679 | - ActionId::AddAudioLane => element("add-audio-lane"), | ||
| 9680 | - // The × in a lane's own header, which takes any track and | ||
| 9681 | - // not only the last one. | ||
| 9682 | - ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => { | ||
| 9683 | - source.contains("this.remove_lane(lane, cx)") | ||
| 9684 | - } | ||
| 9685 | - ActionId::ToggleMute => element("volume"), | ||
| 9686 | - // The button beside the zoom, which says which way it is | ||
| 9687 | - // set as well as setting it. | ||
| 9688 | - ActionId::ToggleSnap => element("snap"), | ||
| 9689 | - // The fader on every audio track's own header, which is | ||
| 9690 | - // also what opens the card the limiter is on. | ||
| 9691 | - ActionId::Mix => element("mix-lane"), | ||
| 9692 | - ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"), | ||
| 9693 | - // The ruler seeks anywhere the pointer points; the frame and | ||
| 9694 | - // the second are the keyboard's finer grain of that move. | ||
| 9695 | - ActionId::StepBack | ||
| 9696 | - | ActionId::StepForward | ||
| 9697 | - | ActionId::JumpBack | ||
| 9698 | - | ActionId::JumpForward | ||
| 9699 | - | ActionId::GoStart | ||
| 9700 | - | ActionId::GoEnd => element("ruler"), | ||
| 9701 | - // A press on a clip is the selection, group and all. | ||
| 9702 | - ActionId::Select | ActionId::SelectNext | ActionId::SelectPrev => { | ||
| 9703 | - source.contains("this.select((lane, i), cx)") | ||
| 9704 | - } | ||
| 9705 | - _ => false, | ||
| 9706 | - }; | ||
| 9707 | - assert!(by_pointer, "{action:?} is reachable by keyboard only"); | ||
| 9708 | } | 9966 | } |
| 9967 | + // The snap has a door of its own as well as its row on the card: the | ||
| 9968 | + // button beside the zoom, which says which way it is set as well as | ||
| 9969 | + // setting it. | ||
| 9970 | + assert!(element("snap"), "no snap button beside the zoom"); | ||
| 9971 | + // And the card is a door the pointer can open: the panel's own button. | ||
| 9972 | + assert!(element("keys"), "no way to open the actions card"); | ||
| 9709 | // The card-local strokes have the same rule, and each of them is a thing | 9973 | // The card-local strokes have the same rule, and each of them is a thing |
| 9710 | // on its card: the graph and its two buttons, the colour bars and their | 9974 | // on its card: the graph and its two buttons, the colour bars and their |
| 9711 | // reset, the speed bar and its presets, and the silence card's rows -- | 9975 | // reset, the speed bar and its presets, and the silence card's rows -- |
| @@ -10866,6 +11130,65 @@ mod tests { | |||
| 10866 | } | 11130 | } |
| 10867 | } | 11131 | } |
| 10868 | 11132 | ||
| 11133 | + /// The whole point of the card: there is no action a pointer cannot reach. | ||
| 11134 | + /// It renders [`keys_rows`] and nothing else, so this reads the same list | ||
| 11135 | + /// the card does -- add an `ActionId` and forget to surface it and this | ||
| 11136 | + /// fails, which is the only way that stays true as the editor grows. | ||
| 11137 | + #[test] | ||
| 11138 | + fn every_action_is_on_the_actions_card() { | ||
| 11139 | + use keymap::{ActionId, Category, Keymap}; | ||
| 11140 | + let rows = keys_rows(); | ||
| 11141 | + let listed: Vec<ActionId> = rows | ||
| 11142 | + .iter() | ||
| 11143 | + .filter_map(|r| match r { | ||
| 11144 | + KeyRow::Act(a) => Some(*a), | ||
| 11145 | + _ => None, | ||
| 11146 | + }) | ||
| 11147 | + .collect(); | ||
| 11148 | + for action in ActionId::ALL { | ||
| 11149 | + assert_eq!( | ||
| 11150 | + listed.iter().filter(|a| **a == action).count(), | ||
| 11151 | + 1, | ||
| 11152 | + "{action:?} is not on the card exactly once" | ||
| 11153 | + ); | ||
| 11154 | + } | ||
| 11155 | + assert_eq!(listed.len(), ActionId::ALL.len()); | ||
| 11156 | + // Under its own heading, in the registry's order: every row after a | ||
| 11157 | + // heading belongs to that heading until the next one. | ||
| 11158 | + let mut heading = None; | ||
| 11159 | + let mut heads = 0; | ||
| 11160 | + for row in &rows { | ||
| 11161 | + match row { | ||
| 11162 | + KeyRow::Head(category) => { | ||
| 11163 | + heading = Some(*category); | ||
| 11164 | + heads += 1; | ||
| 11165 | + } | ||
| 11166 | + KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"), | ||
| 11167 | + KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading), | ||
| 11168 | + } | ||
| 11169 | + } | ||
| 11170 | + assert_eq!(heads, Category::ALL.len(), "a heading per category"); | ||
| 11171 | + // The card-local strokes are still all there beside them. | ||
| 11172 | + assert_eq!( | ||
| 11173 | + rows.iter() | ||
| 11174 | + .filter(|r| matches!(r, KeyRow::Fixed(_))) | ||
| 11175 | + .count(), | ||
| 11176 | + keymap::FIXED.len() | ||
| 11177 | + ); | ||
| 11178 | + // Both columns say something: the label does the action, the stroke | ||
| 11179 | + // beside it changes that stroke, and neither may read blank. | ||
| 11180 | + let keymap = Keymap::defaults(); | ||
| 11181 | + for action in ActionId::ALL { | ||
| 11182 | + assert!(!action.label().is_empty(), "{action:?}"); | ||
| 11183 | + assert_ne!(keymap.display(action), "unbound", "{action:?}"); | ||
| 11184 | + } | ||
| 11185 | + // The list scrolls inside a card the smallest window holds, so a | ||
| 11186 | + // thirty-fourth action costs no height at all. | ||
| 11187 | + assert!(rows.len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, "no cap needed?"); | ||
| 11188 | + // Both halves of a row are click targets, so WCAG 2.5.8 binds them. | ||
| 11189 | + assert!(KEYS_ROW_H >= HIT_MIN); | ||
| 11190 | + } | ||
| 11191 | + | ||
| 10869 | #[test] | 11192 | #[test] |
| 10870 | fn the_keybindings_card_fits_the_smallest_window() { | 11193 | fn the_keybindings_card_fits_the_smallest_window() { |
| 10871 | // The row list is capped and scrolls, so the card's height no longer | 11194 | // The row list is capped and scrolls, so the card's height no longer |
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; | ||
| 2231 | } | 2416 | } |
| 2232 | - let next = pos + (interleaved.len() / channels) as u64; | 2417 | + pos = next; |
| 2418 | + } | ||
| 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. |