forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(T3): mixed frame rates meet mkv HEVC, zero-source survival and the zoom

Browse files at this commit

6b5fa2e956df50363afe16b2ab13a9013a96d272Ahmet Kaan GümüşParent: 26af1e4aa9c851
`main`'s `open_project` now walks every source with the scaffold in its own
slot (T6), so the per-source `rates` table is built there frame by frame beside
`counts` -- one table in two vectors, grown and shortened together. The codec
gate T1 leans on stays; the frame-rate gate is still gone, and a Matroska file
shot at another rate imports through the very same door an mp4 does, its rate
read off the demuxer's `default_duration`.

Grafted from the losing branch, which had the better arithmetic:

* `Rate::from_fps` is exact. Built on `mux::frame_timing` -- the pair the muxer
  already counts an export's frames in -- divided by that pair and reduced, so
  24000/1001 over 30 is `800/1001` and stays it however far the timeline runs.
  The milli-fps rounding it replaces was a frame off after seven hours; that
  ponytail is gone rather than documented.
* A rate no timescale can *name* is an `Err` in `frame_timing`'s own words
  rather than a silent 1:1, and `matches_timeline` is where a file carrying one
  is refused -- it hands back the `Rate` it accepted the file at, so the number
  the refusal was decided on is the number the file plays by.
* `file_frames` and `file_rate` ask one `source_of`, so a path that names a
  length names a rate too.
* Five more tests in `tests/mixed_fps.rs`, in timeline frames: the exactness of
  the NTSC ratio, a trim of an off-rate clip to the room it was dragged to, the
  neighbouring 30 fps clip still read frame for frame, the linked sound placed
  at its picture's length, and the exported pictures measured against the
  file's own frames rather than merely counted.

...and the note the next builder needs in `copy_audio`: a lane holding a clip
at another rate stays a packet copy on purpose. A clip counts the *timeline's*
frames, so the window the copy trims a source's sound to is whole timeline
seconds and the packets are already in sync; re-encoding it would buy nothing
and cost a generation of loss. A speed is different, and still refused there.

36 changed files +11452 -353

Cargo.lockmodified+13 -2
@@ -4884,8 +4884,6 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
4884 [[package]]4884 [[package]]
4885 name = "rusty_aac"4885 name = "rusty_aac"
4886 version = "0.5.0"4886 version = "0.5.0"
4887-source = "registry+https://github.com/rust-lang/crates.io-index"
4888-checksum = "b7ab980ffb66a559565d09dd6727ff2da7d2a39d2e8b6149e48af6908caa99b5"
4889 4887
4890 [[package]]4888 [[package]]
4891 name = "rusty_h264"4889 name = "rusty_h264"
@@ -5607,6 +5605,7 @@ dependencies = [
5607 "symphonia-codec-vorbis",5605 "symphonia-codec-vorbis",
5608 "symphonia-core",5606 "symphonia-core",
5609 "symphonia-format-isomp4",5607 "symphonia-format-isomp4",
5608+ "symphonia-format-mkv",
5610 "symphonia-format-ogg",5609 "symphonia-format-ogg",
5611 "symphonia-format-riff",5610 "symphonia-format-riff",
5612 "symphonia-metadata",5611 "symphonia-metadata",
@@ -5716,6 +5715,18 @@ dependencies = [
5716 "symphonia-metadata",5715 "symphonia-metadata",
5717 ]5716 ]
5718 5717
5718+[[package]]
5719+name = "symphonia-format-mkv"
5720+version = "0.6.0"
5721+source = "registry+https://github.com/rust-lang/crates.io-index"
5722+checksum = "fb17713e134f5ad316c2690fa3104590ccc85842cdbcf82c3cd1a845cb08aa74"
5723+dependencies = [
5724+ "lazy_static",
5725+ "log",
5726+ "symphonia-common",
5727+ "symphonia-core",
5728+]
5729+
5719 [[package]]5730 [[package]]
5720 name = "symphonia-format-ogg"5731 name = "symphonia-format-ogg"
5721 version = "0.6.0"5732 version = "0.6.0"
Cargo.tomlmodified+12 -5
@@ -2,17 +2,24 @@
2 resolver = "3"2 resolver = "3"
3 members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"]3 members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"]
4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.
5-exclude = ["vendor/cros-libva", "vendor/cros-codecs"]5+exclude = ["vendor/cros-libva", "vendor/cros-codecs", "vendor/rusty_aac"]
6 6
7 [workspace.package]7 [workspace.package]
8 version = "0.1.0"8 version = "0.1.0"
9 edition = "2024"9 edition = "2024"
10 10
11-# Two upstream crates vendored verbatim except for one clearly marked fix each,11+# Three upstream crates vendored verbatim except for one clearly marked fix each,
12-# both blockers on this machine and both still unfixed upstream as of 0.0.6/0.0.13:12+# all blockers on this machine and all still unfixed upstream as of 0.0.6/0.0.13/0.5.0:
13 # cros-libva - fails to build against libva >= 1.23 headers13 # cros-libva - fails to build against libva >= 1.23 headers
14-# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses14+# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;
15-# Drop `vendor/` entirely once released versions handle both.15+# and creates every decode context as 8-bit 4:2:0, which no HEVC
16+# Main 10 stream can decode into (its own TODO, its own answer)
17+# rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
18+# term (the fast path in the same file serves the encoder only),
19+# which is 4x slower than real time for 5.1 and therefore not
20+# playable at all; the patch caches the cosine matrix
21+# Drop `vendor/` entirely once released versions handle all three.
16 [patch.crates-io]22 [patch.crates-io]
17 cros-libva = { path = "vendor/cros-libva" }23 cros-libva = { path = "vendor/cros-libva" }
18 cros-codecs = { path = "vendor/cros-codecs" }24 cros-codecs = { path = "vendor/cros-codecs" }
25+rusty_aac = { path = "vendor/rusty_aac" }
crates/app/src/keymap.rsmodified+32 -6
@@ -63,6 +63,9 @@ pub enum ActionId {
63 Color,63 Color,
64 Fit,64 Fit,
65 Resolution,65 Resolution,
66+ ZoomIn,
67+ ZoomOut,
68+ ZoomFit,
66 Undo,69 Undo,
67 AddVideoLane,70 AddVideoLane,
68 AddAudioLane,71 AddAudioLane,
@@ -80,7 +83,7 @@ pub enum ActionId {
80 impl ActionId {83 impl ActionId {
81 /// Display order everywhere -- the editor lists them in it and84 /// Display order everywhere -- the editor lists them in it and
82 /// [`Keymap::defaults`] binds them in it.85 /// [`Keymap::defaults`] binds them in it.
83- pub const ALL: [ActionId; 35] = [86+ pub const ALL: [ActionId; 38] = [
84 ActionId::Play,87 ActionId::Play,
85 ActionId::StepBack,88 ActionId::StepBack,
86 ActionId::StepForward,89 ActionId::StepForward,
@@ -104,6 +107,9 @@ impl ActionId {
104 ActionId::Color,107 ActionId::Color,
105 ActionId::Fit,108 ActionId::Fit,
106 ActionId::Resolution,109 ActionId::Resolution,
110+ ActionId::ZoomIn,
111+ ActionId::ZoomOut,
112+ ActionId::ZoomFit,
107 ActionId::Undo,113 ActionId::Undo,
108 ActionId::AddVideoLane,114 ActionId::AddVideoLane,
109 ActionId::AddAudioLane,115 ActionId::AddAudioLane,
@@ -144,6 +150,9 @@ impl ActionId {
144 ActionId::Color => "Colour…",150 ActionId::Color => "Colour…",
145 ActionId::Fit => "Fit policy: fit → fill → stretch → centre",151 ActionId::Fit => "Fit policy: fit → fill → stretch → centre",
146 ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p",152 ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p",
153+ ActionId::ZoomIn => "Zoom in on the timeline (around the playhead)",
154+ ActionId::ZoomOut => "Zoom out of the timeline",
155+ ActionId::ZoomFit => "Fit the whole timeline on screen",
147 ActionId::Undo => "Undo",156 ActionId::Undo => "Undo",
148 ActionId::AddVideoLane => "Add a video track",157 ActionId::AddVideoLane => "Add a video track",
149 ActionId::AddAudioLane => "Add an audio track",158 ActionId::AddAudioLane => "Add an audio track",
@@ -186,6 +195,9 @@ impl ActionId {
186 ActionId::Color => "color",195 ActionId::Color => "color",
187 ActionId::Fit => "fit",196 ActionId::Fit => "fit",
188 ActionId::Resolution => "resolution",197 ActionId::Resolution => "resolution",
198+ ActionId::ZoomIn => "zoom-in",
199+ ActionId::ZoomOut => "zoom-out",
200+ ActionId::ZoomFit => "zoom-fit",
189 ActionId::Undo => "undo",201 ActionId::Undo => "undo",
190 ActionId::AddVideoLane => "add-video-lane",202 ActionId::AddVideoLane => "add-video-lane",
191 ActionId::AddAudioLane => "add-audio-lane",203 ActionId::AddAudioLane => "add-audio-lane",
@@ -236,7 +248,11 @@ impl ActionId {
236 | ActionId::Silence => Category::Clips,248 | ActionId::Silence => Category::Clips,
237 // The project's own picture size is not a clip's business, and not249 // The project's own picture size is not a clip's business, and not
238 // a file operation either: it is what the viewer is looking at.250 // a file operation either: it is what the viewer is looking at.
239- ActionId::Resolution => Category::View,251+ // Neither is how much of the timeline the panel shows: a zoom edits
252+ // nothing, it magnifies.
253+ ActionId::Resolution | ActionId::ZoomIn | ActionId::ZoomOut | ActionId::ZoomFit => {
254+ Category::View
255+ }
240 ActionId::Cut256 ActionId::Cut
241 | ActionId::Regroup257 | ActionId::Regroup
242 | ActionId::Detach258 | ActionId::Detach
@@ -307,7 +323,7 @@ pub const FIXED: [Fixed; 16] = [
307 // holding anything else still does what one press did.323 // holding anything else still does what one press did.
308 Fixed {324 Fixed {
309 chord: "hold ← → ↑ ↓",325 chord: "hold ← → ↑ ↓",
310- label: "Run a card's slider, or the volume keys, while held",326+ label: "Run a card's slider, or the volume and zoom keys, while held",
311 category: Category::View,327 category: Category::View,
312 },328 },
313 Fixed {329 Fixed {
@@ -544,6 +560,14 @@ impl Keymap {
544 // it changes what every clip is composed onto.560 // it changes what every clip is composed onto.
545 b(ActionId::Fit, "p", false),561 b(ActionId::Fit, "p", false),
546 b(ActionId::Resolution, "r", true),562 b(ActionId::Resolution, "r", true),
563+ // The zoom pair, on the chords every editor and every browser
564+ // magnifies with. The bare "=" and "-" are the volume keys, so
565+ // these take the ctrl versions of them -- and ctrl+0 is the
566+ // "back to 100%" of the same family, which here is the whole
567+ // timeline across the bed.
568+ b(ActionId::ZoomIn, "=", true),
569+ b(ActionId::ZoomOut, "-", true),
570+ b(ActionId::ZoomFit, "0", true),
547 b(ActionId::Undo, "z", false),571 b(ActionId::Undo, "z", false),
548 b(ActionId::Undo, "z", true),572 b(ActionId::Undo, "z", true),
549 // The unshifted initials of what they add. Both were free --573 // The unshifted initials of what they add. Both were free --
@@ -839,7 +863,7 @@ mod tests {
839 #[test]863 #[test]
840 fn every_default_stroke_reaches_its_action() {864 fn every_default_stroke_reaches_its_action() {
841 let k = Keymap::defaults();865 let k = Keymap::defaults();
842- assert_eq!(k.entries().len(), 37);866+ assert_eq!(k.entries().len(), 40);
843 assert_eq!(k.lookup("space", false), Some(ActionId::Play));867 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
844 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two868 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
845 // ends of the timeline.869 // ends of the timeline.
@@ -1015,7 +1039,8 @@ mod tests {
1015 // A bindable chord is one `rebind_action` may keep: what it writes is1039 // A bindable chord is one `rebind_action` may keep: what it writes is
1016 // what the next load reads, for every stroke that passes here.1040 // what the next load reads, for every stroke that passes here.
1017 let mut k = Keymap::defaults();1041 let mut k = Keymap::defaults();
1018- k.rebind_action(ActionId::Play, chord("=", true)).unwrap();1042+ // Any free chord will do here; ctrl+= is the zoom's.
1043+ k.rebind_action(ActionId::Play, chord("w", true)).unwrap();
1019 assert_eq!(whole(&emit(&k)), k);1044 assert_eq!(whole(&emit(&k)), k);
1020 }1045 }
1021 1046
@@ -1072,7 +1097,8 @@ mod tests {
1072 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1097 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1073 // The label is the editor's column, and never the file's word for it.1098 // The label is the editor's column, and never the file's word for it.
1074 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1099 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1075- assert_eq!(ActionId::ALL.len(), 35);1100+ assert_eq!(ActionId::ALL.len(), 38);
1101+ assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1076 }1102 }
1077 1103
1078 #[test]1104 #[test]
crates/app/src/main.rsmodified+902 -82
@@ -19,9 +19,9 @@ use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19 use gpui::{19 use gpui::{
20 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,20 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,21 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
22- Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window,22+ Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign,
23- WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba,23+ TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px,
24- size,24+ relative, rgb, rgba, size,
25 };25 };
26 26
27 /// Editor chrome: three grays and one accent, all darker than the picture so the27 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -74,6 +74,11 @@ const LABEL_MIN_W: f32 = 36.;
74 /// allocates one bucket per window, so a rate taken from anything the user can74 /// allocates one bucket per window, so a rate taken from anything the user can
75 /// influence is an allocation bomb -- and 40 is already finer than the pixels a75 /// influence is an allocation bomb -- and 40 is already finer than the pixels a
76 /// clip is ever given.76 /// clip is ever given.
77+///
78+/// ponytail: "finer than the pixels" stops being true once the timeline is
79+/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as
80+/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade
81+/// is a second, finer pass over the visible span only, cached like `waves` is.
77 const WAVE_BPS: u32 = 40;82 const WAVE_BPS: u32 = 40;
78 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,83 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
79 /// and a path with a point per pixel is a path per repaint.84 /// and a path with a point per pixel is a path per repaint.
@@ -120,6 +125,11 @@ const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
120 const MENU_W: f32 = 260.;125 const MENU_W: f32 = 260.;
121 const MENU_ROW_H: f32 = HIT_MIN;126 const MENU_ROW_H: f32 = HIT_MIN;
122 const MENU_PAD: f32 = 6.;127 const MENU_PAD: f32 = 6.;
128+/// How much of the item list is on screen at once, capped and scrolling like the
129+/// keybindings and export lists: every action the pointer can reach is an item
130+/// here, and a menu taller than the 640x360 floor would hang its last items off
131+/// the bottom edge, where nobody can click them.
132+const MENU_ROWS_H: f32 = 12. * MENU_ROW_H;
123 133
124 /// The one key name this file still spells out, and gpui's spelling of it: it134 /// The one key name this file still spells out, and gpui's spelling of it: it
125 /// is the way out of a capture and out of the overlay, and both have to work135 /// is the way out of a capture and out of the overlay, and both have to work
@@ -342,8 +352,13 @@ impl RowItem {
342 /// action a stroke already reaches -- the menu is a second way *to* the actions352 /// action a stroke already reaches -- the menu is a second way *to* the actions
343 /// and never a second version of them -- so both the label and the hint come353 /// and never a second version of them -- so both the label and the hint come
344 /// out of the keymap registry and the two can never disagree.354 /// out of the keymap registry and the two can never disagree.
345-const MENU_ITEMS: [ActionId; 11] = [355+const MENU_ITEMS: [ActionId; 14] = [
346 ActionId::Cut,356 ActionId::Cut,
357+ // The clipboard pair, which had no door but a chord: copy takes the clip the
358+ // menu names, and paste is the timeline's rather than this clip's -- the
359+ // same kind of global item the mute below already is.
360+ ActionId::Copy,
361+ ActionId::Paste,
347 ActionId::Delete,362 ActionId::Delete,
348 ActionId::Lift,363 ActionId::Lift,
349 ActionId::Regroup,364 ActionId::Regroup,
@@ -351,6 +366,10 @@ const MENU_ITEMS: [ActionId; 11] = [
351 ActionId::Group,366 ActionId::Group,
352 ActionId::Equalizer,367 ActionId::Equalizer,
353 ActionId::Speed,368 ActionId::Speed,
369+ // The scan is a clip card like the two above it -- opened on whichever half
370+ // was clicked -- and a card only a stroke could open is one a pointer never
371+ // finds.
372+ ActionId::Silence,
354 ActionId::Color,373 ActionId::Color,
355 ActionId::Fit,374 ActionId::Fit,
356 ActionId::ToggleMute,375 ActionId::ToggleMute,
@@ -580,6 +599,10 @@ struct Player {
580 /// The ruler's own box, recorded at prepaint: a mouse listener is handed599 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
581 /// the window position and nothing else.600 /// the window position and nothing else.
582 ruler: Rc<Cell<Bounds<Pixels>>>,601 ruler: Rc<Cell<Bounds<Pixels>>>,
602+ /// How much of the timeline the ruler and the lanes are showing. Held here
603+ /// and nowhere else: every frame-to-pixel answer in the panel comes out of
604+ /// it, so the boxes, the playhead and the pointer cannot disagree.
605+ view: View,
583 /// Which clip the edit keys act on: the lane it is in and its index there.606 /// Which clip the edit keys act on: the lane it is in and its index there.
584 /// The *clicked* half, not the group -- a group is what gets marked on607 /// The *clicked* half, not the group -- a group is what gets marked on
585 /// screen, but Lift has to know which half it was aimed at. Indices move608 /// screen, but Lift has to know which half it was aimed at. Indices move
@@ -902,6 +925,12 @@ impl Player {
902 ActionId::Color => self.open_color(cx),925 ActionId::Color => self.open_color(cx),
903 ActionId::Fit => self.cycle_fit(cx),926 ActionId::Fit => self.cycle_fit(cx),
904 ActionId::Resolution => self.cycle_resolution(cx),927 ActionId::Resolution => self.cycle_resolution(cx),
928+ // The playhead is what a key zoom is aimed at: it is the one place
929+ // on the timeline the user is certainly looking at, and keeping it
930+ // still is what every editor does.
931+ ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx),
932+ ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx),
933+ ActionId::ZoomFit => self.zoom_fit(cx),
905 ActionId::Undo => self.undo(cx),934 ActionId::Undo => self.undo(cx),
906 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),935 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
907 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),936 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
@@ -1025,6 +1054,26 @@ impl Player {
1025 cx.notify();1054 cx.notify();
1026 }1055 }
1027 1056
1057+ /// Magnifies the timeline about a point that stays put: `anchor` is where
1058+ /// along the bed to hold still (a ctrl+wheel holds the pointer), and with
1059+ /// none it is the playhead -- so the frame being worked on is still the
1060+ /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
1061+ /// stops at the whole timeline, in at a handful of frames.
1062+ fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
1063+ let duration = self.drawn_duration();
1064+ let at = self.playhead(duration);
1065+ let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.));
1066+ self.view = self.view.zoomed(factor, anchor, duration, self.fps);
1067+ cx.notify();
1068+ }
1069+
1070+ /// All the way back out: the whole timeline across the bed, which is what
1071+ /// the panel shows before anyone has zoomed at all.
1072+ fn zoom_fit(&mut self, cx: &mut Context<Self>) {
1073+ self.view = View::default();
1074+ cx.notify();
1075+ }
1076+
1028 /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from1077 /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from
1029 /// the media's own -- the one size that must stay reachable, since a project1078 /// the media's own -- the one size that must stay reachable, since a project
1030 /// moved off it has no other way back (the resolution is not an undo step).1079 /// moved off it has no other way back (the resolution is not an undo step).
@@ -1499,6 +1548,11 @@ impl Player {
1499 match session.cut_regions(&regions, &lanes) {1548 match session.cut_regions(&regions, &lanes) {
1500 Ok(()) => {1549 Ok(()) => {
1501 self.close_silence();1550 self.close_silence();
1551+ // Every hole closed moves the clips after it up a place, so the
1552+ // selection now names a different clip than the one that is
1553+ // highlighted -- dropped here as after every other edit that
1554+ // moves indexes (a delete, a paste, an undo).
1555+ self.selected = None;
1502 self.reset_after_reseek();1556 self.reset_after_reseek();
1503 self.notice = Some(1557 self.notice = Some(
1504 format!(1558 format!(
@@ -1533,6 +1587,10 @@ impl Player {
1533 match session.speed_regions(&regions, rate, &lanes) {1587 match session.speed_regions(&regions, rate, &lanes) {
1534 Ok(()) => {1588 Ok(()) => {
1535 self.close_silence();1589 self.close_silence();
1590+ // Splitting each silence out and closing the room it no longer
1591+ // needs moves indexes exactly as the cut does: the selection
1592+ // goes with them.
1593+ self.selected = None;
1536 self.reset_after_reseek();1594 self.reset_after_reseek();
1537 self.notice = Some(1595 self.notice = Some(
1538 format!(1596 format!(
@@ -2094,14 +2152,16 @@ impl Player {
2094 /// pointer exactly.2152 /// pointer exactly.
2095 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {2153 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2096 let (duration, fps) = (self.drawn_duration(), self.fps);2154 let (duration, fps) = (self.drawn_duration(), self.fps);
2097- let frac = frac_along(x, self.ruler.get());2155+ let at = self
2156+ .view
2157+ .time_at(frac_along(x, self.ruler.get()), duration);
2098 let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {2158 let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2099 return;2159 return;
2100 };2160 };
2101 let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {2161 let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {
2102 return;2162 return;
2103 };2163 };
2104- trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi);2164+ trim.to = frame_at(at, fps).clamp(lo, hi);
2105 cx.notify();2165 cx.notify();
2106 }2166 }
2107 2167
@@ -2187,6 +2247,21 @@ impl Player {
2187 }2247 }
2188 }2248 }
2189 2249
2250+ /// Where the playhead is, as the panel draws it. The clock keeps running
2251+ /// after the last frame (wall time takes over at audio EOF) while the
2252+ /// picture is frozen, so what the UI shows is the clamped one, pinned to
2253+ /// the out-point once playback is done.
2254+ fn playhead(&self, duration: f64) -> f64 {
2255+ if self.done {
2256+ duration
2257+ } else {
2258+ self.session
2259+ .as_ref()
2260+ .map_or(0., PlaybackSession::now)
2261+ .clamp(0., duration)
2262+ }
2263+ }
2264+
2190 /// The one way a library row reaches the timeline: the Add button and a row2265 /// The one way a library row reaches the timeline: the Add button and a row
2191 /// dragged onto a lane both come here, so there is a single answer to what2266 /// dragged onto a lane both come here, so there is a single answer to what
2192 /// "add this source" does. The whole source goes in at the playhead as one2267 /// "add this source" does. The whole source goes in at the playhead as one
@@ -2266,20 +2341,43 @@ impl Player {
2266 .as_mut()2341 .as_mut()
2267 .map(|session| session.remove_source(path, stream));2342 .map(|session| session.remove_source(path, stream));
2268 let text = match removed {2343 let text = match removed {
2269- Some(Ok(())) => {2344+ Some(Ok(idx)) => {
2270 // The picked row may be the one that just went, and the engine2345 // The picked row may be the one that just went, and the engine
2271 // reseeks, so this owes the flag reset like every other edit.2346 // reseeks, so this owes the flag reset like every other edit.
2272 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {2347 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
2273 self.selected_asset = None;2348 self.selected_asset = None;
2274 }2349 }
2350+ // A copied clip names its source by *index*, and every index
2351+ // past the one that went has just moved down: without this the
2352+ // next paste puts some other file on the timeline.
2353+ self.clipboard = clipboard_after_remove(self.clipboard, idx);
2275 self.reset_after_reseek();2354 self.reset_after_reseek();
2276- // The undo stack goes with it (`Project::remove_source`): said2355+ // The last row leaves a session naming no file: nothing to
2277- // here, because a `z` that does nothing afterwards would2356+ // play, nothing to save and nothing to show, which is the empty
2278- // otherwise read as a bug.2357+ // window the editor launches as. The next import scaffolds a
2279- format!(2358+ // fresh timeline from whatever file it is, at that file's own
2280- "REMOVED {} — there is nothing left to undo",2359+ // rate -- which is why the session goes rather than lingering
2281- file_name(path)2360+ // on with the gone file's parameters.
2282- )2361+ match self
2362+ .session
2363+ .as_ref()
2364+ .is_some_and(|s| s.sources().is_empty())
2365+ {
2366+ true => {
2367+ self.close_session();
2368+ format!(
2369+ "REMOVED {} — the library is empty; import a file to start again",
2370+ file_name(path)
2371+ )
2372+ }
2373+ // The undo stack goes with it (`Project::remove_source`):
2374+ // said here, because a `z` that does nothing afterwards
2375+ // would otherwise read as a bug.
2376+ false => format!(
2377+ "REMOVED {} — there is nothing left to undo",
2378+ file_name(path)
2379+ ),
2380+ }
2283 }2381 }
2284 Some(Err(e)) => format!("NOT REMOVED — {e}"),2382 Some(Err(e)) => format!("NOT REMOVED — {e}"),
2285 None => "NO TIMELINE — open a file first".to_string(),2383 None => "NO TIMELINE — open a file first".to_string(),
@@ -2288,6 +2386,64 @@ impl Player {
2288 cx.notify();2386 cx.notify();
2289 }2387 }
2290 2388
2389+ /// Back to the window the editor launches as: no timeline, no library, no
2390+ /// picture -- and the hint that says to open a file. What removing the last
2391+ /// library row leaves, since a session whose library is empty has nothing
2392+ /// left to be ([`Player::remove_source`]).
2393+ ///
2394+ /// Everything a *loaded project* resets goes here for its reasons (an index
2395+ /// into a timeline that is gone names nothing), plus the three per-file
2396+ /// caches: they are keyed by path, and the next file to arrive fills them
2397+ /// again.
2398+ fn close_session(&mut self) {
2399+ self.session = None;
2400+ // The picture goes with it, or the empty window would keep showing the
2401+ // last frame of a timeline that no longer exists.
2402+ //
2403+ // ponytail: its atlas tile is not released -- `window.drop_image` wants
2404+ // a `&mut Window` this door has no other reason to take. One tile per
2405+ // emptied library, against one per displayed frame in `pump`; the
2406+ // upgrade path is threading the window through `act_on_row`.
2407+ self.image = None;
2408+ self.clipboard = None;
2409+ self.selected = None;
2410+ self.selected_asset = None;
2411+ self.context_menu = None;
2412+ self.library_menu = None;
2413+ self.eq_open = None;
2414+ self.color_open = None;
2415+ self.speed_open = None;
2416+ self.close_silence();
2417+ self.waves.clear();
2418+ self.streams.clear();
2419+ self.sizes.clear();
2420+ // Scanned off a source that is not in the library any more.
2421+ self.silence_levels = None;
2422+ // Every gesture in flight, dropped for `reset_after_reseek`'s reason
2423+ // (it drops the trim below): a drag holds a bar, a clip or a band of a
2424+ // timeline that has just stopped existing.
2425+ self.scrubbing = false;
2426+ self.volume_dragging = false;
2427+ self.eq_dragging = false;
2428+ self.speed_dragging = false;
2429+ self.color_dragging = false;
2430+ self.displayed = 0;
2431+ self.dropped = 0;
2432+ self.started = None;
2433+ // The empty window's own: no name in the titlebar, nowhere chosen to
2434+ // export or save to yet, and a rate that only keeps the timecode
2435+ // reading in frames until a file brings its own (`main`).
2436+ self.name = NO_FILE.into();
2437+ self.export_path = PathBuf::new();
2438+ self.project_path = PathBuf::new();
2439+ self.fps = 30.;
2440+ // No decoder to wait for a frame from: the hint is what shows.
2441+ self.reset_after_reseek();
2442+ self.pending_seek = false;
2443+ self.eos = false;
2444+ self.done = false;
2445+ }
2446+
2291 /// One item of a library row's menu, done. Every one of them closes the2447 /// One item of a library row's menu, done. Every one of them closes the
2292 /// menu first -- the list under it is about to be rebuilt -- except the one2448 /// menu first -- the list under it is about to be rebuilt -- except the one
2293 /// that turns the card over.2449 /// that turns the card over.
@@ -2321,11 +2477,22 @@ impl Player {
2321 cx.notify();2477 cx.notify();
2322 }2478 }
2323 2479
2324- /// The rate and layout the whole timeline's audio is, taken from source 0's2480+ /// The rate and layout the whole timeline's audio is, taken from the stream
2325- /// own stream: what a library row has to match to be placeable. `None`2481+ /// of the first source that could have one: what a library row has to match
2326- /// until that file has been probed, and then nothing is greyed for it.2482+ /// to be placeable. `None` until that file has been probed, and then nothing
2483+ /// is greyed for it.
2484+ ///
2485+ /// The first source that is *not a still*, which is the rule the engine
2486+ /// holds every import to (`playback::audio_source_of`) -- a picture at the
2487+ /// head of the list (a removal moves indexes) has no stream to describe
2488+ /// anything with.
2327 fn timeline_audio(&self) -> Option<(u32, u16)> {2489 fn timeline_audio(&self) -> Option<(u32, u16)> {
2328- let first = self.session.as_ref()?.sources().first()?;2490+ let first = self
2491+ .session
2492+ .as_ref()?
2493+ .sources()
2494+ .iter()
2495+ .find(|s| !engine::is_image(&s.path))?;
2329 let info = self2496 let info = self
2330 .streams2497 .streams
2331 .get(&first.path)?2498 .get(&first.path)?
@@ -2643,7 +2810,9 @@ impl Player {
2643 let Some(session) = &self.session else {2810 let Some(session) = &self.session else {
2644 return;2811 return;
2645 };2812 };
2646- let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration();2813+ let t = self
2814+ .view
2815+ .time_at(frac_along(x, self.ruler.get()), session.timeline_duration());
2647 let target = (t * self.fps) as u32;2816 let target = (t * self.fps) as u32;
2648 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {2817 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
2649 self.last_target = target;2818 self.last_target = target;
@@ -2913,17 +3082,12 @@ impl Render for Player {
2913 // timecode, the ruler and the clamp below all have to follow it -- and3082 // timecode, the ruler and the clamp below all have to follow it -- and
2914 // so does the room a tail being dragged needs to grow into.3083 // so does the room a tail being dragged needs to grow into.
2915 let duration = self.drawn_duration();3084 let duration = self.drawn_duration();
2916- // The clock keeps running after the last frame (wall time takes over at3085+ let position = self.playhead(duration);
2917- // audio EOF) while the picture is frozen, so the timeline the UI shows is3086+ // Re-settled every frame against the duration this one is drawing: an
2918- // the clamped one, pinned to the out-point once playback is done.3087+ // edit that shortens the timeline moves the far end of the view, and a
2919- let position = if self.done {3088+ // playhead that has run off the bed pulls the view after it -- which is
2920- duration3089+ // what makes a zoomed-in timeline scroll while it plays.
2921- } else {3090+ self.view = self.view.following(position, duration, self.fps);
2922- self.session
2923- .as_ref()
2924- .map_or(0., PlaybackSession::now)
2925- .clamp(0., duration)
2926- };
2927 3091
2928 div()3092 div()
2929 .track_focus(&self.focus)3093 .track_focus(&self.focus)
@@ -3630,11 +3794,11 @@ impl Player {
3630 playing: bool,3794 playing: bool,
3631 cx: &mut Context<Self>,3795 cx: &mut Context<Self>,
3632 ) -> impl IntoElement {3796 ) -> impl IntoElement {
3633- let filled = if duration > 0. {3797+ // Where the playhead is *on the bed*, which at the fit is where along
3634- (position / duration) as f323798+ // the timeline it is and zoomed in is where along the visible slice.
3635- } else {3799+ // Clamped because it is drawn as a width as well as an offset, and the
3636- 0.3800+ // view follows the playhead anyway, so it is never off the bed.
3637- };3801+ let filled = self.view.frac_at(position, duration).clamp(0., 1.);
3638 // An export owns the hint slot and the ruler while it runs: the3802 // An export owns the hint slot and the ruler while it runs: the
3639 // percentage and the accent bar are the same number, so the playhead3803 // percentage and the accent bar are the same number, so the playhead
3640 // fill doubles as the progress bar for free.3804 // fill doubles as the progress bar for free.
@@ -3642,6 +3806,10 @@ impl Player {
3642 // Everything but Import and Keys needs a timeline to act on: with none3806 // Everything but Import and Keys needs a timeline to act on: with none
3643 // open they are dimmed rather than silently doing nothing.3807 // open they are dimmed rather than silently doing nothing.
3644 let live = self.session.is_some() && !exporting;3808 let live = self.session.is_some() && !exporting;
3809+ // The project's own picture size, for the button that cycles it: read
3810+ // per render like everything else here, so a cycle shows on the button
3811+ // that made it.
3812+ let resolution = self.session.as_ref().map(PlaybackSession::resolution);
3645 let key = |action| self.keymap.display(action);3813 let key = |action| self.keymap.display(action);
3646 // The lanes the project has, or the pair a fresh one starts with so the3814 // The lanes the project has, or the pair a fresh one starts with so the
3647 // panel reads the same before a file is open as after.3815 // panel reads the same before a file is open as after.
@@ -3691,12 +3859,20 @@ impl Player {
3691 .bg(rgb(CHROME))3859 .bg(rgb(CHROME))
3692 // Transport | edit | file: three groups, so the eye can skip two of3860 // Transport | edit | file: three groups, so the eye can skip two of
3693 // them. Every button says what it does; the tooltip adds its key.3861 // them. Every button says what it does; the tooltip adds its key.
3862+ //
3863+ // The row scrolls rather than losing its tail: at the 640 px floor
3864+ // this window is sized for it is wider than the panel, and a button
3865+ // off the right edge is a button a pointer cannot press. A plain
3866+ // wheel moves it -- gpui puts a vertical delta on the x axis when
3867+ // that is the only one scrolling (div.rs:2424).
3694 .child(3868 .child(
3695 div()3869 div()
3870+ .id("controls")
3696 .flex_none()3871 .flex_none()
3697 .flex()3872 .flex()
3698 .items_center()3873 .items_center()
3699 .gap(px(8.))3874 .gap(px(8.))
3875+ .overflow_x_scroll()
3700 .child(control(3876 .child(control(
3701 "transport",3877 "transport",
3702 Some(transport_glyph(playing).into_any_element()),3878 Some(transport_glyph(playing).into_any_element()),
@@ -3738,6 +3914,17 @@ impl Player {
3738 live && self.selected.is_some(),3914 live && self.selected.is_some(),
3739 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),3915 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),
3740 ))3916 ))
3917+ // The way back from every one of them. It was a stroke and
3918+ // nothing else, which made the whole edit group a one-way
3919+ // door for anyone working with a pointer.
3920+ .child(control(
3921+ "undo",
3922+ None,
3923+ "Undo",
3924+ format!("{} — takes the last edit back", key(ActionId::Undo)),
3925+ live,
3926+ cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)),
3927+ ))
3741 // With the edit group, beside the buttons that change the3928 // With the edit group, beside the buttons that change the
3742 // edit list: a track is a row of it, and adding one is an3929 // edit list: a track is a row of it, and adding one is an
3743 // undoable edit like the rest. Two buttons rather than one3930 // undoable edit like the rest. Two buttons rather than one
@@ -3796,19 +3983,105 @@ impl Player {
3796 cx,3983 cx,
3797 ))3984 ))
3798 .child(separator())3985 .child(separator())
3986+ // The size every clip is composed onto, which is also the
3987+ // size the export comes out at: the one project setting a
3988+ // stroke used to be the only way to. Cycles exactly as the
3989+ // key does, and says where it is now rather than opening a
3990+ // list to close again.
3991+ .child(control(
3992+ "resolution",
3993+ None,
3994+ resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")),
3995+ match resolution {
3996+ Some((w, h)) => format!(
3997+ "{} — the project is {w}x{h}; cycles source → 2160p → 1080p → 720p → 480p",
3998+ key(ActionId::Resolution)
3999+ ),
4000+ None => format!("{} — open a file first", key(ActionId::Resolution)),
4001+ },
4002+ live,
4003+ cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(cx)),
4004+ ))
4005+ // How much of the timeline the panel below is showing --
4006+ // beside the resolution, since neither of them edits
4007+ // anything: they are both what is being looked at. The
4008+ // middle one reads as the state (1.0x is the whole
4009+ // timeline) and is the way back to it.
4010+ .child(control(
4011+ "zoom-out",
4012+ None,
4013+ "−",
4014+ format!(
4015+ "{} — show more of the timeline; stops at the whole of it",
4016+ key(ActionId::ZoomOut)
4017+ ),
4018+ live,
4019+ cx.listener(|this, _: &ClickEvent, _, cx| {
4020+ this.zoom(1. / ZOOM_STEP, None, cx)
4021+ }),
4022+ ))
4023+ .child(control(
4024+ "zoom-fit",
4025+ None,
4026+ format!("{:.1}x", self.view.zoom),
4027+ format!(
4028+ "{} — fit the whole timeline; showing {} to {}",
4029+ key(ActionId::ZoomFit),
4030+ timecode(self.view.start, self.fps),
4031+ timecode(
4032+ (self.view.start + self.view.span(duration)).min(duration),
4033+ self.fps
4034+ )
4035+ ),
4036+ live,
4037+ cx.listener(|this, _: &ClickEvent, _, cx| this.zoom_fit(cx)),
4038+ ))
4039+ .child(control(
4040+ "zoom-in",
4041+ None,
4042+ "+",
4043+ format!(
4044+ "{} — magnify around the playhead; ctrl+wheel on the bar zooms at the pointer",
4045+ key(ActionId::ZoomIn)
4046+ ),
4047+ live,
4048+ cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
4049+ ))
3799 // Import is not here: it belongs to the media list it adds4050 // Import is not here: it belongs to the media list it adds
3800 // to, and two doors into one action is a question about4051 // to, and two doors into one action is a question about
3801 // which one is the real one.4052 // which one is the real one.
4053+ //
4054+ // While one runs, this button is the way out of it: the
4055+ // progress line promised esc and nothing else, which left a
4056+ // pointer no way to stop an export it had started.
3802 .child(control(4057 .child(control(
3803 "export",4058 "export",
3804 None,4059 None,
3805- "Export",4060+ if exporting { "Cancel" } else { "Export" },
3806- format!(4061+ if exporting {
3807- "{} — quality and destination, then writes the timeline out",4062+ format!(
3808- key(ActionId::Export)4063+ "{} — stops the export; the part-written file goes",
3809- ),4064+ key(ActionId::CancelExport)
3810- live && self.export.is_none(),4065+ )
3811- cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)),4066+ } else {
4067+ format!(
4068+ "{} — quality and destination, then writes the timeline out",
4069+ key(ActionId::Export)
4070+ )
4071+ },
4072+ if exporting {
4073+ true
4074+ } else {
4075+ live && self.export.is_none()
4076+ },
4077+ cx.listener(|this, _: &ClickEvent, _, cx| {
4078+ if this.exporting().is_some() {
4079+ this.cancel_export();
4080+ cx.notify();
4081+ } else {
4082+ this.open_export(cx);
4083+ }
4084+ }),
3812 ))4085 ))
3813 .child(control(4086 .child(control(
3814 "save",4087 "save",
@@ -3886,7 +4159,32 @@ impl Player {
3886 .hover(|s| s.bg(rgb(HOVER_DIM)))4159 .hover(|s| s.bg(rgb(HOVER_DIM)))
3887 // The strip carries no text, so the tooltip is the only4160 // The strip carries no text, so the tooltip is the only
3888 // place it can say what it is.4161 // place it can say what it is.
3889- .tooltip(|_, cx| cx.new(|_| Tip("Seek — click or drag".into())).into())4162+ .tooltip(|_, cx| {
4163+ cx.new(|_| Tip("Seek — click or drag; ctrl+wheel zooms".into()))
4164+ .into()
4165+ })
4166+ // Ctrl+wheel is what every timeline zooms with, and
4167+ // the point held still is the one under the pointer
4168+ // rather than the playhead. Only with ctrl: a bare
4169+ // wheel here is the window's to scroll, and the
4170+ // controls row above scrolls on exactly that.
4171+ .on_scroll_wheel(cx.listener(
4172+ |this, event: &ScrollWheelEvent, _, cx| {
4173+ if !event.modifiers.control {
4174+ return;
4175+ }
4176+ let dy = match event.delta {
4177+ ScrollDelta::Lines(d) => d.y,
4178+ ScrollDelta::Pixels(d) => f32::from(d.y),
4179+ };
4180+ if dy == 0. {
4181+ return;
4182+ }
4183+ let anchor = frac_along(event.position.x, this.ruler.get());
4184+ let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP };
4185+ this.zoom(factor, Some(anchor), cx);
4186+ },
4187+ ))
3890 .on_mouse_down(4188 .on_mouse_down(
3891 MouseButton::Left,4189 MouseButton::Left,
3892 cx.listener(|this, event: &MouseDownEvent, _, cx| {4190 cx.listener(|this, event: &MouseDownEvent, _, cx| {
@@ -4958,7 +5256,45 @@ impl Player {
4958 cx.notify();5256 cx.notify();
4959 }))5257 }))
4960 .child(div().text_color(rgb(INK_DIM)).child(label))5258 .child(div().text_color(rgb(INK_DIM)).child(label))
4961- .child(value)5259+ // The value and the two steps that move it. Every other
5260+ // card has something to drag or press; this one had the
5261+ // arrow keys and nothing else, so a row was a setting a
5262+ // pointer could pick but never change. One press each, the
5263+ // same call the arrows make -- the hold-to-run is the
5264+ // keyboard's own and is not a thing a button has.
5265+ .child(
5266+ div()
5267+ .flex()
5268+ .items_center()
5269+ .gap(px(4.))
5270+ .child(value)
5271+ .children([-1, 1].map(|steps: i32| {
5272+ div()
5273+ .id(("silence-step", n * 2 + usize::from(steps > 0)))
5274+ .flex_none()
5275+ .w(px(HIT_MIN))
5276+ .h(px(KEYS_ROW_H))
5277+ .flex()
5278+ .items_center()
5279+ .justify_center()
5280+ .rounded(px(3.))
5281+ .bg(rgb(CHROME))
5282+ .cursor_pointer()
5283+ .hover(|s| s.bg(rgb(HOVER)))
5284+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
5285+ // Picked as well as moved: the row a
5286+ // press lands on is the row the arrows
5287+ // carry on from.
5288+ this.silence_field = n;
5289+ this.nudge_silence(steps);
5290+ cx.notify();
5291+ }))
5292+ .child(match steps > 0 {
5293+ true => "+",
5294+ false => "−",
5295+ })
5296+ })),
5297+ )
4962 })5298 })
4963 .collect();5299 .collect();
4964 // The two buttons the ask names, side by side: a mode toggle would hide5300 // The two buttons the ask names, side by side: a mode toggle would hide
@@ -5016,7 +5352,7 @@ impl Player {
5016 .text_size(px(11.))5352 .text_size(px(11.))
5017 .text_color(rgb(INK_DIM))5353 .text_color(rgb(INK_DIM))
5018 .child(5354 .child(
5019- "↑↓ picks a setting, ←→ moves it (hold to run it) — the marks on the lane are what would go; esc closes",5355+ "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — the marks on the lane are what would go; esc closes",
5020 ),5356 ),
5021 )5357 )
5022 .children(rows)5358 .children(rows)
@@ -5297,7 +5633,7 @@ impl Player {
5297 // The one item that is not about this clip says so, and says it5633 // The one item that is not about this clip says so, and says it
5298 // here rather than in the registry: the stroke is global too,5634 // here rather than in the registry: the stroke is global too,
5299 // but its row in the keys menu is not sitting on a clip.5635 // but its row in the keys menu is not sitting on a clip.
5300- let label = if action == ActionId::ToggleMute {5636+ let label = if matches!(action, ActionId::ToggleMute | ActionId::Paste) {
5301 format!("{} (global)", action.label())5637 format!("{} (global)", action.label())
5302 } else {5638 } else {
5303 action.label().to_string()5639 action.label().to_string()
@@ -5344,7 +5680,10 @@ impl Player {
5344 let (x, y) = menu_at(5680 let (x, y) = menu_at(
5345 menu.at,5681 menu.at,
5346 viewport,5682 viewport,
5347- MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,5683+ // The cap once the list is longer than it: past that the list
5684+ // scrolls and the card stops growing, exactly as the keybindings and
5685+ // export lists do.
5686+ MENU_PAD * 2. + (rows.len() as f32 * MENU_ROW_H).min(MENU_ROWS_H),
5348 );5687 );
5349 let full: SharedString = source.path.display().to_string().into();5688 let full: SharedString = source.path.display().to_string().into();
5350 Some(5689 Some(
@@ -5399,7 +5738,18 @@ impl Player {
5399 .when(menu.details, |d| {5738 .when(menu.details, |d| {
5400 d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())5739 d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
5401 })5740 })
5402- .children(rows),5741+ // The list scrolls where the card would otherwise grow
5742+ // past the window's floor -- an item hanging off the
5743+ // bottom edge is an item nobody can click.
5744+ .child(
5745+ div()
5746+ .id("menu-rows")
5747+ .flex()
5748+ .flex_col()
5749+ .max_h(px(MENU_ROWS_H))
5750+ .overflow_y_scroll()
5751+ .children(rows),
5752+ ),
5403 ),5753 ),
5404 )5754 )
5405 }5755 }
@@ -5426,6 +5776,9 @@ impl Player {
5426 // one probe answers for both. Zero before the first paint, which only5776 // one probe answers for both. Zero before the first paint, which only
5427 // costs the labels one frame.5777 // costs the labels one frame.
5428 let bed_w = f32::from(self.ruler.get().size.width);5778 let bed_w = f32::from(self.ruler.get().size.width);
5779+ // The slice being shown, copied out once: every box in the row is
5780+ // placed through it, so all of them move together when it does.
5781+ let view = self.view;
5429 let clips = self5782 let clips = self
5430 .session5783 .session
5431 .as_ref()5784 .as_ref()
@@ -5563,7 +5916,7 @@ impl Player {
5563 .and_then(|s| sources.iter().position(|o| o.path == s.path))5916 .and_then(|s| sources.iter().position(|o| o.path == s.path))
5564 .unwrap_or(clip.source),5917 .unwrap_or(clip.source),
5565 );5918 );
5566- let width = width_frac(len, duration);5919+ let width = view.width_frac(len, duration);
5567 let label = sources.get(clip.source).map(|s| file_name(&s.path));5920 let label = sources.get(clip.source).map(|s| file_name(&s.path));
5568 let wave = sources5921 let wave = sources
5569 .get(clip.source)5922 .get(clip.source)
@@ -5587,7 +5940,11 @@ impl Player {
5587 .absolute()5940 .absolute()
5588 .top_0()5941 .top_0()
5589 .h_full()5942 .h_full()
5590- .left(relative(start_frac(start, duration)))5943+ // Negative once the clip's head has been scrolled
5944+ // off the left edge: the bed clips what hangs out
5945+ // of it, so a half-visible clip is drawn as the
5946+ // half of itself that is on screen.
5947+ .left(relative(view.frac_at(start, duration)))
5591 .w(relative(width))5948 .w(relative(width))
5592 .overflow_hidden()5949 .overflow_hidden()
5593 .rounded(px(3.))5950 .rounded(px(3.))
@@ -5736,8 +6093,12 @@ impl Player {
5736 .absolute()6093 .absolute()
5737 .top_0()6094 .top_0()
5738 .h_full()6095 .h_full()
5739- .left(relative(start_frac(f64::from(at) / self.fps, duration)))6096+ .left(relative(
5740- .w(relative(width_frac(f64::from(len) / self.fps, duration)))6097+ view.frac_at(f64::from(at) / self.fps, duration),
6098+ ))
6099+ .w(relative(
6100+ view.width_frac(f64::from(len) / self.fps, duration),
6101+ ))
5741 .bg(rgba(0x4a9effaa))6102 .bg(rgba(0x4a9effaa))
5742 }),6103 }),
5743 )6104 )
@@ -6047,6 +6408,28 @@ fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -
6047 picked.is_some() && timeline && !exporting6408 picked.is_some() && timeline && !exporting
6048 }6409 }
6049 6410
6411+/// What is left on the clipboard after the library row at `removed` was taken
6412+/// out. A copied clip names its file by *index* into the source list
6413+/// (`engine::Clip::source`) and a removal renumbers that list
6414+/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste
6415+/// **a different file** -- the next one along -- over the range it was copied
6416+/// from.
6417+///
6418+/// The clip's own file gone means there is nothing to paste: `None`, and the
6419+/// next paste says the clipboard is empty rather than putting some other take
6420+/// down. Every index past it moves down by one, exactly as the lanes' clips do.
6421+fn clipboard_after_remove(clip: Option<Clip>, removed: usize) -> Option<Clip> {
6422+ let mut clip = clip?;
6423+ match clip.source.cmp(&removed) {
6424+ std::cmp::Ordering::Equal => None,
6425+ std::cmp::Ordering::Greater => {
6426+ clip.source -= 1;
6427+ Some(clip)
6428+ }
6429+ std::cmp::Ordering::Less => Some(clip),
6430+ }
6431+}
6432+
6050 /// One library row: a file and one of its audio streams. Plain data, planned6433 /// One library row: a file and one of its audio streams. Plain data, planned
6051 /// before anything is drawn -- which rows exist at all is the branchy part.6434 /// before anything is drawn -- which rows exist at all is the branchy part.
6052 #[derive(Debug, PartialEq)]6435 #[derive(Debug, PartialEq)]
@@ -6567,7 +6950,18 @@ enum Repeat {
6567 fn repeats(scope: Repeat, key: &str, action: Option<ActionId>) -> bool {6950 fn repeats(scope: Repeat, key: &str, action: Option<ActionId>) -> bool {
6568 match scope {6951 match scope {
6569 Repeat::Card => matches!(key, "up" | "down" | "left" | "right"),6952 Repeat::Card => matches!(key, "up" | "down" | "left" | "right"),
6570- Repeat::Keymap => matches!(action, Some(ActionId::VolumeUp | ActionId::VolumeDown)),6953+ Repeat::Keymap => matches!(
6954+ action,
6955+ Some(
6956+ ActionId::VolumeUp
6957+ | ActionId::VolumeDown
6958+ // A zoom is a value being moved as much as a level is:
6959+ // held, it runs from the whole timeline down to a handful
6960+ // of frames and stops there. The fit is one press.
6961+ | ActionId::ZoomIn
6962+ | ActionId::ZoomOut
6963+ )
6964+ ),
6571 Repeat::Nothing => false,6965 Repeat::Nothing => false,
6572 }6966 }
6573 }6967 }
@@ -6665,14 +7059,127 @@ fn width_frac(len: f64, total: f64) -> f32 {
6665 if total > 0. { (len / total) as f32 } else { 1. }7059 if total > 0. { (len / total) as f32 } else { 1. }
6666 }7060 }
6667 7061
6668-/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline7062+/// One press of a zoom key, or one notch of ctrl+wheel.
6669-/// with no length pins this to the left edge -- a full-width offset would push7063+const ZOOM_STEP: f32 = 1.25;
6670-/// the box out of the lane it belongs to.7064+
6671-fn start_frac(start: f64, total: f64) -> f32 {7065+/// How few frames the bed may be narrowed down to. Past this there is nothing
6672- if total > 0. {7066+/// left to aim at -- a single frame across a whole window is a wall of colour,
6673- (start / total).clamp(0., 1.) as f327067+/// not an edit surface.
6674- } else {7068+const ZOOM_MIN_FRAMES: f64 = 8.;
6675- 0.7069+
7070+/// Which slice of the timeline the ruler and the lanes are showing: `zoom` is
7071+/// how many times the whole of it the bed is now worth, and `start` the moment
7072+/// at the bed's left edge. The one place frames become pixels -- every box, the
7073+/// playhead, a seek and a trim all go through it, so none of them can drift
7074+/// away from the others when the view moves.
7075+///
7076+/// [`View::default`] is the whole timeline across the bed, which is what the
7077+/// panel drew before there was a zoom at all: at zoom 1 `start` is pinned to 0
7078+/// and every fraction here is the one [`width_frac`] and `start_frac` gave.
7079+#[derive(Clone, Copy, Debug, PartialEq)]
7080+struct View {
7081+ zoom: f32,
7082+ start: f64,
7083+}
7084+
7085+impl Default for View {
7086+ fn default() -> Self {
7087+ View {
7088+ zoom: 1.,
7089+ start: 0.,
7090+ }
7091+ }
7092+}
7093+
7094+impl View {
7095+ /// How much of the timeline is on the bed, in seconds.
7096+ fn span(self, duration: f64) -> f64 {
7097+ duration / f64::from(self.zoom)
7098+ }
7099+
7100+ /// The tightest this timeline may be zoomed: [`ZOOM_MIN_FRAMES`] across the
7101+ /// bed. Never under 1 -- a timeline shorter than that is already at its
7102+ /// floor, and a zoom that cannot fit the whole of it is not a zoom.
7103+ fn max_zoom(duration: f64, fps: f64) -> f32 {
7104+ let frames = duration * fps;
7105+ if frames > ZOOM_MIN_FRAMES {
7106+ (frames / ZOOM_MIN_FRAMES) as f32
7107+ } else {
7108+ 1.
7109+ }
7110+ }
7111+
7112+ /// Where a moment sits along the bed, 0 at its left edge and 1 at its
7113+ /// right. Outside that range for a moment scrolled off the view, which is
7114+ /// exactly the negative offset a half-visible clip is drawn at.
7115+ fn frac_at(self, at: f64, duration: f64) -> f32 {
7116+ let span = self.span(duration);
7117+ if span > 0. {
7118+ ((at - self.start) / span) as f32
7119+ } else {
7120+ 0.
7121+ }
7122+ }
7123+
7124+ /// How wide a stretch of `len` seconds is on the bed. More than the whole
7125+ /// bed once zoomed in, which is the point of zooming in.
7126+ fn width_frac(self, len: f64, duration: f64) -> f32 {
7127+ width_frac(len, self.span(duration))
7128+ }
7129+
7130+ /// The moment a pointer at `frac` along the bed is pointing at: the inverse
7131+ /// of [`View::frac_at`], and what every seek and every trim reads.
7132+ fn time_at(self, frac: f32, duration: f64) -> f64 {
7133+ (self.start + f64::from(frac) * self.span(duration)).clamp(0., duration)
7134+ }
7135+
7136+ /// Zoomed by `factor` about `anchor` (0..1 along the bed): whatever moment
7137+ /// was under that point stays under it, so a zoom magnifies what was being
7138+ /// looked at rather than throwing it off the edge.
7139+ fn zoomed(self, factor: f32, anchor: f32, duration: f64, fps: f64) -> Self {
7140+ let at = self.start + f64::from(anchor) * self.span(duration);
7141+ // Clamped *before* the offset is worked out, not after: a press that
7142+ // runs into either stop must still leave the anchor where it is, and a
7143+ // start measured against a zoom the stop then took away would slide it.
7144+ let zoom = (self.zoom * factor).clamp(1., Self::max_zoom(duration, fps));
7145+ let start = at - f64::from(anchor) * View { zoom, start: 0. }.span(duration);
7146+ View { zoom, start }.settled(duration, fps)
7147+ }
7148+
7149+ /// Clamped to the timeline it draws: never wider than the whole of it (the
7150+ /// zoom-out floor is the fit), never tighter than [`View::max_zoom`], and
7151+ /// never scrolled past either end.
7152+ fn settled(self, duration: f64, fps: f64) -> Self {
7153+ let zoom = if self.zoom.is_finite() {
7154+ self.zoom.clamp(1., Self::max_zoom(duration, fps))
7155+ } else {
7156+ 1.
7157+ };
7158+ let span = View { zoom, start: 0. }.span(duration);
7159+ let start = if self.start.is_finite() {
7160+ self.start.clamp(0., (duration - span).max(0.))
7161+ } else {
7162+ 0.
7163+ };
7164+ View { zoom, start }
7165+ }
7166+
7167+ /// The view a playhead at `at` needs: the same one while it is on the bed,
7168+ /// and one centred on it once it has run off -- which is how a zoomed-in
7169+ /// timeline scrolls, during playback and after a seek alike. At the fit
7170+ /// this can never fire, so an unzoomed panel is untouched by it.
7171+ fn following(self, at: f64, duration: f64, fps: f64) -> Self {
7172+ let view = self.settled(duration, fps);
7173+ let span = view.span(duration);
7174+ if at < view.start || at > view.start + span {
7175+ View {
7176+ start: at - span / 2.,
7177+ ..view
7178+ }
7179+ .settled(duration, fps)
7180+ } else {
7181+ view
7182+ }
6676 }7183 }
6677 }7184 }
6678 7185
@@ -7334,17 +7841,20 @@ mod tests {
7334 EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS,7841 EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS,
7335 HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,7842 HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,
7336 LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS,7843 LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS,
7337- MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,7844+ MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H,
7338- SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,7845+ SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,
7339- VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add,7846+ Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,
7340- cancels_export, color_snap, envelope, eq_spectrum, eq_x, eq_y, export_path,7847+ can_add, cancels_export, clipboard_after_remove, color_snap, envelope, eq_spectrum, eq_x,
7341- export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at,7848+ eq_y, export_path, export_settings, format_key, format_line, format_refusal, frac_along,
7342- histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, normalise,7849+ frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked,
7343- nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label,7850+ menu_at, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget,
7344- silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths,7851+ scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, timecode,
7345- unseen_sources, whole_take, width_frac, window_title,7852+ unseen_paths, unseen_sources, whole_take, width_frac, window_title,
7853+ };
7854+ use super::{
7855+ LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows,
7856+ repeats, unscannable,
7346 };7857 };
7347- use super::{LaneKind, Repeat, file_name, file_uri, library_rows, repeats, unscannable};
7348 7858
7349 /// What the file manager is handed: the parts a path keeps as they are, and7859 /// What the file manager is handed: the parts a path keeps as they are, and
7350 /// the ones the bus would otherwise read as something else.7860 /// the ones the bus would otherwise read as something else.
@@ -7693,6 +8203,93 @@ mod tests {
7693 assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");8203 assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
7694 assert_ne!(keymap.display(action), "unbound", "{action:?}");8204 assert_ne!(keymap.display(action), "unbound", "{action:?}");
7695 }8205 }
8206+ // ...and the whole card still fits the 640x360 floor, however many items
8207+ // it grows to: the list is what scrolls past the cap, never the card.
8208+ let items = MENU_ITEMS.len() + 1; // Properties
8209+ assert!(MENU_PAD * 2. + MENU_ROWS_H <= 360., "menu too tall");
8210+ assert!(
8211+ MENU_ROWS_H / MENU_ROW_H >= 12.,
8212+ "too few items visible to scan"
8213+ );
8214+ assert_eq!(
8215+ menu_at(point(px(0.), px(0.)), size(px(640.), px(360.)), {
8216+ MENU_PAD * 2. + (items as f32 * MENU_ROW_H).min(MENU_ROWS_H)
8217+ }),
8218+ (0., 0.)
8219+ );
8220+ }
8221+
8222+ /// The other half of the keys menu's guarantee, and the audit this batch was
8223+ /// asked for kept as a test: no action may be a stroke and nothing else.
8224+ /// Either the clip menu offers it, or a control in the panel does -- named
8225+ /// here by the id [`control`] is handed, read out of this file's own source
8226+ /// like `no_stroke_is_missing_from_the_keys_menu` reads the key handler.
8227+ #[test]
8228+ fn every_action_is_reachable_without_the_keyboard() {
8229+ use keymap::ActionId;
8230+ let source = include_str!("main.rs")
8231+ .split("#[cfg(test)]")
8232+ .next()
8233+ .unwrap();
8234+ let element = |id: &str| source.contains(&format!("\"{id}\""));
8235+ for action in ActionId::ALL {
8236+ let by_pointer = MENU_ITEMS.contains(&action)
8237+ || match action {
8238+ ActionId::Play => element("transport"),
8239+ // One slot, two states: it starts an export and stops the
8240+ // one it started.
8241+ ActionId::Export | ActionId::CancelExport => element("export"),
8242+ ActionId::Save => element("save"),
8243+ ActionId::Undo => element("undo"),
8244+ ActionId::Resolution => element("resolution"),
8245+ // Three buttons beside it, and the ctrl+wheel on the bar.
8246+ ActionId::ZoomIn => element("zoom-in"),
8247+ ActionId::ZoomOut => element("zoom-out"),
8248+ ActionId::ZoomFit => element("zoom-fit"),
8249+ ActionId::AddVideoLane => element("add-video-lane"),
8250+ ActionId::AddAudioLane => element("add-audio-lane"),
8251+ // The × in a lane's own header, which takes any track and
8252+ // not only the last one.
8253+ ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => {
8254+ source.contains("this.remove_lane(lane, cx)")
8255+ }
8256+ ActionId::ToggleMute => element("volume"),
8257+ ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"),
8258+ // The ruler seeks anywhere the pointer points; the frame and
8259+ // the second are the keyboard's finer grain of that move.
8260+ ActionId::StepBack
8261+ | ActionId::StepForward
8262+ | ActionId::JumpBack
8263+ | ActionId::JumpForward
8264+ | ActionId::GoStart
8265+ | ActionId::GoEnd => element("ruler"),
8266+ // A press on a clip is the selection, group and all.
8267+ ActionId::Select | ActionId::SelectNext | ActionId::SelectPrev => {
8268+ source.contains("this.select((lane, i), cx)")
8269+ }
8270+ _ => false,
8271+ };
8272+ assert!(by_pointer, "{action:?} is reachable by keyboard only");
8273+ }
8274+ // The card-local strokes have the same rule, and each of them is a thing
8275+ // on its card: the graph and its two buttons, the colour bars and their
8276+ // reset, the speed bar and its presets, and the silence card's rows --
8277+ // whose steppers are the pointer's only way to a threshold.
8278+ for id in [
8279+ "eq-graph",
8280+ "eq-reset",
8281+ "eq-spectrum",
8282+ "color-bar",
8283+ "color-reset",
8284+ "speed-bar",
8285+ "speed-preset",
8286+ "silence-row",
8287+ "silence-step",
8288+ "silence-apply",
8289+ "export-confirm",
8290+ ] {
8291+ assert!(element(id), "{id} is not on any card");
8292+ }
7696 }8293 }
7697 8294
7698 /// What the Detach and Group items do to a real timeline: a music video's8295 /// What the Detach and Group items do to a real timeline: a music video's
@@ -7932,17 +8529,71 @@ mod tests {
7932 .expect("nothing plays av2 any more");8529 .expect("nothing plays av2 any more");
7933 assert_eq!(rows(&session), 1, "the row went with it");8530 assert_eq!(rows(&session), 1, "the row went with it");
7934 assert_eq!(session.sources().len(), 1);8531 assert_eq!(session.sources().len(), 1);
7935- // The one file left cannot go: a project that names none is not one8532+ // The one file left is held to the same rule and no other: its own take
7936- // that reopens.8533+ // is still on the lanes, so it stays...
8534+ let first = session.sources()[0].path.clone();
7937 let refusal = session8535 let refusal = session
7938- .remove_source(&session.sources()[0].path.clone(), 0)8536+ .remove_source(&first, 0)
7939- .expect_err("the last file stays")8537+ .expect_err("its take is still on the timeline")
7940 .to_string();8538 .to_string();
7941- assert!(refusal.contains("only file"), "{refusal}");8539+ assert!(refusal.contains("still plays"), "{refusal}");
8540+ // ...and once nothing plays it, the *last* row goes too. What is left
8541+ // is the empty library `Player::close_session` turns back into the
8542+ // window the editor launches as -- the user-reported bug was that this
8543+ // very removal was refused, leaving a row that could never be taken
8544+ // out.
8545+ assert!(session.delete_clip(Lane::V1, 0));
8546+ session
8547+ .remove_source(&first, 0)
8548+ .expect("the only row goes like any other");
8549+ assert_eq!(rows(&session), 0, "an empty library");
8550+ assert!(session.sources().is_empty());
8551+ // And it is still a session: silent, empty, and asked for its length
8552+ // rather than panicking on a source list that is not there.
8553+ assert_eq!(session.timeline_duration(), 0.0);
8554+ assert!(
8555+ session.save_project(&asset("nothing.edith")).is_err(),
8556+ "a project naming no file could never be opened again, so it is not written"
8557+ );
7942 // A row this timeline never had is refused, not panicked on.8558 // A row this timeline never had is refused, not panicked on.
7943 assert!(session.remove_source(&second, 0).is_err());8559 assert!(session.remove_source(&second, 0).is_err());
7944 }8560 }
7945 8561
8562+ /// The clipboard after a library removal. A copied clip names its file by
8563+ /// index and a removal renumbers the list, so this is the difference
8564+ /// between pasting the take that was copied and pasting **another file**
8565+ /// over the same range ([`clipboard_after_remove`], called by
8566+ /// [`Player::remove_source`]).
8567+ #[test]
8568+ fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
8569+ let clip = |source: usize| Clip {
8570+ start: 0,
8571+ in_frame: 0,
8572+ out_frame: 30,
8573+ source,
8574+ link: None,
8575+ eq: None,
8576+ color: None,
8577+ fit: Default::default(),
8578+ speed: Default::default(),
8579+ };
8580+ // Copied from source 2, source 0 removed: the same file is source 1 now.
8581+ assert_eq!(
8582+ clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source),
8583+ Some(1),
8584+ "the clipboard follows its file down the list"
8585+ );
8586+ // Copied from a source *before* the one that went: untouched.
8587+ assert_eq!(
8588+ clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source),
8589+ Some(0)
8590+ );
8591+ // Copied from the row that was just removed: there is nothing left to
8592+ // paste, and pasting the next file along would be a lie.
8593+ assert!(clipboard_after_remove(Some(clip(1)), 1).is_none());
8594+ assert!(clipboard_after_remove(None, 0).is_none());
8595+ }
8596+
7946 /// The trim-a-clip path through the doors the edge drag uses:8597 /// The trim-a-clip path through the doors the edge drag uses:
7947 /// [`Player::trim_to`] clamps the pointer with `trim_room` and8598 /// [`Player::trim_to`] clamps the pointer with `trim_room` and
7948 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less8599 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
@@ -8369,6 +9020,161 @@ mod tests {
8369 }9020 }
8370 }9021 }
8371 9022
9023+ /// The mapping the whole panel is drawn and clicked through: a moment goes
9024+ /// to a fraction of the bed and comes back the same moment, at every zoom.
9025+ /// The fit is the invariant that matters most -- it must be the arithmetic
9026+ /// the panel did before there was a zoom at all.
9027+ #[test]
9028+ fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() {
9029+ let duration = 20.;
9030+ // The fit: what `start_frac`/`width_frac` used to answer, exactly.
9031+ let fit = View::default();
9032+ for t in [0., 5., 12.5, 20.] {
9033+ assert_eq!(fit.frac_at(t, duration), (t / duration) as f32, "fit at {t}");
9034+ }
9035+ assert_eq!(fit.width_frac(5., duration), width_frac(5., duration));
9036+ for view in [
9037+ fit,
9038+ View {
9039+ zoom: 2.,
9040+ start: 4.,
9041+ },
9042+ View {
9043+ zoom: 8.,
9044+ start: 12.5,
9045+ },
9046+ View {
9047+ zoom: 37.5,
9048+ start: 19.,
9049+ },
9050+ ] {
9051+ let view = view.settled(duration, 30.);
9052+ for frac in [0., 0.25, 0.5, 1.] {
9053+ let at = view.time_at(frac, duration);
9054+ assert!(
9055+ (f64::from(view.frac_at(at, duration)) - f64::from(frac)).abs() < 1e-6,
9056+ "{view:?} round trip at {frac}"
9057+ );
9058+ }
9059+ // A stretch is as wide as the share of the visible slice it takes.
9060+ assert!(
9061+ (f64::from(view.width_frac(view.span(duration), duration)) - 1.).abs() < 1e-6,
9062+ "{view:?} spans the bed"
9063+ );
9064+ }
9065+ }
9066+
9067+ /// The rule that makes a zoom usable: whatever was under the anchor is
9068+ /// still under it afterwards -- the playhead for a key, the pointer for a
9069+ /// ctrl+wheel.
9070+ #[test]
9071+ fn a_zoom_leaves_the_anchor_where_it_was_on_screen() {
9072+ let (duration, fps) = (20., 30.);
9073+ let mut view = View::default();
9074+ for anchor in [0.5f32, 0.25, 0.9] {
9075+ // Well past the zoom-in stop: the anchor holds at the clamp too,
9076+ // which is where it used to slide (the clamp came after the offset).
9077+ for _ in 0..30 {
9078+ let at = view.time_at(anchor, duration);
9079+ let zoomed = view.zoomed(ZOOM_STEP, anchor, duration, fps);
9080+ // Only where the anchor is not pinned by an edge of the
9081+ // timeline: a view already against an end cannot slide further.
9082+ let pinned = zoomed.start <= 0. || zoomed.start + zoomed.span(duration) >= duration;
9083+ if !pinned {
9084+ assert!(
9085+ (f64::from(zoomed.frac_at(at, duration)) - f64::from(anchor)).abs() < 1e-6,
9086+ "{at} moved: {view:?} -> {zoomed:?}"
9087+ );
9088+ }
9089+ assert!(zoomed.zoom >= view.zoom, "and it did zoom in");
9090+ view = zoomed;
9091+ }
9092+ }
9093+ }
9094+
9095+ /// Both stops: out is the whole timeline (which is where the panel starts,
9096+ /// so nothing regressed for anyone who never zooms), in is a handful of
9097+ /// frames -- and neither can scroll off an end.
9098+ #[test]
9099+ fn zoom_stops_at_the_whole_timeline_and_at_a_handful_of_frames() {
9100+ let (duration, fps) = (20., 30.);
9101+ let mut view = View::default();
9102+ for _ in 0..200 {
9103+ view = view.zoomed(1. / ZOOM_STEP, 0.5, duration, fps);
9104+ }
9105+ assert_eq!(view, View::default(), "zoomed out is the fit");
9106+ for _ in 0..200 {
9107+ view = view.zoomed(ZOOM_STEP, 0.5, duration, fps);
9108+ }
9109+ assert_eq!(
9110+ (view.span(duration) * fps).round(),
9111+ ZOOM_MIN_FRAMES,
9112+ "tightest is a handful of frames"
9113+ );
9114+ // Against the far end, the slice still ends at the last frame.
9115+ let end = View {
9116+ zoom: view.zoom,
9117+ start: 1e6,
9118+ }
9119+ .settled(duration, fps);
9120+ assert!((end.start + end.span(duration) - duration).abs() < 1e-9);
9121+ assert!(
9122+ View {
9123+ zoom: view.zoom,
9124+ start: -5.
9125+ }
9126+ .settled(duration, fps)
9127+ .start
9128+ == 0.
9129+ );
9130+ // A timeline too short to zoom into, and one with no length at all,
9131+ // both stay at the fit rather than dividing by nothing.
9132+ assert_eq!(View::max_zoom(0.1, fps), 1.);
9133+ assert_eq!(View::default().settled(0., fps), View::default());
9134+ assert_eq!(View::default().frac_at(3., 0.), 0.);
9135+ assert_eq!(View::default().time_at(0.5, 0.), 0.);
9136+ }
9137+
9138+ /// What makes a zoomed timeline follow the playing head: off the bed at
9139+ /// either end pulls the view onto it, and on the bed it never moves -- a
9140+ /// view that jumped every frame would be unreadable.
9141+ #[test]
9142+ fn the_view_follows_a_playhead_that_runs_off_the_bed() {
9143+ let (duration, fps) = (20., 30.);
9144+ let view = View {
9145+ zoom: 4.,
9146+ start: 5.,
9147+ }
9148+ .settled(duration, fps);
9149+ assert_eq!(view.span(duration), 5.);
9150+ // Inside: untouched, whichever part of the slice it is in.
9151+ for at in [5., 7.5, 10.] {
9152+ assert_eq!(view.following(at, duration, fps), view, "{at} is on the bed");
9153+ }
9154+ // Past the right edge, as playback does it: the head comes back on the
9155+ // bed, and the zoom is not changed by the scroll.
9156+ let moved = view.following(12., duration, fps);
9157+ assert_eq!(moved.zoom, view.zoom);
9158+ assert!(moved.start > view.start, "scrolled forward");
9159+ assert!(
9160+ moved.frac_at(12., duration) > 0. && moved.frac_at(12., duration) < 1.,
9161+ "and the playhead is on screen"
9162+ );
9163+ // A seek back behind the slice does the same the other way.
9164+ let back = view.following(1., duration, fps);
9165+ assert!(back.start < view.start);
9166+ assert!(back.frac_at(1., duration) >= 0.);
9167+ // At the fit there is nothing to follow: the whole timeline is on the
9168+ // bed already, so no playhead can move it.
9169+ for at in [0., 10., 20.] {
9170+ assert_eq!(
9171+ View::default().following(at, duration, fps),
9172+ View::default(),
9173+ "the fit never scrolls"
9174+ );
9175+ }
9176+ }
9177+
8372 #[test]9178 #[test]
8373 fn clip_boxes_split_the_lane_by_duration() {9179 fn clip_boxes_split_the_lane_by_duration() {
8374 // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.9180 // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.
@@ -8951,11 +9757,20 @@ mod tests {
8951 // value being moved.9757 // value being moved.
8952 assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp)));9758 assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp)));
8953 assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown)));9759 assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown)));
9760+ // ...and the zoom pair, which runs the view the way they run the level.
9761+ assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn)));
9762+ assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit)));
8954 for action in ActionId::ALL {9763 for action in ActionId::ALL {
8955 let held = repeats(Repeat::Keymap, "k", Some(action));9764 let held = repeats(Repeat::Keymap, "k", Some(action));
8956 assert_eq!(9765 assert_eq!(
8957 held,9766 held,
8958- matches!(action, ActionId::VolumeUp | ActionId::VolumeDown),9767+ matches!(
9768+ action,
9769+ ActionId::VolumeUp
9770+ | ActionId::VolumeDown
9771+ | ActionId::ZoomIn
9772+ | ActionId::ZoomOut
9773+ ),
8959 "{action:?} on a hold"9774 "{action:?} on a hold"
8960 );9775 );
8961 }9776 }
@@ -8989,8 +9804,11 @@ mod tests {
8989 <= 360.,9804 <= 360.,
8990 "card too tall"9805 "card too tall"
8991 );9806 );
8992- // Its rows and buttons are clicked, so WCAG 2.5.8 binds them.9807+ // Its rows, its steppers and its buttons are clicked, so WCAG 2.5.8
9808+ // binds them: a stepper is `HIT_MIN` square inside a row of that height.
8993 assert!(KEYS_ROW_H >= HIT_MIN);9809 assert!(KEYS_ROW_H >= HIT_MIN);
9810+ // ...and the pair of them fits beside the widest value the card prints.
9811+ assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value");
8994 // A "speed-up" is never a slow-down: the rate stops above real time at9812 // A "speed-up" is never a slow-down: the rate stops above real time at
8995 // one end and at what a clip can hold at the other, whatever the keys9813 // one end and at what a clip can hold at the other, whatever the keys
8996 // ask for. A silence played *slower* would make the timeline longer,9814 // ask for. A silence played *slower* would make the timeline longer,
@@ -9176,10 +9994,9 @@ mod tests {
9176 assert!(show_label(400.));9994 assert!(show_label(400.));
9177 assert!(!show_label(LABEL_MIN_W - 0.1));9995 assert!(!show_label(LABEL_MIN_W - 0.1));
9178 // A timeline with no length must not put a box outside its lane.9996 // A timeline with no length must not put a box outside its lane.
9179- assert_eq!(start_frac(3., 0.), 0.);9997+ let fit = View::default();
9180- assert_eq!(start_frac(1., 4.), 0.25);9998+ assert_eq!(fit.frac_at(3., 0.), 0.);
9181- // Past the end clamps rather than running off the bed.9999+ assert_eq!(fit.frac_at(1., 4.), 0.25);
9182- assert_eq!(start_frac(8., 4.), 1.);
9183 }10000 }
9184 10001
9185 #[test]10002 #[test]
@@ -9544,6 +10361,9 @@ fn main() {
9544 eos: false,10361 eos: false,
9545 done: false,10362 done: false,
9546 ruler: Rc::default(),10363 ruler: Rc::default(),
10364+ // The whole timeline across the bed, which is where a
10365+ // project opens: zooming is something the user asks for.
10366+ view: View::default(),
9547 selected: None,10367 selected: None,
9548 context_menu: None,10368 context_menu: None,
9549 library_menu: None,10369 library_menu: None,
crates/engine-hw/src/lib.rsmodified+101 -17
@@ -35,7 +35,8 @@ use cros_codecs::encoder::{
35 };35 };
36 use cros_codecs::image_processing::nv12_to_i420;36 use cros_codecs::image_processing::nv12_to_i420;
37 use cros_codecs::libva::{37 use cros_codecs::libva::{
38- Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile,38+ Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat,
39+ VAProfile,
39 };40 };
40 use cros_codecs::video_frame::VideoFrame;41 use cros_codecs::video_frame::VideoFrame;
41 use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};42 use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
@@ -58,11 +59,16 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
58 /// still loads and still decodes H.264 (it simply refuses the newer codecs'59 /// still loads and still decodes H.264 (it simply refuses the newer codecs'
59 /// files at `Demuxer`).60 /// files at `Demuxer`).
60 ///61 ///
61-/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP962+/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main.
62-/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV1263+/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit
63-/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses64+/// I420 every frame here is ([`Session::emit`]).
64-/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool65+///
65-/// selected from the stream info.66+/// ponytail: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample
67+/// interface all the way to the renderer. That costs the low two bits of a Main
68+/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every
69+/// stage between here and the texture upload, not to this file.
70+/// VP9 profile 2 and 10-bit AV1 are still refused by `Demuxer`: neither codec
71+/// states its depth where this reads it.
66 enum Decoder {72 enum Decoder {
67 H264(Dec<H264>),73 H264(Dec<H264>),
68 Hevc(Dec<H265>),74 Hevc(Dec<H265>),
@@ -97,8 +103,12 @@ const STALL_LIMIT: u32 = 10_000;
97 103
98 struct Session {104 struct Session {
99 decoder: Decoder,105 decoder: Decoder,
100- /// NV12 descriptor for `vaGetImage`, queried once at open.106+ /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
107+ /// queried once at open.
101 nv12_format: VAImageFormat,108 nv12_format: VAImageFormat,
109+ /// Whether the surfaces are P010 rather than NV12, which is the one thing
110+ /// the read-back has to do differently.
111+ ten_bit: bool,
102 pool: FramePool<GenericDmaVideoFrame>,112 pool: FramePool<GenericDmaVideoFrame>,
103 demuxer: Demuxer,113 demuxer: Demuxer,
104 meta: VhMeta,114 meta: VhMeta,
@@ -122,23 +132,35 @@ struct Session {
122 /// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object132 /// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
123 /// with two planes at known offsets, which is exactly what the descriptor in133 /// with two planes at known offsets, which is exactly what the descriptor in
124 /// `GenericDmaVideoFrame` emits.134 /// `GenericDmaVideoFrame` emits.
135+///
136+/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0
137+/// shape with 16-bit samples, so the buffer is simply twice as wide.
125 fn alloc_nv12(138 fn alloc_nv12(
126 gbm: &gbm::Device<std::fs::File>,139 gbm: &gbm::Device<std::fs::File>,
127 coded: Resolution,140 coded: Resolution,
141+ ten_bit: bool,
128 ) -> Result<GenericDmaVideoFrame, String> {142 ) -> Result<GenericDmaVideoFrame, String> {
129 let rows = coded.height + coded.height.div_ceil(2);143 let rows = coded.height + coded.height.div_ceil(2);
144+ let width = coded.width * if ten_bit { 2 } else { 1 };
130 let bo = gbm145 let bo = gbm
131- .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)146+ .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
132- .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;147+ .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?;
133 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;148 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
134 let fd = bo.fd().map_err(|e| e.to_string())?;149 let fd = bo.fd().map_err(|e| e.to_string())?;
135- GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch))150+ GenericDmaVideoFrame::new(
151+ vec![std::fs::File::from(fd)],
152+ nv12_layout(coded, pitch, ten_bit),
153+ )
136 }154 }
137 155
138-/// Two NV12 planes packed one after the other in a single buffer object.156+/// Two NV12 (or P010) planes packed one after the other in a single buffer
139-fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout {157+/// object.
158+fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout {
140 FrameLayout {159 FrameLayout {
141- format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),160+ format: (
161+ Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }),
162+ 0, /* DRM_FORMAT_MOD_LINEAR */
163+ ),
142 size: coded,164 size: coded,
143 planes: vec![165 planes: vec![
144 PlaneLayout {166 PlaneLayout {
@@ -186,11 +208,21 @@ impl Session {
186 fn open(path: &Path) -> Option<Self> {208 fn open(path: &Path) -> Option<Self> {
187 let (meta, demuxer) = Demuxer::open(path).ok()?;209 let (meta, demuxer) = Demuxer::open(path).ok()?;
188 let (display, gbm) = open_devices()?;210 let (display, gbm) = open_devices()?;
211+ // A 10-bit stream decodes into P010 surfaces and is read back through a
212+ // P010 image; a driver that has no such image format is one this cannot
213+ // read 10-bit off at all, which is a null session and a software
214+ // fallback like any other refusal here.
215+ let ten_bit = demuxer.bit_depth() > 8;
216+ let want = if ten_bit {
217+ VA_FOURCC_P010
218+ } else {
219+ VA_FOURCC_NV12
220+ };
189 let nv12_format = display221 let nv12_format = display
190 .query_image_formats()222 .query_image_formats()
191 .ok()?223 .ok()?
192 .into_iter()224 .into_iter()
193- .find(|f| f.fourcc == VA_FOURCC_NV12)?;225+ .find(|f| f.fourcc == want)?;
194 let decoder = match meta.codec {226 let decoder = match meta.codec {
195 Codec::H264 => {227 Codec::H264 => {
196 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)228 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
@@ -206,11 +238,12 @@ impl Session {
206 }238 }
207 };239 };
208 let pool = FramePool::new(move |info: &StreamInfo| {240 let pool = FramePool::new(move |info: &StreamInfo| {
209- alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")241+ alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")
210 });242 });
211 Some(Self {243 Some(Self {
212 decoder,244 decoder,
213 nv12_format,245 nv12_format,
246+ ten_bit,
214 pool,247 pool,
215 demuxer,248 demuxer,
216 meta: VhMeta {249 meta: VhMeta {
@@ -350,6 +383,20 @@ impl Session {
350 383
351 let (dst_y, rest) = self.out.split_at_mut(self.luma);384 let (dst_y, rest) = self.out.split_at_mut(self.luma);
352 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);385 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
386+ if self.ten_bit {
387+ p010_to_i420(
388+ &data[va.offsets[Y_PLANE] as usize..],
389+ va.pitches[Y_PLANE] as usize,
390+ dst_y,
391+ &data[va.offsets[UV_PLANE] as usize..],
392+ va.pitches[UV_PLANE] as usize,
393+ dst_u,
394+ dst_v,
395+ w,
396+ h,
397+ );
398+ return;
399+ }
353 nv12_to_i420(400 nv12_to_i420(
354 &data[va.offsets[Y_PLANE] as usize..],401 &data[va.offsets[Y_PLANE] as usize..],
355 va.pitches[Y_PLANE] as usize,402 va.pitches[Y_PLANE] as usize,
@@ -383,6 +430,43 @@ impl Session {
383 }430 }
384 }431 }
385 432
433+/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface
434+/// whose samples are 16-bit little-endian with the value in the **high** bits,
435+/// which is what P010 means. The high byte of each pair is therefore the 10-bit
436+/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a
437+/// second read of the low byte costs more than the half-bit it would buy.
438+fn p010_to_i420(
439+ src_y: &[u8],
440+ src_y_pitch: usize,
441+ dst_y: &mut [u8],
442+ src_uv: &[u8],
443+ src_uv_pitch: usize,
444+ dst_u: &mut [u8],
445+ dst_v: &mut [u8],
446+ width: usize,
447+ height: usize,
448+) {
449+ for row in 0..height {
450+ let src = &src_y[row * src_y_pitch..];
451+ let dst = &mut dst_y[row * width..row * width + width];
452+ for (x, out) in dst.iter_mut().enumerate() {
453+ *out = src[2 * x + 1];
454+ }
455+ }
456+ let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
457+ for row in 0..ch {
458+ let src = &src_uv[row * src_uv_pitch..];
459+ let (u, v) = (
460+ &mut dst_u[row * cw..row * cw + cw],
461+ &mut dst_v[row * cw..row * cw + cw],
462+ );
463+ for x in 0..cw {
464+ u[x] = src[4 * x + 1];
465+ v[x] = src[4 * x + 3];
466+ }
467+ }
468+}
469+
386 /// Opens `path` for hardware decode, positioned so the first470 /// Opens `path` for hardware decode, positioned so the first
387 /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean471 /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
388 /// the start of the stream). Returns null on any failure at all: no libva472 /// the start of the stream). Returns null on any failure at all: no libva
@@ -657,8 +741,8 @@ impl EncSession {
657 };741 };
658 // Allocated at the aligned size, so the buffer's pitch is never smaller742 // Allocated at the aligned size, so the buffer's pitch is never smaller
659 // than a padded row.743 // than a padded row.
660- let frame = alloc_nv12(&gbm, coded).ok()?;744+ let frame = alloc_nv12(&gbm, coded, false).ok()?;
661- let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);745+ let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false);
662 Some(Self {746 Some(Self {
663 encoder,747 encoder,
664 h264: !av1,748 h264: !av1,
crates/engine/Cargo.tomlmodified+15 -6
@@ -23,18 +23,26 @@ image = { version = "0.25", default-features = false, features = [
23 ] }23 ] }
24 mp4 = "0.14"24 mp4 = "0.14"
25 rusty_h264 = { version = "0.8", default-features = false }25 rusty_h264 = { version = "0.8", default-features = false }
26-# The AAC-LC *encoder*, so an mp4's sound can be a mix rather than a copy: an26+# Both halves of AAC, and the only crate here that is asked for both. The
27-# equalized (or otherwise processed) lane has to be decoded, and what is decoded27+# *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or
28-# has to be encoded again. Pure Rust with no C or FFI, Apache-2.0, same family28+# otherwise processed) lane has to be decoded, and what is decoded has to be
29-# as `rusty_h264` above. Nothing else in the ecosystem encodes AAC without29+# encoded again. The *decoder*, because symphonia's own refuses anything wider
30-# linking Fraunhofer's C library, which this project's no-install rule forbids.30+# than stereo outright (`aac/mod.rs:93`, "aac: aac too complex") and a 5.1 film
31+# soundtrack in an mkv is exactly that -- this one hands 5.1 back already
32+# reordered into FL, FR, FC, LFE, BL, BR, which is the order the downmix in
33+# `audio` folds. Pure Rust with no C or FFI, Apache-2.0, same family as
34+# `rusty_h264` above. Nothing else in the ecosystem encodes AAC without linking
35+# Fraunhofer's C library, which this project's no-install rule forbids. Built
36+# from `vendor/rusty_aac` -- see the patch table in the workspace manifest.
31 rusty_aac = "0.5"37 rusty_aac = "0.5"
32 symphonia-core = "0.6"38 symphonia-core = "0.6"
33 symphonia-codec-aac = "0.6"39 symphonia-codec-aac = "0.6"
34 # The umbrella crate for the standalone audio files: one dependency instead of40 # The umbrella crate for the standalone audio files: one dependency instead of
35 # seven, and its `default::get_probe`/`get_codecs` are the registries this would41 # seven, and its `default::get_probe`/`get_codecs` are the registries this would
36 # otherwise hand-build. Explicit feature list rather than the default one -- no42 # otherwise hand-build. Explicit feature list rather than the default one -- no
37-# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits.43+# ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus
44+# `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of
45+# a Matroska video file is read, the picture having its own demuxer here.
38 # There is no opus/ac3/dts feature at any symphonia version, which is why those46 # There is no opus/ac3/dts feature at any symphonia version, which is why those
39 # are refused rather than promised.47 # are refused rather than promised.
40 symphonia = { version = "0.6", default-features = false, features = [48 symphonia = { version = "0.6", default-features = false, features = [
@@ -44,6 +52,7 @@ symphonia = { version = "0.6", default-features = false, features = [
44 "id3v1",52 "id3v1",
45 "id3v2",53 "id3v2",
46 "isomp4",54 "isomp4",
55+ "mkv",
47 "mp3",56 "mp3",
48 "ogg",57 "ogg",
49 "pcm",58 "pcm",
crates/engine/src/audio.rsmodified+203 -33
@@ -6,7 +6,9 @@
6 //! it always has -- that path also yields the raw access units the export6 //! it always has -- that path also yields the raw access units the export
7 //! copies, which is the only reason it is kept separate -- and a standalone7 //! copies, which is the only reason it is kept separate -- and a standalone
8 //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through8 //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through
9-//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same9+//! symphonia's own format probe, as does the AAC track of a **Matroska** file:
10+//! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to
11+//! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same
10 //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the12 //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the
11 //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo13 //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo
12 //! timeline. Everything downstream of [`Track`] sees the14 //! timeline. Everything downstream of [`Track`] sees the
@@ -268,14 +270,23 @@ impl AudioSession {
268 eqs: &[Option<EqParams>],270 eqs: &[Option<EqParams>],
269 speeds: &[Option<crate::project::Stretch>],271 speeds: &[Option<crate::project::Stretch>],
270 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {272 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
271- let Some((path, stream)) = sources.first() else {273+ // The first source that could have a track, which is not always index 0:
274+ // a still image has none, and one at the front of the list (a save
275+ // renumbers, a library removal moves indexes) would be opened as a
276+ // broken audio file and take the whole timeline's sound down with it.
277+ // The same rule `PlaybackSession` probes by (`audio_source_of`).
278+ let Some((at, (path, stream))) = sources
279+ .iter()
280+ .enumerate()
281+ .find(|(_, (path, _))| !crate::is_image(path))
282+ else {
272 return Ok(None);283 return Ok(None);
273 };284 };
274 let Some(first) = Track::open(path, *stream)? else {285 let Some(first) = Track::open(path, *stream)? else {
275 return Ok(None);286 return Ok(None);
276 };287 };
277- // The timeline's meta is the first source's: policy makes every other288+ // The timeline's meta is that source's: policy makes every other source
278- // source match it, and the checks below hold them to that.289+ // match it, and the checks below hold them to that.
279 let meta = AudioMeta {290 let meta = AudioMeta {
280 sample_rate: first.sample_rate(),291 sample_rate: first.sample_rate(),
281 channels: first.channels()?,292 channels: first.channels()?,
@@ -286,7 +297,7 @@ impl AudioSession {
286 first.check_decoder()?;297 first.check_decoder()?;
287 298
288 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();299 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
289- tracks[0] = Some(first);300+ tracks[at] = Some(first);
290 for &(source, ..) in segs {301 for &(source, ..) in segs {
291 let Some(source) = source else {302 let Some(source) = source else {
292 continue; // a gap opens no file303 continue; // a gap opens no file
@@ -459,8 +470,9 @@ impl AudioSession {
459 let mut meta = None;470 let mut meta = None;
460 let mut rxs = Vec::with_capacity(lanes.len());471 let mut rxs = Vec::with_capacity(lanes.len());
461 for (i, segs) in lanes.iter().enumerate() {472 for (i, segs) in lanes.iter().enumerate() {
462- // Every lane probes the same source 0, so the metas agree by473+ // Every lane takes its meta from the same source, so the metas
463- // construction; `None` from any of them is a silent timeline.474+ // agree by construction; `None` from any of them is a silent
475+ // timeline.
464 let flat = Vec::new();476 let flat = Vec::new();
465 let plain = Vec::new();477 let plain = Vec::new();
466 let Some((lane_meta, rx)) = Self::open_multi_streams_speed(478 let Some((lane_meta, rx)) = Self::open_multi_streams_speed(
@@ -490,14 +502,15 @@ impl AudioSession {
490 /// -- nothing to tell the user there. Header only, and only worth calling502 /// -- nothing to tell the user there. Header only, and only worth calling
491 /// once the open has already returned no audio.503 /// once the open has already returned no audio.
492 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {504 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
493- // Matroska: the demuxer reads its picture and nothing else yet, so a505+ // Matroska: AAC is read out of one ([`Track::open`]) and everything
494- // file that has sound is told so by name rather than playing silent506+ // else -- Opus, AC-3, DTS, none of which symphonia decodes at any
495- // with no reason given. A Matroska file with no audio track at all507+ // version -- is named rather than left playing silent with no reason
496- // returns `None` here like any other silent file.508+ // given. A Matroska file with no audio track at all returns `None` here
509+ // like any other silent file.
497 if crate::demux::is_matroska(path.as_ref()) {510 if crate::demux::is_matroska(path.as_ref()) {
498 return Ok(511 return Ok(
499 crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {512 crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {
500- format!("{codec} audio in a Matroska file is not wired to the decoder yet")513+ format!("the {codec} track of this Matroska file cannot be decoded (AAC only)")
501 }),514 }),
502 );515 );
503 }516 }
@@ -546,11 +559,22 @@ impl AudioSession {
546 /// and an ALAC `.m4a` only half is.559 /// and an ALAC `.m4a` only half is.
547 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {560 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
548 let path = path.as_ref();561 let path = path.as_ref();
549- // A Matroska file's audio tracks are not readable here yet ([`Track`]),562+ // A Matroska file has exactly one readable audio stream here -- the
550- // and a stream nothing can open is not one to offer: an mkv lists as563+ // reader's default track ([`SymTrack::open`]) -- so it lists like a
551- // the silent source it currently is.564+ // standalone audio file rather than like an mp4, and one with no
565+ // readable track at all lists as the silent source it is.
552 if crate::demux::is_matroska(path) {566 if crate::demux::is_matroska(path) {
553- return Ok(Vec::new());567+ let Ok(track) = SymTrack::open(path) else {
568+ return Ok(Vec::new());
569+ };
570+ return Ok(vec![StreamInfo {
571+ index: 0,
572+ codec: track.codec.into(),
573+ channels: track.channels,
574+ sample_rate: track.sample_rate,
575+ lang: None,
576+ decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),
577+ }]);
554 }578 }
555 if crate::is_audio(path) {579 if crate::is_audio(path) {
556 let track = SymTrack::open(path)?;580 let track = SymTrack::open(path)?;
@@ -835,6 +859,24 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
835 match Track::open(path, stream)? {859 match Track::open(path, stream)? {
836 None => Ok(None),860 None => Ok(None),
837 Some(Track::Aac(track)) => Ok(Some(track)),861 Some(Track::Aac(track)) => Ok(Some(track)),
862+ // A Matroska source gets its own words: its packets *are* AAC, so
863+ // "export needs AAC audio today" would read as a contradiction. What
864+ // they are not is packets of an mp4 sample table, which is what the
865+ // copy walks -- and refusing beats writing a film with no sound in it.
866+ //
867+ // ponytail: the ceiling is the copy path being written against the mp4
868+ // reader, not anything about the bytes. Upgrade path is the same one
869+ // every other refusal here names -- an AAC encoder, or a `copy_segments`
870+ // that walks a Matroska track -- and either would let this through.
871+ Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
872+ "{}'s sound is AAC inside a Matroska file, which an mp4 export cannot copy: \
873+ it copies packets out of an mp4's own sample table. Export WAV or FLAC for \
874+ the sound, or AV1 for the picture alone",
875+ path.file_name()
876+ .unwrap_or(path.as_os_str())
877+ .to_string_lossy(),
878+ )
879+ .into()),
838 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),880 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
839 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`881 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
840 // sample table can hold, and there is no AAC encoder here to turn it882 // sample table can hold, and there is no AAC encoder here to turn it
@@ -879,11 +921,20 @@ impl Track {
879 /// has exactly one, so any `stream` above 0 there is a promise the file921 /// has exactly one, so any `stream` above 0 there is a promise the file
880 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.922 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
881 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {923 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
882- // A Matroska file's sound is not wired to either reader yet: its picture924+ // A Matroska file goes straight to symphonia, whose `mkv` reader is the
883- // is what this slice delivers, and the source counts as a silent one --925+ // one thing here that reads its packets -- neither mp4 reader can open
884- // which `AudioSession::unsupported` puts into words for the user.926+ // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia
927+ // has no such decoder at any version) leaves the source the silent one
928+ // it always was, which `AudioSession::unsupported` puts into words,
929+ // rather than failing the import of a file whose picture is fine.
885 if crate::demux::is_matroska(path) {930 if crate::demux::is_matroska(path) {
886- return Ok(None);931+ if stream > 0 {
932+ return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
933+ }
934+ return Ok(SymTrack::open(path)
935+ .ok()
936+ .filter(|t| t.decoder().is_ok())
937+ .map(Self::Sym));
887 }938 }
888 let audio_file = crate::is_audio(path);939 let audio_file = crate::is_audio(path);
889 // Ahead of the AAC reader, because that one answers "not AAC" for a940 // Ahead of the AAC reader, because that one answers "not AAC" for a
@@ -996,7 +1047,12 @@ struct SymTrack {
996 reader: Box<dyn FormatReader>,1047 reader: Box<dyn FormatReader>,
997 track_id: u32,1048 track_id: u32,
998 sample_rate: u32,1049 sample_rate: u32,
1050+ /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,
1051+ /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's
1052+ /// decoder folds its own.
999 channels: u16,1053 channels: u16,
1054+ /// What the decoder emits, which is what the fold reads.
1055+ source_channels: u16,
1000 /// Frames per channel of audible audio, `None` when the header does not say.1056 /// Frames per channel of audible audio, `None` when the header does not say.
1001 total_samples: Option<u64>,1057 total_samples: Option<u64>,
1002 /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the1058 /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the
@@ -1051,7 +1107,11 @@ impl SymTrack {
1051 reader,1107 reader,
1052 track_id,1108 track_id,
1053 sample_rate,1109 sample_rate,
1054- channels,1110+ // 5.1 arrives as a stereo source, whatever it was stored as; every
1111+ // other layout is passed through and refused above stereo by
1112+ // [`Track::channels`], where it always was.
1113+ channels: if channels == 6 { 2 } else { channels },
1114+ source_channels: channels,
1055 total_samples: num_frames,1115 total_samples: num_frames,
1056 priming: u64::from(delay.unwrap_or(0)),1116 priming: u64::from(delay.unwrap_or(0)),
1057 time_base,1117 time_base,
@@ -1062,9 +1122,28 @@ impl SymTrack {
1062 1122
1063 /// A fresh decoder: seeking mid-stream leaves state that belongs to the1123 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
1064 /// packets we skipped, exactly as on the AAC path.1124 /// packets we skipped, exactly as on the AAC path.
1065- fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> {1125+ ///
1066- Ok(symphonia::default::get_codecs()1126+ /// Which decoder is not the caller's business, and it is not always
1067- .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?)1127+ /// symphonia's: its AAC decoder refuses anything wider than stereo outright
1128+ /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track
1129+ /// of a film in an mkv, so that one goes to `rusty_aac` instead.
1130+ fn decoder(&self) -> crate::Result<SymDecoder> {
1131+ let fold = self.source_channels != self.channels;
1132+ if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 {
1133+ let asc = self
1134+ .params
1135+ .extra_data
1136+ .as_deref()
1137+ .ok_or("a multichannel AAC track with no AudioSpecificConfig")?;
1138+ let decoder = rusty_aac::AacDecoder::with_config_bytes(asc)
1139+ .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?;
1140+ return Ok(SymDecoder::Aac(Box::new(decoder), fold));
1141+ }
1142+ Ok(SymDecoder::Sym(
1143+ symphonia::default::get_codecs()
1144+ .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
1145+ fold,
1146+ ))
1068 }1147 }
1069 1148
1070 /// `secs` on this source's audible timeline into media samples (priming1149 /// `secs` on this source's audible timeline into media samples (priming
@@ -1080,6 +1159,65 @@ impl SymTrack {
1080 }1159 }
1081 }1160 }
1082 1161
1162+/// One packet in, interleaved f32 out — whichever library did the decoding, and
1163+/// already folded to the layout [`SymTrack::channels`] promised. The flag is
1164+/// that fold: `true` for a 5.1 track, and there is nothing else it can be.
1165+enum SymDecoder {
1166+ Sym(Box<dyn AudioDecoder>, bool),
1167+ /// Boxed because the decoder carries its own IMDCT tables and this enum is
1168+ /// moved into the worker.
1169+ Aac(Box<rusty_aac::AacDecoder>, bool),
1170+}
1171+
1172+impl SymDecoder {
1173+ fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
1174+ match self {
1175+ Self::Sym(decoder, fold) => {
1176+ decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
1177+ fold_5_1(out, *fold);
1178+ }
1179+ Self::Aac(decoder, fold) => {
1180+ let pcm = decoder
1181+ .decode(&packet.data, None)
1182+ .map_err(|e| format!("AAC decode failed: {e}"))?;
1183+ *out = pcm.samples;
1184+ fold_5_1(out, *fold);
1185+ }
1186+ }
1187+ Ok(())
1188+ }
1189+}
1190+
1191+/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of
1192+/// each side join that side at -3 dB, and the LFE is dropped -- it carries no
1193+/// programme a stereo pair could put anywhere. Both outputs are divided by the
1194+/// sum of their own coefficients, so a source at full scale cannot come out
1195+/// clipped; that is what every player does by default.
1196+///
1197+/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders
1198+/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls,
1199+/// Rs, LFE element order into it: `decode.rs:779`).
1200+///
1201+/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands
1202+/// out, which does not normalise and can overload -- so a film plays quieter
1203+/// here than in a player beside it. It is the loudness the AC-3 5.1 path already
1204+/// has (measured within 1.3 dB), so the two agree; the upgrade path is a
1205+/// limiter on the output, at which point the coefficients can go back to 1.0.
1206+fn fold_5_1(samples: &mut Vec<f32>, fold: bool) {
1207+ if !fold {
1208+ return;
1209+ }
1210+ const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2;
1211+ const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE);
1212+ for frame in 0..samples.len() / 6 {
1213+ let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6])
1214+ .expect("six samples of a 5.1 frame");
1215+ samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM;
1216+ samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM;
1217+ }
1218+ samples.truncate(samples.len() / 6 * 2);
1219+}
1220+
1083 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read1221 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read
1084 /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder1222 /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder
1085 /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and1223 /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and
@@ -2086,14 +2224,10 @@ fn run_sym(
2086 if pos >= seg.media_end {2224 if pos >= seg.media_end {
2087 return true; // segment done, on to the next one2225 return true; // segment done, on to the next one
2088 }2226 }
2089- let buf = match decoder.decode(&packet) {2227+ if let Err(e) = decoder.decode(&packet, &mut interleaved) {
2090- Ok(buf) => buf,2228+ eprintln!("audio decode error at sample {pos}: {e}");
2091- Err(e) => {2229+ return true;
2092- eprintln!("audio decode error at sample {pos}: {e}");2230+ }
2093- return true;
2094- }
2095- };
2096- buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
2097 let next = pos + (interleaved.len() / channels) as u64;2231 let next = pos + (interleaved.len() / channels) as u64;
2098 // Reborrowed per packet: the filter memory has to carry across the2232 // Reborrowed per packet: the filter memory has to carry across the
2099 // packet boundary, so this is one `EqState` for the whole segment.2233 // packet boundary, so this is one `EqState` for the whole segment.
@@ -2115,7 +2249,43 @@ fn run_sym(
2115 2249
2116 #[cfg(test)]2250 #[cfg(test)]
2117 mod tests {2251 mod tests {
2118- use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run};2252+ use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run};
2253+
2254+ /// The 5.1 fold: each side keeps its own front channel, takes the centre
2255+ /// and its own surround at -3 dB, drops the LFE, and comes out unable to
2256+ /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR.
2257+ #[test]
2258+ fn five_one_folds_to_stereo_without_clipping() {
2259+ // One frame per channel at full scale, one channel at a time.
2260+ for (channel, (left, right)) in [
2261+ (0, (1.0, 0.0)), // FL
2262+ (1, (0.0, 1.0)), // FR
2263+ (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC
2264+ (3, (0.0, 0.0)), // LFE, dropped
2265+ (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL
2266+ (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR
2267+ ] {
2268+ let mut frame = vec![0.0f32; 6];
2269+ frame[channel] = 1.0;
2270+ fold_5_1(&mut frame, true);
2271+ let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);
2272+ assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame");
2273+ assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2274+ assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2275+ }
2276+ // Every channel at once is what a normalised fold exists for.
2277+ let mut loud = vec![1.0f32; 12];
2278+ fold_5_1(&mut loud, true);
2279+ assert_eq!(loud.len(), 4);
2280+ assert!(
2281+ loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
2282+ "full scale in, full scale out, never past it: {loud:?}"
2283+ );
2284+ // A track that is not 5.1 is handed over untouched.
2285+ let mut stereo = vec![0.5f32, -0.5];
2286+ fold_5_1(&mut stereo, false);
2287+ assert_eq!(stereo, [0.5, -0.5]);
2288+ }
2119 2289
2120 /// A real AAC track: one stts entry, N packets of 1024.2290 /// A real AAC track: one stts entry, N packets of 1024.
2121 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {2291 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
crates/engine/src/demux.rsmodified+151 -57
@@ -6,7 +6,8 @@
6 //! Two containers, one interface: mp4 through the `mp4` crate, Matroska6 //! Two containers, one interface: mp4 through the `mp4` crate, Matroska
7 //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --7 //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --
8 //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in8 //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in
9-//! practice.9+//! practice -- and HEVC rides the same walk, because that is the other codec a
10+//! `.mkv` off a disc arrives in.
10 11
11 use std::fs::File;12 use std::fs::File;
12 use std::io::{BufReader, Read, Seek, SeekFrom};13 use std::io::{BufReader, Read, Seek, SeekFrom};
@@ -97,12 +98,24 @@ impl Demuxer {
97 Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),98 Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),
98 }99 }
99 }100 }
101+
102+ /// Bits per luma sample the stream is coded at: 8 for everything but an
103+ /// HEVC Main 10 track, which decodes into a P010 surface rather than an
104+ /// NV12 one. Not part of [`VideoMeta`] because nothing above the plugin has
105+ /// a use for it -- what comes out of the read-back is 8-bit either way.
106+ pub fn bit_depth(&self) -> u8 {
107+ match self {
108+ Self::Mp4(d) => d.bit_depth,
109+ Self::Mkv(d) => d.bit_depth,
110+ }
111+ }
100 }112 }
101 113
102-/// Whether a path names a Matroska file, which is where AV1 arrives. Extension114+/// Whether a path names a Matroska file, which is where AV1 arrives and where a
103-/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the115+/// film off a disc arrives as HEVC. Extension only, like [`crate::is_audio`]:
104-/// audio path has to know before it opens anything that this file's sound is116+/// the demuxer is what really decides, but the audio path has to know before it
105-/// not one it reads (see [`crate::audio::AudioSession::unsupported`]).117+/// opens anything that this file's sound is read by symphonia's `mkv` reader
118+/// and not by either mp4 one (see [`crate::audio::Track::open`]).
106 pub fn is_matroska(path: &Path) -> bool {119 pub fn is_matroska(path: &Path) -> bool {
107 path.extension()120 path.extension()
108 .and_then(|e| e.to_str())121 .and_then(|e| e.to_str())
@@ -129,6 +142,8 @@ pub struct Mp4Demuxer {
129 /// at all, i.e. every sample is a sync sample.142 /// at all, i.e. every sample is a sync sample.
130 sync_samples: Vec<u32>,143 sync_samples: Vec<u32>,
131 next_sample: u32,144 next_sample: u32,
145+ /// Bits per luma sample; see [`Demuxer::bit_depth`].
146+ bit_depth: u8,
132 }147 }
133 148
134 impl Mp4Demuxer {149 impl Mp4Demuxer {
@@ -172,6 +187,7 @@ impl Mp4Demuxer {
172 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));187 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
173 let mut parameter_sets = Vec::new();188 let mut parameter_sets = Vec::new();
174 let mut nal_length = 4;189 let mut nal_length = 4;
190+ let mut bit_depth = 8;
175 match codec {191 match codec {
176 Codec::H264 => {192 Codec::H264 => {
177 let avcc = &track193 let avcc = &track
@@ -195,9 +211,10 @@ impl Mp4Demuxer {
195 // start without are read out of the file by hand.211 // start without are read out of the file by hand.
196 Codec::Hevc => {212 Codec::Hevc => {
197 let hvcc = hvcc_record(path, track_id)?;213 let hvcc = hvcc_record(path, track_id)?;
198- let (len, sets) = parse_hvcc(&hvcc)?;214+ let (len, sets, depth) = parse_hvcc(&hvcc)?;
199 nal_length = len;215 nal_length = len;
200 parameter_sets = sets;216 parameter_sets = sets;
217+ bit_depth = depth;
201 }218 }
202 // No parameter sets: a VP9 sample is self-contained, and AV1 never219 // No parameter sets: a VP9 sample is self-contained, and AV1 never
203 // reaches this arm at all -- `mp4 0.14` knows no `av01` sample220 // reaches this arm at all -- `mp4 0.14` knows no `av01` sample
@@ -235,6 +252,7 @@ impl Mp4Demuxer {
235 nal_length,252 nal_length,
236 sync_samples,253 sync_samples,
237 next_sample,254 next_sample,
255+ bit_depth,
238 },256 },
239 ))257 ))
240 }258 }
@@ -291,7 +309,7 @@ struct Block {
291 key: bool,309 key: bool,
292 }310 }
293 311
294-/// AV1 out of a Matroska file (`.mkv`/`.webm`).312+/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`).
295 ///313 ///
296 /// The whole segment is walked once at open -- element *headers* only, the block314 /// The whole segment is walked once at open -- element *headers* only, the block
297 /// payloads are seeked over -- because Matroska carries no sample table: the315 /// payloads are seeked over -- because Matroska carries no sample table: the
@@ -300,12 +318,26 @@ struct Block {
300 pub struct MkvDemuxer {318 pub struct MkvDemuxer {
301 file: File,319 file: File,
302 blocks: Vec<Block>,320 blocks: Vec<Block>,
321+ codec: Codec,
303 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of322 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
304 /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream323 /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream
305 /// repeats its sequence header at every keyframe anyway, and cros-codecs324 /// repeats its sequence header at every keyframe anyway, and cros-codecs
306 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is325 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
307 /// free when the encoder already wrote one and load-bearing when it did not.326 /// free when the encoder already wrote one and load-bearing when it did not.
327+ ///
328+ /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
329+ /// an `hvcC` record verbatim -- the same blob, re-injected for the same
330+ /// reason, as the one [`Mp4Demuxer`] carries.
308 config: Vec<u8>,331 config: Vec<u8>,
332+ /// Bytes of the NAL length prefix an HEVC block is written with; unused by
333+ /// AV1, whose block is one temporal unit and carries no prefixes.
334+ nal_length: usize,
335+ /// Bits per luma sample; see [`Demuxer::bit_depth`].
336+ bit_depth: u8,
337+ /// One block's bytes, reused across access units: a 4K HEVC keyframe is a
338+ /// megabyte and it is reframed, not handed over, so the read needs a
339+ /// landing place of its own.
340+ scratch: Vec<u8>,
309 next: usize,341 next: usize,
310 }342 }
311 343
@@ -314,13 +346,28 @@ impl MkvDemuxer {
314 let mut file = File::open(path)?;346 let mut file = File::open(path)?;
315 let end = file.metadata()?.len();347 let end = file.metadata()?.len();
316 let segment = mkv_segment(&mut file, end)?;348 let segment = mkv_segment(&mut file, end)?;
317- let (video, _) = mkv_tracks(&mut file, segment)?;349+ let (video, _, other) = mkv_tracks(&mut file, segment)?;
318- let video = video.ok_or(350+ let video = match video {
319- "no AV1 video track in this Matroska file — AV1 is the only codec read from one",351+ Some(video) => video,
320- )?;352+ // Named, because "no video track" is a lie about a file that has one
353+ // in a codec this does not read.
354+ None => {
355+ return Err(match other {
356+ Some(codec) => format!(
357+ "{codec} video in a Matroska file is not supported — AV1 and HEVC are"
358+ ),
359+ None => "this Matroska file has no video track".to_string(),
360+ }
361+ .into());
362+ }
363+ };
321 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;364 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;
322 if blocks.is_empty() {365 if blocks.is_empty() {
323- return Err("the AV1 track in this Matroska file has no frames".into());366+ return Err(format!(
367+ "the {} track in this Matroska file has no frames",
368+ video.codec.name()
369+ )
370+ .into());
324 }371 }
325 // Timing, in this order: what the track declares, then what its own372 // Timing, in this order: what the track declares, then what its own
326 // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333373 // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333
@@ -350,28 +397,44 @@ impl MkvDemuxer {
350 height: video.height,397 height: video.height,
351 frame_rate,398 frame_rate,
352 frame_count: blocks.len() as u32,399 frame_count: blocks.len() as u32,
353- codec: Codec::Av1,400+ codec: video.codec,
354 };401 };
355 Ok((402 Ok((
356 meta,403 meta,
357 Self {404 Self {
358 file,405 file,
359 blocks,406 blocks,
407+ codec: video.codec,
360 config: video.config,408 config: video.config,
409+ nal_length: video.nal_length,
410+ bit_depth: video.bit_depth,
411+ scratch: Vec::new(),
361 next: 0,412 next: 0,
362 },413 },
363 ))414 ))
364 }415 }
365 416
417+ /// Next access unit in decode order: the block verbatim for AV1, which is
418+ /// one temporal unit already, and Annex-B for HEVC, whose block holds the
419+ /// same length-prefixed NALs an mp4 sample does.
366 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {420 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
367 let Some(&block) = self.blocks.get(self.next) else {421 let Some(&block) = self.blocks.get(self.next) else {
368 return Ok(None);422 return Ok(None);
369 };423 };
370 self.next += 1;424 self.next += 1;
371 let head = if block.key { self.config.len() } else { 0 };425 let head = if block.key { self.config.len() } else { 0 };
372- let mut au = vec![0u8; head + block.len];426+ if self.codec == Codec::Av1 {
373- au[..head].copy_from_slice(&self.config[..head]);427+ let mut au = vec![0u8; head + block.len];
374- read_exact_at(&mut self.file, block.at, &mut au[head..])?;428+ au[..head].copy_from_slice(&self.config[..head]);
429+ read_exact_at(&mut self.file, block.at, &mut au[head..])?;
430+ return Ok(Some(au));
431+ }
432+ let Self { file, scratch, .. } = self;
433+ scratch.resize(block.len, 0);
434+ read_exact_at(file, block.at, scratch)?;
435+ let mut au = Vec::with_capacity(head + block.len + 16);
436+ au.extend_from_slice(&self.config[..head]);
437+ append_annex_b(&self.scratch, self.nal_length, &mut au)?;
375 Ok(Some(au))438 Ok(Some(au))
376 }439 }
377 440
@@ -401,14 +464,17 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
401 Ok(mkv_tracks(&mut file, segment)?.1)464 Ok(mkv_tracks(&mut file, segment)?.1)
402 }465 }
403 466
404-/// What the `Tracks` element says about the AV1 track.467+/// What the `Tracks` element says about the video track.
405 struct MkvVideo {468 struct MkvVideo {
406 number: u64,469 number: u64,
407 width: u32,470 width: u32,
408 height: u32,471 height: u32,
409 default_duration: Option<u64>,472 default_duration: Option<u64>,
410 timestamp_scale: u64,473 timestamp_scale: u64,
474+ codec: Codec,
411 config: Vec<u8>,475 config: Vec<u8>,
476+ nal_length: usize,
477+ bit_depth: u8,
412 }478 }
413 479
414 // Matroska element IDs, written with the leading length marker they carry in480 // Matroska element IDs, written with the leading length marker they carry in
@@ -445,17 +511,18 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
445 Err("no Segment element: not a Matroska file".into())511 Err("no Segment element: not a Matroska file".into())
446 }512 }
447 513
448-/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be514+/// The video track of `segment`, the codec id of its first audio track, and the
449-/// named -- the second is what tells a user why a file with sound plays silent515+/// codec id of a video track this cannot read -- the last two are what tell a
450-/// ([`crate::audio::AudioSession::unsupported`]).516+/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`])
517+/// or refuses to open at all.
451 ///518 ///
452 /// Header only: the walk stops at the first `Cluster`, so this costs a handful519 /// Header only: the walk stops at the first `Cluster`, so this costs a handful
453 /// of seeks whatever the file weighs.520 /// of seeks whatever the file weighs.
454 fn mkv_tracks(521 fn mkv_tracks(
455 file: &mut File,522 file: &mut File,
456 segment: (u64, u64),523 segment: (u64, u64),
457-) -> crate::Result<(Option<MkvVideo>, Option<String>)> {524+) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> {
458- let (mut video, mut audio) = (None, None);525+ let (mut video, mut audio, mut other) = (None, None, None);
459 let mut timestamp_scale = 1_000_000;526 let mut timestamp_scale = 1_000_000;
460 let mut at = segment.0;527 let mut at = segment.0;
461 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {528 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
@@ -475,8 +542,9 @@ fn mkv_tracks(
475 while let Some(e) = ebml_element(file, at, stop)? {542 while let Some(e) = ebml_element(file, at, stop)? {
476 if e.0 == TRACK_ENTRY {543 if e.0 == TRACK_ENTRY {
477 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {544 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
478- (Some(track), _) if video.is_none() => video = Some(track),545+ MkvEntry::Video(track) if video.is_none() => video = Some(track),
479- (_, Some(codec)) if audio.is_none() => audio = Some(codec),546+ MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
547+ MkvEntry::Audio(codec) if audio.is_none() => audio = Some(codec),
480 _ => {}548 _ => {}
481 }549 }
482 }550 }
@@ -487,17 +555,27 @@ fn mkv_tracks(
487 }555 }
488 at = stop;556 at = stop;
489 }557 }
490- Ok((video, audio))558+ Ok((video, audio, other))
559+}
560+
561+/// What one `TrackEntry` turned out to be.
562+enum MkvEntry {
563+ Video(MkvVideo),
564+ /// A video track in a codec this does not read, by the name it gives itself.
565+ OtherVideo(String),
566+ /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...).
567+ Audio(String),
568+ /// Subtitles, buttons: nobody's here.
569+ Other,
491 }570 }
492 571
493-/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id572+/// One `TrackEntry`, read for what it is.
494-/// of an audio track otherwise.
495 fn mkv_track_entry(573 fn mkv_track_entry(
496 file: &mut File,574 file: &mut File,
497 body: u64,575 body: u64,
498 end: u64,576 end: u64,
499 timestamp_scale: u64,577 timestamp_scale: u64,
500-) -> crate::Result<(Option<MkvVideo>, Option<String>)> {578+) -> crate::Result<MkvEntry> {
501 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);579 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
502 let (mut width, mut height, mut config) = (0, 0, Vec::new());580 let (mut width, mut height, mut config) = (0, 0, Vec::new());
503 let mut at = body;581 let mut at = body;
@@ -528,21 +606,30 @@ fn mkv_track_entry(
528 at = stop;606 at = stop;
529 }607 }
530 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.608 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
531- match (kind, codec.as_str()) {609+ // A Matroska `CodecPrivate` is the codec's own configuration record --
532- (1, "V_AV1") => Ok((610+ // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4
533- Some(MkvVideo {611+ // sample entry carries, so it parses with the very same reader.
534- number,612+ let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) {
535- width,613+ (1, "V_AV1") => (Codec::Av1, 4, parse_av1c(&config)?, 8),
536- height,614+ (1, "V_MPEGH/ISO/HEVC") => {
537- default_duration,615+ let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
538- timestamp_scale,616+ (Codec::Hevc, nal_length, sets, bit_depth)
539- config: parse_av1c(&config)?,617+ }
540- }),618+ (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
541- None,619+ (2, _) => return Ok(MkvEntry::Audio(codec)),
542- )),620+ _ => return Ok(MkvEntry::Other),
543- (2, _) => Ok((None, Some(codec))),621+ };
544- _ => Ok((None, None)),622+ Ok(MkvEntry::Video(MkvVideo {
545- }623+ number,
624+ width,
625+ height,
626+ default_duration,
627+ timestamp_scale,
628+ codec,
629+ config,
630+ nal_length,
631+ bit_depth,
632+ }))
546 }633 }
547 634
548 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF635 /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
@@ -898,21 +985,22 @@ pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4]
898 }985 }
899 986
900 /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length987 /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
901-/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob.988+/// prefix width, the VPS/SPS/PPS arrays as one Annex-B blob, and the luma bit
902-fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {989+/// depth the plugin picks its surface pool from.
990+fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>, u8)> {
903 // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.991 // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.
904 let (&flags, &arrays) = rec992 let (&flags, &arrays) = rec
905 .get(21)993 .get(21)
906 .zip(rec.get(22))994 .zip(rec.get(22))
907 .ok_or("hvcC box shorter than its fixed header")?;995 .ok_or("hvcC box shorter than its fixed header")?;
908- // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and996+ // 17 is bit_depth_luma_minus8 in its low 3 bits. 8-bit decodes into the
909- // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into997+ // plugin's NV12 pool and 10-bit (Main 10) into its P010 one; 12-bit has
910- // a surface nothing here can carry -- refused by name instead of shown as998+ // neither a pool here nor, on the hardware this was written against, a
911- // garbage. Upgrade path: a P010 pool chosen from the stream info.999+ // VA-API profile -- refused by name rather than shown as garbage.
912- if rec[17] & 0x7 != 0 {1000+ let bit_depth = 8 + (rec[17] & 0x7);
1001+ if bit_depth > 10 {
913 return Err(format!(1002 return Err(format!(
914- "10-bit HEVC (Main 10) is not supported yet — this file is {}-bit",1003+ "{bit_depth}-bit HEVC is not supported — 8- and 10-bit are what the decoder carries"
915- 8 + (rec[17] & 0x7)
916 )1004 )
917 .into());1005 .into());
918 }1006 }
@@ -947,7 +1035,7 @@ fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
947 if sets.is_empty() {1035 if sets.is_empty() {
948 return Err("hvcC box carries no VPS/SPS/PPS".into());1036 return Err("hvcC box carries no VPS/SPS/PPS".into());
949 }1037 }
950- Ok((usize::from(flags & 0x3) + 1, sets))1038+ Ok((usize::from(flags & 0x3) + 1, sets, bit_depth))
951 }1039 }
952 1040
953 /// Payload of the first top-level box of type `want`, or `None` if the file has1041 /// Payload of the first top-level box of type `want`, or `None` if the file has
@@ -1052,8 +1140,9 @@ mod tests {
1052 rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength1140 rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength
1053 rec.extend_from_slice(&[kind << 1, nal]);1141 rec.extend_from_slice(&[kind << 1, nal]);
1054 }1142 }
1055- let (len, sets) = parse_hvcc(&rec).unwrap();1143+ let (len, sets, depth) = parse_hvcc(&rec).unwrap();
1056 assert_eq!(len, 2);1144 assert_eq!(len, 2);
1145+ assert_eq!(depth, 8);
1057 assert_eq!(1146 assert_eq!(
1058 sets,1147 sets,
1059 [1148 [
@@ -1063,11 +1152,16 @@ mod tests {
1063 ]1152 ]
1064 );1153 );
1065 1154
1066- // 10-bit is refused by name rather than decoded into an 8-bit surface.1155+ // Main 10 is read, and read as 10-bit: that is what picks the P010
1156+ // surface pool over the NV12 one.
1067 let mut main10 = rec.clone();1157 let mut main10 = rec.clone();
1068 main10[17] = 0xf8 | 2;1158 main10[17] = 0xf8 | 2;
1069- let refused = parse_hvcc(&main10).unwrap_err().to_string();1159+ assert_eq!(parse_hvcc(&main10).unwrap().2, 10);
1070- assert!(refused.contains("10-bit"), "{refused}");1160+ // 12-bit has no pool and no profile here, and is refused by name.
1161+ let mut main12 = rec.clone();
1162+ main12[17] = 0xf8 | 4;
1163+ let refused = parse_hvcc(&main12).unwrap_err().to_string();
1164+ assert!(refused.contains("12-bit"), "{refused}");
1071 // Nothing is read past the end of a truncated box.1165 // Nothing is read past the end of a truncated box.
1072 assert!(parse_hvcc(&rec[..20]).is_err());1166 assert!(parse_hvcc(&rec[..20]).is_err());
1073 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());1167 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
crates/engine/src/export.rsmodified+24 -6
@@ -82,11 +82,13 @@ pub enum Format {
82 #[default]82 #[default]
83 Mp4,83 Mp4,
84 /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound84 /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound
85- /// this project can write: this engine's Matroska writer has no audio track85+ /// this project can *write*: this engine's Matroska writer has no audio
86- /// at all, and an AAC track written into one would be one *this engine's own86+ /// track at all, and the copy path walks an mp4 sample table, which a
87- /// reader* leaves silent87+ /// Matroska file has none of. (*Reading* one's AAC is a different question,
88- /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV188+ /// and since this engine gained a Matroska demuxer the answer is yes --
89- /// export is a WAV or FLAC beside it, which a front-end says up front.89+ /// `audio::Track::open` does it through symphonia's mkv reader.) The sound
90+ /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up
91+ /// front.
90 Av1,92 Av1,
91 /// The audio lane alone, 16-bit PCM.93 /// The audio lane alone, 16-bit PCM.
92 Wav,94 Wav,
@@ -345,6 +347,19 @@ fn copy_audio(
345 )347 )
346 .into());348 .into());
347 }349 }
350+ // A frame *rate* of its own is not one of those, and that is deliberate:
351+ // do not "fix" this into a re-encode. A clip counts the **timeline's**
352+ // frames whatever its file was shot at ([`Rate`]), so the window this copy
353+ // trims a source's sound to is `start..end` in whole timeline frames --
354+ // exactly the seconds the picture covers -- and the file is read at the
355+ // pitch it was recorded at, which is what playing at the rate it was shot at
356+ // means. There is no per-clip stretch to express, so the packets are already
357+ // the right sound in the right place; re-encoding a conformed lane would buy
358+ // nothing and cost a generation of loss on every mixed-rate export
359+ // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
360+ // measures the copied sound against the picture). A *speed* is different
361+ // because it resamples, which is why it is refused above.
362+ //
348 // ...and last, whether any clip on it carries an equalizer. An EQ is sample363 // ...and last, whether any clip on it carries an equalizer. An EQ is sample
349 // math and a copy never decodes, so copying such a lane would write the clip364 // math and a copy never decodes, so copying such a lane would write the clip
350 // *flat*, silently -- the failure a missing audio track is. This lane is365 // *flat*, silently -- the failure a missing audio track is. This lane is
@@ -660,7 +675,10 @@ fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
660 return Rate::REAL_TIME;675 return Rate::REAL_TIME;
661 }676 }
662 match Demuxer::open(path) {677 match Demuxer::open(path) {
663- Ok((meta, _)) => Rate::new(meta.frame_rate, timeline_fps),678+ // ...and one whose rate cannot be named against the timeline's, which
679+ // `matches_timeline` refuses at import, so nothing on a timeline is on
680+ // this arm either.
681+ Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
664 Err(_) => Rate::REAL_TIME,682 Err(_) => Rate::REAL_TIME,
665 }683 }
666 }684 }
crates/engine/src/playback.rsmodified+141 -38
@@ -466,10 +466,12 @@ impl PlaybackSession {
466 ///466 ///
467 /// A *new* session rather than a reload of this one, so a load that fails467 /// A *new* session rather than a reload of this one, so a load that fails
468 /// leaves the caller's current session untouched -- atomic by468 /// leaves the caller's current session untouched -- atomic by
469- /// construction. Every named file is opened and checked here: source 0469+ /// construction. Every named file is opened and checked here: the
470- /// defines the timeline exactly as `open` does, every other source has to470+ /// *scaffolding* source -- the first that is not a still, since a picture
471- /// match it the way [`import`](Self::import) demands, and every clip has to471+ /// carries no rate -- defines the timeline exactly as `open` does, every
472- /// still be inside the file it plays from. A source that vanished or472+ /// other source has to match it the way [`import`](Self::import) demands
473+ /// (a save renumbers, so which index that is says nothing), and every clip
474+ /// has to still be inside the file it plays from. A source that vanished or
473 /// shrank since the save is a refusal naming it, not a silently shorter475 /// shrank since the save is a refusal naming it, not a silently shorter
474 /// timeline -- the disappearing-file tolerance elsewhere in this type476 /// timeline -- the disappearing-file tolerance elsewhere in this type
475 /// applies only *after* a project has loaded.477 /// applies only *after* a project has loaded.
@@ -477,15 +479,35 @@ impl PlaybackSession {
477 /// The undo history is not saved: `undo` is `false` on a fresh load.479 /// The undo history is not saved: `undo` is `false` on a fresh load.
478 pub fn open_project(path: &Path) -> crate::Result<Self> {480 pub fn open_project(path: &Path) -> crate::Result<Self> {
479 let doc = crate::edith::load(path)?;481 let doc = crate::edith::load(path)?;
482+ // *Which* source scaffolds it: the first that is not a still, and index
483+ // 0 only when there is no other. A still defines no frame rate -- it is
484+ // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
485+ // footage off a PNG that a save happened to renumber to index 0
486+ // (`Project::without_orphan_sources` numbers by first use, and a
487+ // library removal moves indexes too) reads the timeline as 30 fps and
488+ // then refuses every file on it for not matching. The rule this and
489+ // [`audio_source_of`] share: nothing may assume what source 0 *is*.
490+ //
491+ // ponytail: a timeline of nothing but stills, or of stills and songs,
492+ // still comes back at the rate its scaffold implies rather than the one
493+ // it was cut at -- the rate is written nowhere in the file. The upgrade
494+ // path is a dialect that writes it (`crate::edith`), which is also what
495+ // a project naming no file at all would need.
496+ let scaffold = doc
497+ .sources
498+ .iter()
499+ .position(|s| !crate::is_image(&s.path))
500+ .unwrap_or(0);
480 // Owned: the sources move into the `Project` below, and the device is501 // Owned: the sources move into the `Project` below, and the device is
481 // opened after that (see the comment there).502 // opened after that (see the comment there).
482 let first = doc503 let first = doc
483 .sources504 .sources
484- .first()505+ .get(scaffold)
485 .cloned()506 .cloned()
486 .ok_or("the project names no sources")?;507 .ok_or("the project names no sources")?;
487- // Source 0 both scaffolds the session and defines the timeline, so it508+ // The scaffolding source both defines the timeline and is what the
488- // is opened for playback rather than merely probed.509+ // playhead's first picture comes from, so it is opened for playback
510+ // rather than merely probed.
489 // One value, not two locals: everything below this line can refuse, and511 // One value, not two locals: everything below this line can refuse, and
490 // locals drop in reverse declaration order -- a bare worker would join512 // locals drop in reverse declaration order -- a bare worker would join
491 // its decode thread while the receiver next to it was still holding513 // its decode thread while the receiver next to it was still holding
@@ -552,13 +574,22 @@ impl PlaybackSession {
552 }574 }
553 let first_audio = first_audio_of(&doc.sources)?;575 let first_audio = first_audio_of(&doc.sources)?;
554 576
555- let mut counts = vec![meta.frame_count];577+ // In source order, with the scaffold's own count in its own slot: the
556- // Source 0 defines the rate, so it is read frame for frame; every other578+ // clip check below indexes this list by source, so it must line up with
579+ // `doc.sources` whichever entry the scaffolding came from.
580+ let mut counts = Vec::with_capacity(doc.sources.len());
581+ // Beside it, one entry per source, grown at every `push` below: the
582+ // scaffold defines the rate, so it is read frame for frame; every other
557 // one is however long it is *in this timeline's frames*, which is the583 // one is however long it is *in this timeline's frames*, which is the
558 // length `import` noted for it and the wall the clip check below holds584 // length `import` noted for it and the wall the clip check below holds
559 // it to.585 // it to.
560- let mut rates = vec![Rate::REAL_TIME];586+ let mut rates = Vec::with_capacity(doc.sources.len());
561- for source in &doc.sources[1..] {587+ for (i, source) in doc.sources.iter().enumerate() {
588+ if i == scaffold {
589+ counts.push(meta.frame_count);
590+ rates.push(Rate::REAL_TIME);
591+ continue;
592+ }
562 // A still has neither a rate to match nor a track to match with:593 // A still has neither a rate to match nor a track to match with:
563 // its length is the one it is held to, recomputed exactly as the594 // its length is the one it is held to, recomputed exactly as the
564 // import that first noted it did ([`image_frames`]), which is what595 // import that first noted it did ([`image_frames`]), which is what
@@ -582,9 +613,8 @@ impl PlaybackSession {
582 }613 }
583 let (other, _) = Demuxer::open(&source.path)614 let (other, _) = Demuxer::open(&source.path)
584 .map_err(|e| format!("source {}: {e}", source.path.display()))?;615 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
585- matches_timeline(source, &other, &meta, &first_audio)616+ let rate = matches_timeline(source, &other, &meta, &first_audio)
586 .map_err(|e| format!("source {}: {e}", source.path.display()))?;617 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
587- let rate = Rate::new(other.frame_rate, meta.frame_rate);
588 counts.push(rate.timeline_at(other.frame_count));618 counts.push(rate.timeline_at(other.frame_count));
589 rates.push(rate);619 rates.push(rate);
590 }620 }
@@ -637,7 +667,15 @@ impl PlaybackSession {
637 // only a session's `drop` retires it, so a refusal above this line would667 // only a session's `drop` retires it, so a refusal above this line would
638 // leave a PipeWire stream and a thread behind for a project that never668 // leave a PipeWire stream and a thread behind for a project that never
639 // opened. Nothing before it needs the device.669 // opened. Nothing before it needs the device.
640- let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);670+ //
671+ // On the source the timeline's *sound* is defined by, which is the
672+ // scaffold unless that one is a still ([`audio_source_of`]): opening a
673+ // PNG as the device is a session with no audio at all, however many
674+ // clips with sound are on its lanes.
675+ let (audio, audio_disabled) = match audio_source_of(project.sources()) {
676+ Some(source) => open_audio(&source.path, source.audio_stream),
677+ None => (None, None),
678+ };
641 let mut session = Self {679 let mut session = Self {
642 meta,680 meta,
643 native,681 native,
@@ -687,7 +725,16 @@ impl PlaybackSession {
687 /// Writes the timeline to `path` as a `.edith`, atomically (see725 /// Writes the timeline to `path` as a `.edith`, atomically (see
688 /// [`crate::edith`]). Sources no clip plays from are left out, and the726 /// [`crate::edith`]). Sources no clip plays from are left out, and the
689 /// playhead is saved with it so a reopened project resumes where it stood.727 /// playhead is saved with it so a reopened project resumes where it stood.
728+ ///
729+ /// Refused, writing nothing, for a session whose library is empty (every
730+ /// row removed, [`Project::remove_source`]): a file naming no source has no
731+ /// timeline in it and [`open_project`](Self::open_project) could only
732+ /// refuse it, so the refusal belongs here, where nothing has been
733+ /// overwritten yet.
690 pub fn save_project(&self, path: &Path) -> crate::Result<()> {734 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
735+ if self.project.sources().is_empty() {
736+ return Err("this project names no file: there is nothing to save".into());
737+ }
691 let (sources, lanes, eq, color) = self.project.without_orphan_sources();738 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
692 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)739 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
693 .min(self.project.timeline_frames().saturating_sub(1));740 .min(self.project.timeline_frames().saturating_sub(1));
@@ -1148,13 +1195,20 @@ impl PlaybackSession {
1148 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session1195 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
1149 /// has never taken in.1196 /// has never taken in.
1150 fn file_rate(&self, path: &Path) -> Rate {1197 fn file_rate(&self, path: &Path) -> Rate {
1151- self.project1198+ self.source_of(path)
1152- .sources()
1153- .iter()
1154- .position(|s| s.path == path)
1155 .map_or(Rate::REAL_TIME, |i| self.rates[i])1199 .map_or(Rate::REAL_TIME, |i| self.rates[i])
1156 }1200 }
1157 1201
1202+ /// Which source `path` is, canonicalising only if it has to: a source's own
1203+ /// path is canonical ([`Source::new`]), so a caller handing one back from
1204+ /// [`sources`](Self::sources) -- which is every library row -- hits on the
1205+ /// first walk and never pays for the `canonicalize` syscall the second one
1206+ /// makes. One rule, so a path that names a length names a rate too.
1207+ fn source_of(&self, path: &Path) -> Option<usize> {
1208+ let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
1209+ at(path).or_else(|| at(&Source::new(path, 0).path))
1210+ }
1211+
1158 /// How long the whole of `path` is, in timeline frames: the length noted1212 /// How long the whole of `path` is, in timeline frames: the length noted
1159 /// when it became a source, so a file sitting in the library with no clip1213 /// when it became a source, so a file sitting in the library with no clip
1160 /// anywhere still knows how much of itself there is to place. `0` for a1214 /// anywhere still knows how much of itself there is to place. `0` for a
@@ -1164,14 +1218,7 @@ impl PlaybackSession {
1164 /// audio tracks it carries -- the picture's frame count for an mp4, the1218 /// audio tracks it carries -- the picture's frame count for an mp4, the
1165 /// playing time for a song.1219 /// playing time for a song.
1166 pub fn file_frames(&self, path: &Path) -> u32 {1220 pub fn file_frames(&self, path: &Path) -> u32 {
1167- let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);1221+ self.source_of(path).map_or(0, |i| self.counts[i])
1168- // A source's own path is canonical ([`Source::new`]), so a caller
1169- // handing one back from [`sources`](Self::sources) -- which is every
1170- // library row -- hits on the first walk and never pays for the
1171- // `canonicalize` syscall the second one makes.
1172- at(path)
1173- .or_else(|| at(&Source::new(path, 0).path))
1174- .map_or(0, |i| self.counts[i])
1175 }1222 }
1176 1223
1177 /// What rate the file at `path` was *shot* at, in frames per second -- which1224 /// What rate the file at `path` was *shot* at, in frames per second -- which
@@ -1404,7 +1451,14 @@ impl PlaybackSession {
1404 /// Reseeks like an edit even though nothing playable changed: the clip1451 /// Reseeks like an edit even though nothing playable changed: the clip
1405 /// indexes into the source list have just moved, and the running workers1452 /// indexes into the source list have just moved, and the running workers
1406 /// were opened against the old numbering.1453 /// were opened against the old numbering.
1407- pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> {1454+ ///
1455+ /// The index that went, because everything past it moved down: a caller
1456+ /// holding a source index of its own (a clipboard) has to fix it up or drop
1457+ /// it, or it names a different file afterwards. The **last** row goes like
1458+ /// any other and leaves a session with an empty library -- silent, empty of
1459+ /// clips, and unsaveable ([`save_project`](Self::save_project)); a
1460+ /// front-end showing one is showing an empty window.
1461+ pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
1408 let wanted = Source::new(path, stream);1462 let wanted = Source::new(path, stream);
1409 let idx = self1463 let idx = self
1410 .project1464 .project
@@ -1424,11 +1478,12 @@ impl PlaybackSession {
1424 }1478 }
1425 let now = self.now();1479 let now = self.now();
1426 self.seek(now);1480 self.seek(now);
1427- Ok(())1481+ Ok(idx)
1428 }1482 }
1429 1483
1430- /// What the timeline's audio *is*: source 0's chosen stream, probed. Every1484+ /// What the timeline's audio *is*: the chosen stream of the first source
1431- /// other source is held to it.1485+ /// that could have any ([`audio_source_of`]), probed. Every other source is
1486+ /// held to it.
1432 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {1487 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
1433 first_audio_of(self.project.sources())1488 first_audio_of(self.project.sources())
1434 }1489 }
@@ -1494,12 +1549,14 @@ impl PlaybackSession {
1494 // Stream 0: an import brings a file in on its first audio track, and1549 // Stream 0: an import brings a file in on its first audio track, and
1495 // [`place_stream_at`](Self::place_stream_at) is how any other one of1550 // [`place_stream_at`](Self::place_stream_at) is how any other one of
1496 // its streams reaches the timeline afterwards.1551 // its streams reaches the timeline afterwards.
1497- matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;1552+ // ...and the rate it will be read at comes back from the check that
1553+ // accepted it, so the number the refusal was decided on is the number
1554+ // the file is played by.
1555+ let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
1498 let source = self.project.import(path, 0);1556 let source = self.project.import(path, 0);
1499 // Its length *on this timeline*: a file shot slower than the timeline1557 // Its length *on this timeline*: a file shot slower than the timeline
1500 // runs covers more frames than it holds, which is the whole of what1558 // runs covers more frames than it holds, which is the whole of what
1501 // placing it at another rate means ([`Rate`]).1559 // placing it at another rate means ([`Rate`]).
1502- let rate = Rate::new(meta.frame_rate, self.meta.frame_rate);
1503 self.note_frames(source, rate.timeline_at(meta.frame_count), rate);1560 self.note_frames(source, rate.timeline_at(meta.frame_count), rate);
1504 Ok(source)1561 Ok(source)
1505 }1562 }
@@ -1806,7 +1863,9 @@ impl Drop for PlaybackSession {
1806 1863
1807 /// Whether `path`, already demuxed to `meta`, may join a timeline whose1864 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
1808 /// parameters are `timeline` and whose audio probes as `first`: same codec,1865 /// parameters are `timeline` and whose audio probes as `first`: same codec,
1809-/// same frame rate, same audio parameters or both silent.1866+/// same audio parameters or both silent, and a frame rate that can be named
1867+/// against the timeline's. The [`Rate`] it will be read at comes back with the
1868+/// answer, so the number the check was decided on is the number it plays by.
1810 ///1869 ///
1811 /// *Not* the same size any more. A project has its own resolution1870 /// *Not* the same size any more. A project has its own resolution
1812 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its1871 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
@@ -1824,7 +1883,7 @@ fn matches_timeline(
1824 meta: &VideoMeta,1883 meta: &VideoMeta,
1825 timeline: &VideoMeta,1884 timeline: &VideoMeta,
1826 first: &Option<crate::AudioProbe>,1885 first: &Option<crate::AudioProbe>,
1827-) -> crate::Result<()> {1886+) -> crate::Result<Rate> {
1828 // Codec first: one timeline is one kind of source. Mixing them would decode1887 // Codec first: one timeline is one kind of source. Mixing them would decode
1829 // (every clip opens its own decoder) but on a machine without the VA-API1888 // (every clip opens its own decoder) but on a machine without the VA-API
1830 // plugin the VP9 half would be black frames with the refusal only on1889 // plugin the VP9 half would be black frames with the refusal only on
@@ -1837,11 +1896,20 @@ fn matches_timeline(
1837 )1896 )
1838 .into());1897 .into());
1839 }1898 }
1840- // The frame rate is *not* one of these: a file shot at another rate is1899+ // The frame rate is *not* a refusal any more: a file shot at another rate is
1841 // placed for the seconds it lasts and read through [`Rate`] at the1900 // placed for the seconds it lasts and read through [`Rate`] at the
1842 // decoder's door, so it plays at the speed it was shot at on a timeline1901 // decoder's door, so it plays at the speed it was shot at on a timeline
1843 // that counts frames faster or slower.1902 // that counts frames faster or slower.
1844- audio_matches(source, first)1903+ //
1904+ // A rate that cannot be *named* still is, and this is the one place it is
1905+ // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
1906+ // and a file whose rate has none of those (a container that says nothing and
1907+ // holds one block, so the demuxer measures 0 fps) would otherwise be read
1908+ // 1:1 in silence -- the old rate gate refused those too, by arithmetic
1909+ // accident. The `Err` is `mux::frame_timing`'s own words.
1910+ let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
1911+ audio_matches(source, first)?;
1912+ Ok(rate)
1845 }1913 }
1846 1914
1847 /// Whether a candidate's audio may join a timeline whose first source probes as1915 /// Whether a candidate's audio may join a timeline whose first source probes as
@@ -1868,12 +1936,26 @@ fn matches_timeline(
1868 /// source 0 has always given. This function widens which source is asked, not1936 /// source 0 has always given. This function widens which source is asked, not
1869 /// what the answer means.1937 /// what the answer means.
1870 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {1938 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
1871- match sources.iter().find(|s| !crate::is_image(&s.path)) {1939+ match audio_source_of(sources) {
1872 Some(first) => AudioSession::probe(&first.path, first.audio_stream),1940 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
1873 None => Ok(None),1941 None => Ok(None),
1874 }1942 }
1875 }1943 }
1876 1944
1945+/// *Which* source that is: the first one that is not a still. The single answer
1946+/// to "what does this timeline's sound come from", so that probing it
1947+/// ([`first_audio_of`]) and opening the device on it
1948+/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
1949+/// the scaffolding file until a save renumbers it or a library removal takes it
1950+/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
1951+/// device is a timeline that plays silent although every clip on it has sound.
1952+///
1953+/// `None` for a library of nothing but stills, and for one with no file at all:
1954+/// both are silent timelines.
1955+fn audio_source_of(sources: &[Source]) -> Option<&Source> {
1956+ sources.iter().find(|s| !crate::is_image(&s.path))
1957+}
1958+
1877 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {1959 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
1878 // Whole-probe equality: rate and layout, which the audio worker holds every1960 // Whole-probe equality: rate and layout, which the audio worker holds every
1879 // source to anyway. Both silent is a match.1961 // source to anyway. Both silent is a match.
@@ -2026,7 +2108,7 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 {
2026 2108
2027 #[cfg(test)]2109 #[cfg(test)]
2028 mod tests {2110 mod tests {
2029- use super::{Edge, Lane, PlaybackSession, secs_to_frame};2111+ use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame};
2030 use std::path::PathBuf;2112 use std::path::PathBuf;
2031 2113
2032 fn asset(name: &str) -> PathBuf {2114 fn asset(name: &str) -> PathBuf {
@@ -2035,6 +2117,27 @@ mod tests {
2035 .join(name)2117 .join(name)
2036 }2118 }
2037 2119
2120+ /// Which source the timeline's sound is opened on -- the one rule
2121+ /// [`open_project`](PlaybackSession::open_project), the probe every import
2122+ /// is held to and the audio worker all read through. A still at index 0 is
2123+ /// a picture, not a silent timeline: opening the device on it is a project
2124+ /// that plays silent although every clip on it has sound.
2125+ #[test]
2126+ fn the_audio_reference_is_never_a_still() {
2127+ let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
2128+ let sources = [Source::new(&still, 0), Source::new(&video, 3)];
2129+ assert_eq!(
2130+ audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
2131+ Some((&sources[1].path, 3)),
2132+ "the first source that could have a track, with its own stream"
2133+ );
2134+ assert!(
2135+ audio_source_of(&sources[..1]).is_none(),
2136+ "nothing but stills"
2137+ );
2138+ assert!(audio_source_of(&[]).is_none(), "and no file at all");
2139+ }
2140+
2038 /// The seam between the two lists a source index reaches: dropping a file2141 /// The seam between the two lists a source index reaches: dropping a file
2039 /// from the library shortens `sources`, and `counts` -- the frame length2142 /// from the library shortens `sources`, and `counts` -- the frame length
2040 /// per source, which is what a trim is walled by -- has to lose the same2143 /// per source, which is what a trim is walled by -- has to lose the same
crates/engine/src/project.rsmodified+116 -66
@@ -221,9 +221,8 @@ impl std::fmt::Display for Speed {
221 }221 }
222 }222 }
223 223
224-/// What a file's own frame rate is against the timeline's, as an exact rational224+/// What a file's own frame rate is against the timeline's, as an exact
225-/// in thousandths of a frame per second: how many frames of the *file* one frame225+/// rational: how many frames of the *file* one frame of the timeline is worth.
226-/// of the timeline is worth.
227 ///226 ///
228 /// Every frame number in this module counts **timeline** frames -- a clip's227 /// Every frame number in this module counts **timeline** frames -- a clip's
229 /// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps228 /// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
@@ -238,18 +237,18 @@ impl std::fmt::Display for Speed {
238 /// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps237 /// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
239 /// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).238 /// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
240 ///239 ///
241-/// ponytail: the rate is rounded to milli-fps, so 24000/1001 is carried as240+/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
242-/// 23.976 -- about a frame per 40000, or a frame off after seven hours of one241+/// stays `800/1001` however far the timeline runs, where a rate rounded to
243-/// clip. Upgrade path is carrying the container's own timescale rational in242+/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
244-/// [`crate::VideoMeta`] and building this from it.243+/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
245 ///244 ///
246 /// [`PlaybackSession`]: crate::PlaybackSession245 /// [`PlaybackSession`]: crate::PlaybackSession
247 #[derive(Clone, Copy, PartialEq, Eq, Debug)]246 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
248 pub struct Rate {247 pub struct Rate {
249- /// Milli-fps of the file...248+ /// Frames of the file...
250- source: u64,249+ source: u32,
251- /// ...and of the timeline it plays on.250+ /// ...per this many frames of the timeline it plays on. Never zero.
252- timeline: u64,251+ timeline: u32,
253 }252 }
254 253
255 impl Rate {254 impl Rate {
@@ -260,22 +259,36 @@ impl Rate {
260 timeline: 1,259 timeline: 1,
261 };260 };
262 261
263- /// The rate of a file at `source_fps` on a timeline at `timeline_fps`.262+ /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
264- /// Rounded to milli-fps, and [`REAL_TIME`](Self::REAL_TIME) for the rates263+ /// exactly.
265- /// that agree there -- container rates are computed from timescales, so264+ ///
266- /// "the same rate" is never `==` either.265+ /// Both rates come out of a container as a division, so neither is ever the
267- pub fn new(source_fps: f64, timeline_fps: f64) -> Self {266+ /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
268- let milli = |fps: f64| match fps.is_finite() && fps > 0. {267+ /// already knows how to name one exactly -- it is the same pair the muxer
269- true => (fps * 1000.).round().clamp(1., 1e9) as u64,268+ /// counts an export's frames in -- and this is that pair divided by that
270- // Not a rate at all: read the file frame for frame rather than269+ /// pair, reduced. A rate no timescale can name is an `Err` in that
271- // dividing the timeline by a zero.270+ /// function's own words rather than a silent 1:1 -- `matches_timeline` is
272- false => 0,271+ /// where a file carrying one is refused by name, beside the codec.
273- };272+ ///
274- match (milli(source_fps), milli(timeline_fps)) {273+ /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
275- (0, _) | (_, 0) => Self::REAL_TIME,274+ /// timeline that had ever opened in this editor before mixed rates.
276- (source, timeline) if source == timeline => Self::REAL_TIME,275+ pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
277- (source, timeline) => Self { source, timeline },276+ let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
277+ let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
278+ // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
279+ let num = u64::from(src_scale) * u64::from(tl_ticks);
280+ let den = u64::from(src_ticks) * u64::from(tl_scale);
281+ let g = gcd(num, den);
282+ let (mut num, mut den) = (num / g, den / g);
283+ // A ratio no pair of real frame rates produces, but the fields are `u32`
284+ // so that every multiplication below fits a `u64` at any frame count.
285+ while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
286+ (num, den) = (num.div_ceil(2), den.div_ceil(2));
278 }287 }
288+ Ok(Self {
289+ source: num.max(1) as u32,
290+ timeline: den.max(1) as u32,
291+ })
279 }292 }
280 293
281 pub fn is_real_time(self) -> bool {294 pub fn is_real_time(self) -> bool {
@@ -285,13 +298,14 @@ impl Rate {
285 /// As a multiplier of the timeline's rate: what a *file's* own frame rate298 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
286 /// is, given the timeline's, for a library row that names it.299 /// is, given the timeline's, for a library row that names it.
287 pub fn as_f64(self) -> f64 {300 pub fn as_f64(self) -> f64 {
288- self.source as f64 / self.timeline as f64301+ f64::from(self.source) / f64::from(self.timeline)
289 }302 }
290 303
291 /// Which frame of the file the `frame`th timeline-rate frame of it is:304 /// Which frame of the file the `frame`th timeline-rate frame of it is:
292 /// floored, [`Speed::source_at`]'s half of the pair.305 /// floored, [`Speed::source_at`]'s half of the pair.
293 pub fn source_at(self, frame: u32) -> u32 {306 pub fn source_at(self, frame: u32) -> u32 {
294- (u64::from(frame) * self.source / self.timeline).min(u64::from(u32::MAX)) as u32307+ (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
308+ .min(u64::from(u32::MAX)) as u32
295 }309 }
296 310
297 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first311 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
@@ -299,12 +313,21 @@ impl Rate {
299 /// the stamp playback puts on a decoded picture, and, applied to a file's313 /// the stamp playback puts on a decoded picture, and, applied to a file's
300 /// frame *count*, how long that file is in timeline frames.314 /// frame *count*, how long that file is in timeline frames.
301 pub fn timeline_at(self, source_frame: u32) -> u32 {315 pub fn timeline_at(self, source_frame: u32) -> u32 {
302- (u64::from(source_frame) * self.timeline)316+ (u64::from(source_frame) * u64::from(self.timeline))
303- .div_ceil(self.source)317+ .div_ceil(u64::from(self.source))
304 .min(u64::from(u32::MAX)) as u32318 .min(u64::from(u32::MAX)) as u32
305 }319 }
306 }320 }
307 321
322+/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
323+/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
324+fn gcd(a: u64, b: u64) -> u64 {
325+ match b {
326+ 0 => a.max(1),
327+ b => gcd(b, a % b),
328+ }
329+}
330+
308 /// A half-open `[in_frame, out_frame)` range of frames of source331 /// A half-open `[in_frame, out_frame)` range of frames of source
309 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).332 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
310 /// Never empty.333 /// Never empty.
@@ -897,10 +920,20 @@ impl Project {
897 ///920 ///
898 /// Refused, changing nothing, while any clip still plays from it: the921 /// Refused, changing nothing, while any clip still plays from it: the
899 /// refusal names the lanes and how many clips each holds, so a caller can922 /// refusal names the lanes and how many clips each holds, so a caller can
900- /// say what has to be deleted first. Refused too for the last entry left,923+ /// say what has to be deleted first. The *last* entry goes like any other
901- /// because a project that names no file cannot be reopened924+ /// -- a project may name no file at all, which is an empty library over an
902- /// (`PlaybackSession::open_project`) and the timeline's audio parameters925+ /// empty timeline (nothing can play, since a clip would have refused the
903- /// are read off source 0.926+ /// removal). What a front-end does with that is its own decision: `edith`'s
927+ /// window goes back to the empty state it launches in, and
928+ /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
929+ /// refuses to write a project that names nothing, because no such file
930+ /// could be opened again.
931+ ///
932+ /// Every index past `idx` moves down by one, so a caller holding a *raw*
933+ /// source index of its own -- a clipboard, which is the one thing outside
934+ /// this type that does -- has to fix it up or drop it, or a paste plays a
935+ /// different file. [`PlaybackSession::remove_source`] hands back the index
936+ /// that went for exactly that.
904 ///937 ///
905 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a938 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
906 /// snapshot older than the removal can name the very source being removed939 /// snapshot older than the removal can name the very source being removed
@@ -915,12 +948,6 @@ impl Project {
915 return Err(format!("there is no source {idx} to remove").into());948 return Err(format!("there is no source {idx} to remove").into());
916 };949 };
917 let name = source.path.display().to_string();950 let name = source.path.display().to_string();
918- // Asked before the clips are counted: with one file left the answer is
919- // the same whatever plays, and "the only file" is the more useful half
920- // of it.
921- if self.sources.len() == 1 {
922- return Err(format!("{name} is the only file this project names").into());
923- }
924 let used: Vec<String> = handles(&self.lanes)951 let used: Vec<String> = handles(&self.lanes)
925 .into_iter()952 .into_iter()
926 .zip(&self.lanes)953 .zip(&self.lanes)
@@ -964,9 +991,16 @@ impl Project {
964 /// only the ones a clip names.991 /// only the ones a clip names.
965 ///992 ///
966 /// One exception, and it is the emptied timeline's: a project no clip plays993 /// One exception, and it is the emptied timeline's: a project no clip plays
967- /// from still keeps source 0. It is the file a session is scaffolded from --994+ /// from still keeps its first source, if it has one. A file is what a
968- /// its frame rate is the timeline's and is written nowhere else -- so a save995+ /// reopened project scaffolds itself from -- the frame rate is written
969- /// that pruned it would write a project that cannot be loaded back at all.996+ /// nowhere else -- so a save that pruned the last of them would write a
997+ /// project that cannot be loaded back at all.
998+ ///
999+ /// What comes out is *not* ordered by anything a reader may assume: first
1000+ /// use, lane by lane, means the entry at index 0 can be a still or a song
1001+ /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1002+ /// picks its rate and its audio reference by what a source *is*, never by
1003+ /// where it sits.
970 pub fn without_orphan_sources(&self) -> Parts {1004 pub fn without_orphan_sources(&self) -> Parts {
971 let mut moved = vec![None; self.sources.len()];1005 let mut moved = vec![None; self.sources.len()];
972 let mut sources = Vec::new();1006 let mut sources = Vec::new();
@@ -4019,10 +4053,10 @@ mod tests {
4019 }4053 }
4020 4054
4021 /// The two edges of a removal: it retires the undo stack (the ponytail on4055 /// The two edges of a removal: it retires the undo stack (the ponytail on
4022- /// [`Project::remove_source`]), and the last entry standing cannot go --4056+ /// [`Project::remove_source`]), and the last entry goes like any other
4023- /// source 0 is where a reopened project reads its frame rate.4057+ /// once nothing plays it -- a project may name no file at all.
4024 #[test]4058 #[test]
4025- fn remove_source_retires_undo_and_keeps_the_last_file() {4059+ fn remove_source_retires_undo_and_empties_the_library() {
4026 let mut p = two_sources();4060 let mut p = two_sources();
4027 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");4061 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
4028 assert!(!p.history.is_empty(), "there is something to undo");4062 assert!(!p.history.is_empty(), "there is something to undo");
@@ -4033,18 +4067,25 @@ mod tests {
4033 );4067 );
4034 assert!(!p.undo(), "and so there is nothing left to undo");4068 assert!(!p.undo(), "and so there is nothing left to undo");
4035 4069
4036- // The last file standing stays, whatever plays from it:4070+ // The last file standing is held to the one rule every row is -- what
4037- // `PlaybackSession::open_project` refuses a project that names no4071+ // plays cannot go -- and to no other.
4038- // sources at all, and the timeline's frame rate lives in source 0.
4039 assert_eq!(p.sources().len(), 1);4072 assert_eq!(p.sources().len(), 1);
4040 let refusal = p4073 let refusal = p
4041 .remove_source(0)4074 .remove_source(0)
4042- .expect_err("the only source must stay")4075+ .expect_err("its clips are still on the lanes")
4043 .to_string();4076 .to_string();
4044- assert!(refusal.contains("only file"), "{refusal}");4077+ assert!(refusal.contains("still plays"), "{refusal}");
4045- assert_eq!(p.sources().len(), 1);4078+ assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
4079+ while p.delete_in(Lane::V1, 0) {}
4080+ p.remove_source(0)
4081+ .expect("the last row goes like any other");
4046 assert!(4082 assert!(
4047- p.remove_source(1).is_err(),4083+ p.sources().is_empty(),
4084+ "a project may name no file at all: an empty library over an empty timeline"
4085+ );
4086+ assert_eq!(p.timeline_frames(), 0);
4087+ assert!(
4088+ p.remove_source(0).is_err(),
4048 "and an index that is not there is refused, not panicked on"4089 "and an index that is not there is refused, not panicked on"
4049 );4090 );
4050 }4091 }
@@ -4643,7 +4684,7 @@ mod tests {
4643 (25., 30.),4684 (25., 30.),
4644 (30., 30.),4685 (30., 30.),
4645 ] {4686 ] {
4646- let rate = Rate::new(source_fps, timeline_fps);4687+ let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
4647 for n in 0..2000u32 {4688 for n in 0..2000u32 {
4648 let source = rate.source_at(n);4689 let source = rate.source_at(n);
4649 // The stamp is the *first* timeline-rate frame that shows it, so4690 // The stamp is the *first* timeline-rate frame that shows it, so
@@ -4663,13 +4704,12 @@ mod tests {
4663 "{source_fps} on {timeline_fps}: {count} frames reads past the file"4704 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
4664 );4705 );
4665 }4706 }
4666- // No drift: the mapping is one exact division, not an accumulation,4707+ // No drift: the mapping is one exact division of the *rate itself*,
4667- // so an hour in is as true as the first second. (`Rate` rounds the4708+ // not an accumulation and not a rounded rate, so an hour in is as
4668- // rate itself to milli-fps -- 23.976 for 24000/1001 -- which is the4709+ // true as the first second. (Held to the real ratio of the two rates
4669- // 3e-8 the tolerance below allows for.)4710+ // the caller asked for -- `as_f64` would be true of a wrong rate.)
4670- let milli = |fps: f64| (fps * 1000.).round();
4671 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {4711 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
4672- let want = f64::from(n) * milli(source_fps) / milli(timeline_fps);4712+ let want = f64::from(n) * source_fps / timeline_fps;
4673 assert!(4713 assert!(
4674 (f64::from(rate.source_at(n)) - want).abs() < 1.,4714 (f64::from(rate.source_at(n)) - want).abs() < 1.,
4675 "{source_fps} on {timeline_fps}: frame {n} drifted"4715 "{source_fps} on {timeline_fps}: frame {n} drifted"
@@ -4677,9 +4717,18 @@ mod tests {
4677 }4717 }
4678 }4718 }
4679 // The timeline's own rate is the identity, whichever way it is written.4719 // The timeline's own rate is the identity, whichever way it is written.
4680- assert!(Rate::new(30., 30.).is_real_time());4720+ assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
4681- assert!(Rate::new(30.0004, 30.).is_real_time(), "milli-fps rounding");4721+ assert!(
4682- assert!(Rate::new(0., 30.).is_real_time(), "not a rate at all");4722+ Rate::from_fps(30.0004, 30.)
4723+ .expect("30.0004 over 30")
4724+ .is_real_time(),
4725+ "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
4726+ );
4727+ // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
4728+ // one thing `matches_timeline` refuses a file for now that the rate gate
4729+ // is gone.
4730+ assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
4731+ assert!(Rate::from_fps(30., f64::NAN).is_err());
4683 for n in 0..1000 {4732 for n in 0..1000 {
4684 assert_eq!(Rate::REAL_TIME.source_at(n), n);4733 assert_eq!(Rate::REAL_TIME.source_at(n), n);
4685 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);4734 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
@@ -4687,13 +4736,14 @@ mod tests {
4687 // ...and the composition, in the order the decoder's door applies it:4736 // ...and the composition, in the order the decoder's door applies it:
4688 // the speed picks the clip's (timeline-rate) frame, the rate picks the4737 // the speed picks the clip's (timeline-rate) frame, the rate picks the
4689 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two4738 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
4690- // timeline frames per frame shown, each of them 0.799 of a file frame.4739+ // timeline frames per frame shown, each of them exactly 800/1001 of a
4691- let rate = Rate::new(24000. / 1001., 30.);4740+ // file frame.
4741+ let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
4692 let speed = Speed::from_permille(2000);4742 let speed = Speed::from_permille(2000);
4693 for d in 0..100u32 {4743 for d in 0..100u32 {
4694 assert_eq!(4744 assert_eq!(
4695 rate.source_at(speed.source_at(d)),4745 rate.source_at(speed.source_at(d)),
4696- (u64::from(d) * 2 * 23976 / 30000) as u32,4746+ (u64::from(d) * 2 * 800 / 1001) as u32,
4697 "2x of a 23.976 fps file at timeline frame {d}"4747 "2x of a 23.976 fps file at timeline frame {d}"
4698 );4748 );
4699 }4749 }
crates/engine/tests/av1.rsmodified+30 -30
@@ -57,28 +57,19 @@ fn the_demuxer_reports_an_av1_track_in_matroska() {
57 assert_eq!(vp9.codec, Codec::Vp9);57 assert_eq!(vp9.codec, Codec::Vp9);
58 }58 }
59 59
60-/// The delivered audio scope, as an assert: this slice reads a Matroska file's60+/// The delivered audio scope, as an assert: a Matroska file's AAC track is read
61-/// picture and not its sound, so the fixture's AAC track is *named* in the61+/// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its
62-/// notice a session shows rather than half-played or reported as an mp4 error.62+/// *picture* being AV1 changes nothing about it.
63 #[test]63 #[test]
64-fn matroska_audio_is_not_wired_and_says_so() {64+fn matroska_audio_is_read_whatever_the_picture_is() {
65 let path = asset("test_av1.mkv");65 let path = asset("test_av1.mkv");
66- assert!(66+ let probe = AudioSession::probe(&path, 0)
67- AudioSession::probe(&path, 0)67+ .expect("probe must not fail")
68- .expect("probe must not fail")68+ .expect("the fixture has an AAC track");
69- .is_none(),69+ assert_eq!((probe.sample_rate, probe.channels), (44_100, 2));
70- "an mkv is a silent source for now, not an error"70+ let streams = AudioSession::probe_streams(&path).expect("streams");
71- );71+ assert_eq!(streams.len(), 1, "one readable audio stream: {streams:?}");
72- assert!(72+ assert!(streams[0].decodable);
73- AudioSession::probe_streams(&path)
74- .expect("streams")
75- .is_empty()
76- );
77- let reason = AudioSession::unsupported(&path)
78- .expect("unsupported")
79- .expect("the fixture has an AAC track to name");
80- assert!(reason.contains("A_AAC"), "{reason}");
81- assert!(reason.contains("not wired"), "{reason}");
82 }73 }
83 74
84 /// Every block comes back, keyframes carry the sequence header, and the sync75 /// Every block comes back, keyframes carry the sequence header, and the sync
@@ -204,11 +195,18 @@ fn a_seek_lands_on_the_frame_it_asked_for() {
204 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");195 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");
205 }196 }
206 197
207-/// Export re-encodes to H.264 whatever the source was coded with -- and out of198+/// An mp4 export of a Matroska source is refused by name, and says where the
208-/// a Matroska source it also has to write an mp4 the demuxer reads back.199+/// sound can go instead.
200+///
201+/// It used to *succeed*, silently, and only because this engine could not read
202+/// a Matroska file's audio at all: the export wrote picture with no sound in it
203+/// and nobody was told. Now that the sound is read (`tests/hevc_mkv.rs`), the
204+/// rule the whole mp4 path is built on applies to it like to any other source
205+/// it cannot copy -- an AC-3 mp4 has always been refused in the same breath.
206+/// The picture half of the same export is [`an_av1_export_reopens_through_our_own_demuxer`].
209 #[test]207 #[test]
210 #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]208 #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
211-fn an_av1_source_exports_as_h264() {209+fn an_mp4_export_of_a_matroska_source_is_refused_by_name() {
212 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");210 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
213 let meta = *session.meta();211 let meta = *session.meta();
214 let project = Project::single(asset("test_av1.mkv"), meta.frame_count);212 let project = Project::single(asset("test_av1.mkv"), meta.frame_count);
@@ -221,13 +219,15 @@ fn an_av1_source_exports_as_h264() {
221 assert!(started.elapsed() < Duration::from_secs(120), "export hung");219 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
222 std::thread::sleep(Duration::from_millis(20));220 std::thread::sleep(Duration::from_millis(20));
223 }221 }
224- handle.result().expect("outcome").expect("export");222+ let refused = handle
225-223+ .result()
226- let (written, _) = Demuxer::open(&out).expect("reopen the export");224+ .expect("outcome")
227- assert_eq!(written.codec, Codec::H264, "the default format is H.264");225+ .expect_err("an mkv's AAC cannot be copied into an mp4")
228- assert_eq!(written.frame_count, FRAMES, "every timeline frame written");226+ .to_string();
229- assert_eq!((written.width, written.height), (1280, 720));227+ assert!(refused.contains("test_av1.mkv"), "{refused}");
230- let _ = std::fs::remove_file(&out);228+ assert!(refused.contains("Matroska"), "{refused}");
229+ assert!(refused.contains("WAV or FLAC"), "{refused}");
230+ assert!(!out.exists(), "a refused export leaves no file behind");
231 }231 }
232 232
233 /// A short timeline out of the H.264 fixture, which is what the AV1 export tests233 /// A short timeline out of the H.264 fixture, which is what the AV1 export tests
crates/engine/tests/hevc_mkv.rsadded+245 -0
@@ -0,0 +1,245 @@
1+//! HEVC in Matroska, 8- and 10-bit, sound included: the shape a film off a disc
2+//! arrives in, and the one the AV1 walk was written for one codec too early.
3+//!
4+//! Three things meet here and each is checked on its own: the demuxer reads an
5+//! `hvcC` out of a `CodecPrivate` and reframes Matroska blocks to Annex-B, the
6+//! plugin decodes Main 10 through a P010 surface pool, and the sound -- 5.1 AAC
7+//! at 48 kHz -- is read by symphonia's mkv reader, decoded by `rusty_aac` and
8+//! folded to the stereo one output device carries.
9+//!
10+//! The container and audio checks need nothing installed. The decode twins need
11+//! a built `libengine_hw.so` and a VA-API driver with an HEVC decode entrypoint
12+//! (`vainfo | grep HEVC`), so they are `#[ignore]`d:
13+//!
14+//! ```text
15+//! cargo build -p engine -p engine-hw --release
16+//! LD_LIBRARY_PATH=target/release \
17+//! cargo test -p engine --release --test hevc_mkv -- --include-ignored --nocapture
18+//! ```
19+
20+use std::path::PathBuf;
21+
22+use engine::demux::{Codec, Demuxer};
23+use engine::hw::HwSession;
24+use engine::{AudioSession, DecodeSession};
25+
26+/// 1280x720@30, 2 s, keyed twice -- see `scripts/gen_fixtures.sh`.
27+const FRAMES: u32 = 60;
28+
29+fn asset(name: &str) -> PathBuf {
30+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31+ .join("../../assets")
32+ .join(name)
33+}
34+
35+/// The container half: an HEVC track in an mkv is found, named, measured, and
36+/// its blocks come back as Annex-B access units with the parameter sets in
37+/// front of every keyframe. Matroska indexes nothing, so all four numbers come
38+/// out of the walk.
39+#[test]
40+fn the_demuxer_reads_hevc_out_of_a_matroska_file() {
41+ for (name, depth) in [("test_hevc.mkv", 8), ("test_hevc10.mkv", 10)] {
42+ let (meta, mut demuxer) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
43+ assert_eq!(meta.codec, Codec::Hevc, "{name}");
44+ assert_eq!((meta.width, meta.height), (1280, 720), "{name}");
45+ assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{name}: {}", meta.frame_rate);
46+ assert_eq!(meta.frame_count, FRAMES, "{name}");
47+ // What picks the P010 surface pool over the NV12 one.
48+ assert_eq!(demuxer.bit_depth(), depth, "{name}");
49+
50+ let first = demuxer
51+ .next_access_unit()
52+ .expect("read")
53+ .expect("a first access unit");
54+ // A Matroska block is length-prefixed NALs, exactly as an mp4 sample is,
55+ // and what a decoder has to be handed is Annex-B with the VPS (NAL type
56+ // 32) out of the `CodecPrivate` in front.
57+ assert_eq!(&first[..4], [0, 0, 0, 1], "{name}: Annex-B start code");
58+ assert_eq!(
59+ (first[4] >> 1) & 0x3f,
60+ 32,
61+ "{name}: the keyframe leads with the VPS off the CodecPrivate"
62+ );
63+ let mut count = 1;
64+ while demuxer.next_access_unit().expect("read").is_some() {
65+ count += 1;
66+ }
67+ assert_eq!(count, FRAMES, "{name}: every block came back out");
68+
69+ // The fixture is keyed twice (`-g 30`), and a seek may only ever land on
70+ // a keyframe. *Which* block that is, is the encoder's business: an HEVC
71+ // stream with B-frames is stored in decode order and the second IDR
72+ // lands a couple of blocks before the display frame it shows, so the
73+ // check is on the rule rather than on the number.
74+ let second = demuxer.seek_to_sync_at_or_before(FRAMES - 1);
75+ assert!(
76+ second > 0 && second < i64::from(FRAMES),
77+ "{name}: a second keyframe, at {second}"
78+ );
79+ assert_eq!(
80+ demuxer.seek_to_sync_at_or_before(second as u32),
81+ second,
82+ "{name}: landing on a keyframe stays on it"
83+ );
84+ assert_eq!(
85+ demuxer.seek_to_sync_at_or_before(second as u32 - 1),
86+ 0,
87+ "{name}: one block earlier there is only the first keyframe"
88+ );
89+ }
90+
91+ // The invariant: the AV1 mkv and the HEVC mp4 still read as themselves.
92+ let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
93+ assert_eq!(av1.codec, Codec::Av1);
94+ let (mp4, hevc) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
95+ assert_eq!(mp4.codec, Codec::Hevc);
96+ assert_eq!(hevc.bit_depth(), 8);
97+}
98+
99+/// A Matroska file's sound is read now, and a 5.1 track joins the timeline as
100+/// the stereo source the fold makes of it.
101+#[test]
102+fn matroska_audio_is_read_and_five_one_arrives_as_stereo() {
103+ let stereo = AudioSession::probe(asset("test_hevc.mkv"), 0)
104+ .expect("probe")
105+ .expect("the fixture has an AAC track");
106+ assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2));
107+
108+ let wide = AudioSession::probe(asset("test_hevc10.mkv"), 0)
109+ .expect("probe")
110+ .expect("the fixture has a 5.1 AAC track");
111+ assert_eq!(
112+ (wide.sample_rate, wide.channels),
113+ (48_000, 2),
114+ "5.1 is folded to the layout one output device carries"
115+ );
116+
117+ // The picker's row, which is what a user chooses a stream from.
118+ let streams = AudioSession::probe_streams(asset("test_hevc10.mkv")).expect("streams");
119+ assert_eq!(streams.len(), 1);
120+ assert_eq!(streams[0].codec, "aac");
121+ assert_eq!(streams[0].channels, 2);
122+ assert!(streams[0].decodable);
123+
124+ // ...and nothing is left to explain away: a file whose sound plays is not
125+ // one the "cannot be decoded" notice may name.
126+ assert!(
127+ AudioSession::open(asset("test_hevc10.mkv"))
128+ .expect("open")
129+ .is_some()
130+ );
131+}
132+
133+/// The fold, measured on the tones the fixture puts one per channel: every
134+/// channel but the LFE reaches the stereo pair, the surrounds and the centre at
135+/// -3 dB of the fronts, and nothing crosses sides.
136+///
137+/// Which tone is which *position* is the encoder's business (ffmpeg's AAC
138+/// encoder does not keep the order they were written in), so the check is on
139+/// the shape: two full-weight tones, one per side; one tone in both at -3 dB;
140+/// two more at -3 dB, one per side; and the 60 Hz LFE nowhere.
141+#[test]
142+fn the_five_one_fold_keeps_every_channel_but_the_lfe() {
143+ let (meta, rx) = AudioSession::open(asset("test_hevc10.mkv"))
144+ .expect("open")
145+ .expect("the fixture has sound");
146+ assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
147+ let mut left = Vec::new();
148+ let mut right = Vec::new();
149+ for chunk in rx {
150+ for pair in chunk.samples.chunks_exact(2) {
151+ left.push(pair[0]);
152+ right.push(pair[1]);
153+ }
154+ }
155+ // Past the encoder priming, and a whole number of cycles of every tone.
156+ let (left, right) = (&left[9_600..57_600], &right[9_600..57_600]);
157+ let tones = [60.0, 220.0, 440.0, 880.0, 1320.0, 1760.0];
158+ let l: Vec<f32> = tones.iter().map(|f| tone(left, *f)).collect();
159+ let r: Vec<f32> = tones.iter().map(|f| tone(right, *f)).collect();
160+
161+ // The source tones are at 0.125 (lavfi's `sine`), and the fold divides by
162+ // the sum of its own coefficients so a full-scale source cannot clip.
163+ let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);
164+ let full = 0.125 * norm;
165+ let quiet = full * std::f32::consts::FRAC_1_SQRT_2;
166+ let near = |got: f32, want: f32| (got - want).abs() < 0.01;
167+
168+ assert!(
169+ near(l[0], 0.0) && near(r[0], 0.0),
170+ "the LFE is dropped: {} {}",
171+ l[0],
172+ r[0]
173+ );
174+ let both = tones
175+ .iter()
176+ .enumerate()
177+ .filter(|(i, _)| near(l[*i], quiet) && near(r[*i], quiet))
178+ .count();
179+ assert_eq!(both, 1, "exactly the centre reaches both sides: {l:?} {r:?}");
180+ let fronts = tones
181+ .iter()
182+ .enumerate()
183+ .filter(|(i, _)| near(l[*i], full) != near(r[*i], full))
184+ .count();
185+ assert_eq!(fronts, 2, "one front channel per side: {l:?} {r:?}");
186+ let surrounds = tones
187+ .iter()
188+ .enumerate()
189+ .filter(|(i, _)| {
190+ (near(l[*i], quiet) && near(r[*i], 0.0)) || (near(r[*i], quiet) && near(l[*i], 0.0))
191+ })
192+ .count();
193+ assert_eq!(surrounds, 2, "one surround per side, at -3 dB: {l:?} {r:?}");
194+}
195+
196+/// Amplitude of one frequency in `x` (Goertzel), which is what "this channel
197+/// reached that output" is measured with.
198+fn tone(x: &[f32], freq: f32) -> f32 {
199+ let w = 2.0 * std::f32::consts::PI * freq / 48_000.0;
200+ let (cos, sin) = (w.cos(), w.sin());
201+ let (mut s1, mut s2) = (0.0f32, 0.0f32);
202+ for &v in x {
203+ let s0 = v + 2.0 * cos * s1 - s2;
204+ s2 = s1;
205+ s1 = s0;
206+ }
207+ let (re, im) = (s1 - s2 * cos, s2 * sin);
208+ 2.0 * (re * re + im * im).sqrt() / x.len() as f32
209+}
210+
211+/// The picture, on the hardware that decodes it: every frame of both files, at
212+/// the size the container declared. Main 10 goes through the P010 pool and is
213+/// read back to the same 8-bit I420 the 8-bit path hands out, so the only thing
214+/// this can tell them apart by is that neither errors.
215+#[test]
216+#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
217+fn the_plugin_decodes_hevc_in_matroska_at_both_depths() {
218+ for name in ["test_hevc.mkv", "test_hevc10.mkv"] {
219+ let mut hw = HwSession::open(&asset(name)).expect("no hardware decode plugin available");
220+ let mut count = 0;
221+ let mut lit = 0;
222+ while let Some((y, _, _, w, h)) = hw.next_frame().expect("hardware decode") {
223+ assert_eq!((w, h), (1280, 720), "{name} frame {count}");
224+ // Not a black frame: the fixture is a colour pattern, and a P010
225+ // surface read back through the NV12 path would come out as noise
226+ // or as nothing at all.
227+ if y.iter().any(|&s| s > 32) {
228+ lit += 1;
229+ }
230+ count += 1;
231+ }
232+ assert_eq!(count, FRAMES as usize, "{name}");
233+ assert_eq!(lit, count, "{name}: every frame carries picture");
234+ }
235+}
236+
237+/// ...and the same file through the session a clip actually plays from, which
238+/// is where a codec that only the plugin can decode is refused if it cannot.
239+#[test]
240+#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
241+fn a_ten_bit_matroska_clip_decodes_through_the_ordinary_session() {
242+ let (meta, frames) = DecodeSession::open(asset("test_hevc10.mkv")).expect("open");
243+ assert_eq!(meta.codec, Codec::Hevc);
244+ assert_eq!(frames.iter().count(), FRAMES as usize);
245+}
crates/engine/tests/images.rsmodified+89 -0
@@ -360,6 +360,95 @@ fn a_still_survives_the_project_round_trip() {
360 let _ = std::fs::remove_dir_all(&dir);360 let _ = std::fs::remove_dir_all(&dir);
361 }361 }
362 362
363+/// The save renumbers sources by first use, so a still at the head of `V1`
364+/// comes back as **source 0** however the session was scaffolded -- and source
365+/// 0 is what everything used to read the timeline off. A picture defines no
366+/// frame rate and has no sound, so the reload used to read this project as 30
367+/// fps (refusing the 25 fps footage still on `A1` by name) and open the output
368+/// device on a PNG (a timeline that plays silent although its clips have
369+/// sound). Nothing may assume what source 0 *is*: the rate comes from the first
370+/// source that has one, and the sound from the first that could have any.
371+#[test]
372+fn a_still_at_saved_source_zero_keeps_the_rate_and_the_sound() {
373+ pin_software();
374+ let dir = std::env::temp_dir().join(format!("ve_still_first_{}", std::process::id()));
375+ let _ = std::fs::remove_dir_all(&dir);
376+ std::fs::create_dir_all(&dir).expect("scratch dir");
377+ let media = dir.join("test_25fps.mp4");
378+ let still = dir.join("test_still.png");
379+ std::fs::copy(asset("test_25fps.mp4"), &media).expect("copy the video");
380+ std::fs::copy(asset("test_still.png"), &still).expect("copy the still");
381+
382+ // 25 fps, which no still is ever given: the rate alone says which source
383+ // the reload scaffolded from.
384+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
385+ session.set_gain(0.0);
386+ assert!((session.meta().frame_rate - 25.0).abs() < 0.01);
387+ session.import(&still).expect("a picture");
388+ // Over the head of V1, where it takes the whole take's picture: the sound
389+ // stays on A1, so the still is the first clip in save order and the video
390+ // is a source only the audio lane names.
391+ assert!(
392+ session
393+ .place_stream_at(0.0, &still, 0, Some(Lane::V1))
394+ .expect("a still joins any timeline")
395+ );
396+ assert!(session.lane_clips(Lane::V1).len() == 1 && session.lane_clips(Lane::A1).len() == 1);
397+
398+ let project = dir.join("still_first.edith");
399+ session.save_project(&project).expect("save");
400+ let text = std::fs::read_to_string(&project).expect("read the project");
401+ let source_0 = text
402+ .lines()
403+ .find(|l| l.starts_with("source "))
404+ .expect("a source line");
405+ assert!(
406+ source_0.contains("test_still.png"),
407+ "the premise: the save put the still at index 0 -- {source_0}"
408+ );
409+
410+ let reopened = PlaybackSession::open_project(&project).expect("a saved project always reopens");
411+ assert!(
412+ (reopened.meta().frame_rate - 25.0).abs() < 0.01,
413+ "the footage's rate, not the still's 30: {}",
414+ reopened.meta().frame_rate
415+ );
416+ // The same sound, at the same place, playing the same file -- by a *new*
417+ // index, which is the renumbering this whole test is about.
418+ let (sound, was) = (
419+ reopened.lane_clips(Lane::A1)[0],
420+ session.lane_clips(Lane::A1)[0],
421+ );
422+ assert_eq!(
423+ (sound.start, sound.in_frame, sound.out_frame),
424+ (was.start, was.in_frame, was.out_frame)
425+ );
426+ assert!(
427+ reopened.sources()[sound.source]
428+ .path
429+ .ends_with("test_25fps.mp4"),
430+ "the take's sound still names the video"
431+ );
432+ assert!(
433+ reopened.audio_disabled_reason().is_none(),
434+ "a still is not a reason a timeline is silent: {:?}",
435+ reopened.audio_disabled_reason()
436+ );
437+ // And the sound itself, through the very opener a seek builds its worker
438+ // with: source 0 is the PNG here, and one opened unconditionally is an
439+ // error that takes every lane's audio down with it.
440+ let sources: Vec<_> = reopened
441+ .sources()
442+ .iter()
443+ .map(|s| (s.path.clone(), s.audio_stream))
444+ .collect();
445+ let (meta, _rx) = engine::AudioSession::open_multi_streams(&sources, &[(Some(1), 0.0, 1.0)])
446+ .expect("the worker opens over a still at index 0")
447+ .expect("the take on A1 has sound");
448+ assert_eq!(meta.sample_rate, 44_100, "the take's own rate");
449+ let _ = std::fs::remove_dir_all(&dir);
450+}
451+
363 /// The export is what was watched: a timeline of video then still comes back452 /// The export is what was watched: a timeline of video then still comes back
364 /// out of the mp4 as video then still, with the still's own colours in it.453 /// out of the mp4 as video then still, with the still's own colours in it.
365 #[test]454 #[test]
crates/engine/tests/mixed_fps.rsmodified+140 -1
@@ -17,7 +17,7 @@ use std::thread::sleep;
17 use std::time::{Duration, Instant};17 use std::time::{Duration, Instant};
18 18
19 use engine::export::{ExportSettings, Format};19 use engine::export::{ExportSettings, Format};
20-use engine::project::{Edge, Lane, Speed};20+use engine::project::{Edge, Lane, Rate, Speed};
21 use engine::{DecodeSession, Frame, PlaybackSession};21 use engine::{DecodeSession, Frame, PlaybackSession};
22 22
23 /// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines.23 /// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines.
@@ -133,6 +133,62 @@ fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() {
133 "{} s",133 "{} s",
134 session.timeline_duration()134 session.timeline_duration()
135 );135 );
136+ // ...and the sound that came down with each take is the same length as its
137+ // picture: a placed take is one linked group, so a rate that stretched only
138+ // the picture would slide the two apart on the very first drag.
139+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
140+ assert_eq!(video.len(), 3, "the 30 fps take and the two others");
141+ assert_eq!(audio.len(), video.len(), "one audio clip per take");
142+ for (v, a) in video.iter().zip(audio) {
143+ assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}");
144+ }
145+}
146+
147+/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30
148+/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate
149+/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame
150+/// per clip to pile up into a visible drift over an hour, which is why the
151+/// mapping is built out of the muxer's own timescales and not a division.
152+#[test]
153+fn a_23_976_rate_is_exact_and_never_drifts() {
154+ let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30");
155+ assert!(
156+ (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15,
157+ "{}",
158+ ntsc.as_f64()
159+ );
160+ // Independent integer arithmetic, out to an hour of source and past it: 800
161+ // source frames per 1001 timeline ones, and a file's length is that ceiled
162+ // (the last picture must still be reachable by a trim).
163+ for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] {
164+ assert_eq!(
165+ u64::from(ntsc.timeline_at(source as u32)),
166+ (source * 1001).div_ceil(800),
167+ "{source} source frames"
168+ );
169+ }
170+ // ...and the two directions stay each other's inverse at every one of them:
171+ // the frame an export writes at timeline frame `d` is the frame playback is
172+ // holding there, which is what `timeline_at`'s ceil buys.
173+ for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] {
174+ let source = ntsc.source_at(d);
175+ assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due");
176+ assert!(
177+ ntsc.timeline_at(source + 1) > d,
178+ "the next frame is due too early at {d}"
179+ );
180+ }
181+ // A timeline's own rate conforms by nothing at all, exactly -- whichever of
182+ // the two rates it is written at.
183+ assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time());
184+ assert!(
185+ Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0)
186+ .expect("ntsc over ntsc")
187+ .is_real_time()
188+ );
189+ // A rate no timescale can name is refused rather than read 1:1 in silence:
190+ // the one thing `matches_timeline` still turns a file away for.
191+ assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all");
136 }192 }
137 193
138 /// The picture on screen at a timeline frame is the picture the *file* holds194 /// The picture on screen at a timeline frame is the picture the *file* holds
@@ -162,6 +218,55 @@ fn playback_shows_the_frame_the_file_holds_there() {
162 session.seek(f64::from(start + 59) / FPS);218 session.seek(f64::from(start + 59) / FPS);
163 let last = next_frame(&mut session, "the last frame of the clip");219 let last = next_frame(&mut session, "the last frame of the clip");
164 assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last");220 assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last");
221+ // ...and the frame in front of it is the 30 fps take, frame for frame: a
222+ // rate belongs to the source that has one, so the clip beside it is read
223+ // exactly as it was before any of this existed.
224+ let av = asset("test_av.mp4");
225+ session.seek(f64::from(start - 1) / FPS);
226+ let before = next_frame(&mut session, "the last frame of the 30 fps take");
227+ assert_eq!(before.index, start - 1);
228+ assert!(
229+ before.bgra == source_frame(&av, start - 1),
230+ "the 30 fps clip is still frame for frame"
231+ );
232+}
233+
234+/// A trim of a clip at another rate is dragged in *timeline* frames and commits
235+/// the source range those frames are worth -- so the box is exactly the room it
236+/// was dragged to, and the picture at its new edge is the file's own frame
237+/// there.
238+#[test]
239+fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() {
240+ let pal = asset("test_25fps.mp4");
241+ let mut session = open(asset("test_av.mp4"));
242+ import_and_place(&mut session, &pal);
243+ session.pause();
244+ let start = 150u32;
245+ // Drag its tail back to 30 timeline frames of room: one second, which at 25
246+ // fps is the file's first 25 pictures.
247+ assert!(
248+ session.trim_clip(Lane::V1, 1, Edge::End, start + 30),
249+ "trim the tail of the 25 fps clip"
250+ );
251+ let clip = session.lane_clips(Lane::V1)[1];
252+ assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}");
253+ session.seek(f64::from(start + 29) / FPS);
254+ let last = next_frame(&mut session, "the trimmed tail");
255+ assert!(
256+ last.bgra == source_frame(&pal, 24),
257+ "one second of a 25 fps file ends on its frame 24"
258+ );
259+ // ...and its head, dragged forward into source it keeps: 6 timeline frames
260+ // in is 5 source frames in, and the tail did not move.
261+ assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6));
262+ let clip = session.lane_clips(Lane::V1)[1];
263+ assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}");
264+ session.seek(f64::from(start + 6) / FPS);
265+ let head = next_frame(&mut session, "the trimmed head");
266+ assert!(
267+ head.bgra == source_frame(&pal, 5),
268+ "6 frames of a 30 fps timeline is 5 frames of a 25 fps file"
269+ );
165 }270 }
166 271
167 /// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is272 /// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is
@@ -276,5 +381,39 @@ fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() {
276 held, 5,381 held, 5,
277 "30 timeline frames of a 25 fps clip hold 5 pictures over"382 "30 timeline frames of a 25 fps clip hold 5 pictures over"
278 );383 );
384+
385+ // ...and *which* picture each of those frames is: the very one playback
386+ // holds there, which is the whole reason the two conversions are one
387+ // floor/ceil pair. Nearer its own source frame than either neighbour rather
388+ // than equal to it -- the export is re-encoded, so no pixel survives whole.
389+ for offset in [0u32, 1, 6, 12, 24, 29] {
390+ let want = (u64::from(offset) * 25_000 / 30_000) as u32;
391+ let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want));
392+ for other in [want.saturating_sub(1), want + 1] {
393+ if other == want {
394+ continue;
395+ }
396+ assert!(
397+ mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)),
398+ "exported frame {offset} of the 25 fps clip is nearer source \
399+ frame {other} than its own {want}"
400+ );
401+ }
402+ }
403+
404+ // The sound came out as long as the picture, from a *packet copy*: a clip
405+ // counts timeline frames whatever its file was shot at, so the window this
406+ // export trimmed the 25 fps file's AAC to is whole timeline frames and the
407+ // copy is in sync. This is the assertion behind the note in
408+ // `export::copy_audio` that says not to turn a conformed lane into a
409+ // re-encode.
410+ let secs = engine::AudioSession::duration_secs(&out)
411+ .expect("probe the export")
412+ .expect("the export has sound");
413+ let want = f64::from(total) / FPS;
414+ assert!(
415+ (secs - want).abs() < 0.05,
416+ "sound is {secs} s under {want} s of picture"
417+ );
279 std::fs::remove_file(&out).ok();418 std::fs::remove_file(&out).ok();
280 }419 }
scripts/gen_fixtures.shmodified+26 -0
@@ -113,6 +113,32 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115 -c:a aac -b:a 128k assets/test_av1.mkv115 -c:a aac -b:a 128k assets/test_av1.mkv
116+# HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as
117+# test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for
118+# the same reason test_av1.mkv has it (a second keyframe to seek to), and the
119+# AAC track is read out of the mkv now rather than named as unsupported.
120+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
121+ -f lavfi -i "sine=frequency=440:duration=2" \
122+ -f lavfi -i "sine=frequency=880:duration=2" \
123+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
124+ -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p \
125+ -c:a aac -b:a 128k assets/test_hevc.mkv
126+# ...and the same file in the shape the ask came from: HEVC **Main 10** with a
127+# 5.1 AAC track, which is a 4K BluRay remux in miniature. The picture decodes
128+# through a P010 surface pool and the sound is folded to stereo, so both halves
129+# of that file have a fixture. One tone per channel -- 440 FL, 880 FR, 220 FC,
130+# 60 LFE, 1320 BL, 1760 BR as written, whatever the encoder's own element order
131+# does with them -- so a test can say which channel reached which output.
132+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
133+ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
134+ -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \
135+ -f lavfi -i "sine=frequency=220:duration=2:sample_rate=48000" \
136+ -f lavfi -i "sine=frequency=60:duration=2:sample_rate=48000" \
137+ -f lavfi -i "sine=frequency=1320:duration=2:sample_rate=48000" \
138+ -f lavfi -i "sine=frequency=1760:duration=2:sample_rate=48000" \
139+ -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \
140+ -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \
141+ -c:a aac -b:a 384k assets/test_hevc10.mkv
116 # Sync fixture: one flash and one beep, at the same instant. Black picture with142 # Sync fixture: one flash and one beep, at the same instant. Black picture with
117 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that143 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
118 # stretch — so a test can find each of them and say how far apart they came out.144 # stretch — so a test can find each of them and say how far apart they came out.
vendor/cros-codecs/src/backend/vaapi/decoder.rsmodified+7 -3
@@ -73,7 +73,6 @@ pub(crate) trait VaStreamInfo {
73 /// Returns the VA profile of the stream.73 /// Returns the VA profile of the stream.
74 fn va_profile(&self) -> anyhow::Result<i32>;74 fn va_profile(&self) -> anyhow::Result<i32>;
75 /// Returns the RT format of the stream.75 /// Returns the RT format of the stream.
76- #[allow(dead_code)]
77 fn rt_format(&self) -> anyhow::Result<u32>;76 fn rt_format(&self) -> anyhow::Result<u32>;
78 /// Returns the minimum number of surfaces required to decode the stream.77 /// Returns the minimum number of surfaces required to decode the stream.
79 fn min_num_surfaces(&self) -> usize;78 fn min_num_surfaces(&self) -> usize;
@@ -255,13 +254,18 @@ impl<V: VideoFrame> VaapiBackend<V> {
255 self.stream_info.min_num_frames = stream_params.min_num_surfaces();254 self.stream_info.min_num_frames = stream_params.min_num_surfaces();
256 255
257 // TODO: Handle context re-use256 // TODO: Handle context re-use
258- // TODO: We should obtain RT_FORMAT from stream_info257+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the RT format comes
258+ // from the stream rather than being assumed 8-bit 4:2:0, which is what
259+ // an HEVC Main 10 stream needs -- its surfaces are P010 and a
260+ // YUV420-only config rejects them. This is upstream's own TODO, and
261+ // `VaStreamInfo::rt_format` is upstream's own answer to it.
262+ let rt_format = stream_params.rt_format().unwrap_or(libva::VA_RT_FORMAT_YUV420);
259 let config = self263 let config = self
260 .display264 .display
261 .create_config(265 .create_config(
262 vec![libva::VAConfigAttrib {266 vec![libva::VAConfigAttrib {
263 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,267 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
264- value: libva::VA_RT_FORMAT_YUV420,268+ value: rt_format,
265 }],269 }],
266 stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?,270 stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?,
267 libva::VAEntrypoint::VAEntrypointVLD,271 libva::VAEntrypoint::VAEntrypointVLD,
vendor/cros-codecs/src/lib.rsmodified+9 -0
@@ -222,6 +222,10 @@ pub enum DecodedFormat {
222 I410,222 I410,
223 /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used.223 /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used.
224 I412,224 I412,
225+ /// One Y and one interleaved UV plane, 4:2:0 sampling, 16 bits per sample,
226+ /// LE. Only the 10 MSBs are used. LOCAL PATCH (see /Cargo.toml
227+ /// [patch.crates-io]): what an HEVC Main 10 stream decodes into.
228+ P010,
225 /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample.229 /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample.
226 /// In a tiled format.230 /// In a tiled format.
227 MM21,231 MM21,
@@ -242,6 +246,7 @@ impl FromStr for DecodedFormat {
242 "i212" | "I212" => Ok(DecodedFormat::I212),246 "i212" | "I212" => Ok(DecodedFormat::I212),
243 "i410" | "I410" => Ok(DecodedFormat::I410),247 "i410" | "I410" => Ok(DecodedFormat::I410),
244 "i412" | "I412" => Ok(DecodedFormat::I412),248 "i412" | "I412" => Ok(DecodedFormat::I412),
249+ "p010" | "P010" => Ok(DecodedFormat::P010),
245 "mm21" | "MM21" => Ok(DecodedFormat::MM21),250 "mm21" | "MM21" => Ok(DecodedFormat::MM21),
246 _ => Err("unrecognized output format. \251 _ => Err("unrecognized output format. \
247 Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"),252 Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"),
@@ -254,6 +259,7 @@ impl From<Fourcc> for DecodedFormat {
254 match fourcc.to_string().as_str() {259 match fourcc.to_string().as_str() {
255 "I420" => DecodedFormat::I420,260 "I420" => DecodedFormat::I420,
256 "NV12" | "NM12" => DecodedFormat::NV12,261 "NV12" | "NM12" => DecodedFormat::NV12,
262+ "P010" => DecodedFormat::P010,
257 "MM21" => DecodedFormat::MM21,263 "MM21" => DecodedFormat::MM21,
258 _ => todo!("Fourcc {} not yet supported", fourcc),264 _ => todo!("Fourcc {} not yet supported", fourcc),
259 }265 }
@@ -265,6 +271,7 @@ impl From<DecodedFormat> for Fourcc {
265 match format {271 match format {
266 DecodedFormat::I420 => Fourcc::from(b"I420"),272 DecodedFormat::I420 => Fourcc::from(b"I420"),
267 DecodedFormat::NV12 => Fourcc::from(b"NV12"),273 DecodedFormat::NV12 => Fourcc::from(b"NV12"),
274+ DecodedFormat::P010 => Fourcc::from(b"P010"),
268 DecodedFormat::MM21 => Fourcc::from(b"MM21"),275 DecodedFormat::MM21 => Fourcc::from(b"MM21"),
269 _ => todo!(),276 _ => todo!(),
270 }277 }
@@ -417,6 +424,8 @@ pub fn decoded_frame_size(format: DecodedFormat, width: usize, height: usize) ->
417 u_size + uv_size424 u_size + uv_size
418 }425 }
419 DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3,426 DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3,
427+ // LOCAL PATCH: NV12 with 16-bit samples.
428+ DecodedFormat::P010 => decoded_frame_size(DecodedFormat::NV12, width, height) * 2,
420 DecodedFormat::MM21 => panic!("Unable to convert to MM21"),429 DecodedFormat::MM21 => panic!("Unable to convert to MM21"),
421 }430 }
422 }431 }
vendor/cros-codecs/src/video_frame.rsmodified+12 -1
@@ -134,7 +134,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static {
134 | DecodedFormat::I212134 | DecodedFormat::I212
135 | DecodedFormat::I410135 | DecodedFormat::I410
136 | DecodedFormat::I412 => 3,136 | DecodedFormat::I412 => 3,
137- DecodedFormat::NV12 | DecodedFormat::MM21 => 2,137+ DecodedFormat::NV12 | DecodedFormat::P010 | DecodedFormat::MM21 => 2,
138 }138 }
139 }139 }
140 140
@@ -152,6 +152,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static {
152 | DecodedFormat::I012152 | DecodedFormat::I012
153 | DecodedFormat::I210153 | DecodedFormat::I210
154 | DecodedFormat::I212154 | DecodedFormat::I212
155+ | DecodedFormat::P010
155 | DecodedFormat::MM21 => {156 | DecodedFormat::MM21 => {
156 if plane_idx == 0 {157 if plane_idx == 0 {
157 1158 1
@@ -177,6 +178,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static {
177 | DecodedFormat::NV12178 | DecodedFormat::NV12
178 | DecodedFormat::I010179 | DecodedFormat::I010
179 | DecodedFormat::I012180 | DecodedFormat::I012
181+ | DecodedFormat::P010
180 | DecodedFormat::MM21 => {182 | DecodedFormat::MM21 => {
181 if plane_idx == 0 {183 if plane_idx == 0 {
182 1184 1
@@ -217,6 +219,15 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static {
217 2219 2
218 }220 }
219 }221 }
222+ // LOCAL PATCH: P010 is NV12 with 16-bit samples, so its
223+ // chroma element -- one UV pair -- is four bytes wide.
224+ DecodedFormat::P010 => {
225+ if plane_idx == 0 {
226+ 2
227+ } else {
228+ 4
229+ }
230+ }
220 })231 })
221 }232 }
222 }233 }
vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rsmodified+3 -0
@@ -528,6 +528,9 @@ impl VideoFrame for GenericDmaVideoFrame {
528 // TODO: Add more supported formats528 // TODO: Add more supported formats
529 let rt_format = match self.decoded_format().unwrap() {529 let rt_format = match self.decoded_format().unwrap() {
530 DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420,530 DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420,
531+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the 10-bit
532+ // surface an HEVC Main 10 stream decodes into.
533+ DecodedFormat::P010 => libva::VA_RT_FORMAT_YUV420_10,
531 _ => return Err("Format unsupported for VA-API export".to_string()),534 _ => return Err("Format unsupported for VA-API export".to_string()),
532 };535 };
533 536
vendor/rusty_aac/Cargo.tomladded+54 -0
@@ -0,0 +1,54 @@
1+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2+#
3+# When uploading crates to the registry Cargo will automatically
4+# "normalize" Cargo.toml files for maximal compatibility
5+# with all versions of Cargo and also rewrite `path` dependencies
6+# to registry (e.g., crates.io) dependencies.
7+#
8+# If you are reading this file be aware that the original Cargo.toml
9+# will likely look very different (and much more reasonable).
10+# See Cargo.toml.orig for the original contents.
11+
12+[package]
13+edition = "2021"
14+rust-version = "1.85"
15+name = "rusty_aac"
16+version = "0.5.0"
17+authors = ["Mata Network <https://www.mata.network>"]
18+build = false
19+autolib = false
20+autobins = false
21+autoexamples = false
22+autotests = false
23+autobenches = false
24+description = "Pure-Rust AAC-LC decoder + encoder, no C/FFI. ~5x faster than FFmpeg's native AAC encoder and beats it on mono music at 128k+ (PEAQ-measured). Level-invariant transient detection, joint stereo rate loop, ADTS/MP4/LATM-LOAS, 5.1 layouts, HE-AAC signalling."
25+homepage = "https://github.com/Remade-With-Rust/remade_ffmpeg_rs"
26+readme = "README.md"
27+keywords = [
28+ "aac",
29+ "audio",
30+ "codec",
31+ "decoder",
32+ "encoder",
33+]
34+categories = [
35+ "multimedia::audio",
36+ "multimedia::encoding",
37+]
38+license = "Apache-2.0"
39+repository = "https://github.com/Remade-With-Rust/remade_ffmpeg_rs"
40+
41+[features]
42+default = ["simd"]
43+lab = []
44+simd = []
45+simd-avx512 = ["simd"]
46+
47+[lib]
48+name = "rusty_aac"
49+path = "src/lib.rs"
50+
51+[dependencies]
52+
53+# LOCAL: the crate's own `lab` examples and their allocator dev-dependency are
54+# not vendored -- only the library is, and only for its decoder.
vendor/rusty_aac/LICENSEadded+201 -0
@@ -0,0 +1,201 @@
1+ Apache License
2+ Version 2.0, January 2004
3+ http://www.apache.org/licenses/
4+
5+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+ 1. Definitions.
8+
9+ "License" shall mean the terms and conditions for use, reproduction,
10+ and distribution as defined by Sections 1 through 9 of this document.
11+
12+ "Licensor" shall mean the copyright owner or entity authorized by
13+ the copyright owner that is granting the License.
14+
15+ "Legal Entity" shall mean the union of the acting entity and all
16+ other entities that control, are controlled by, or are under common
17+ control with that entity. For the purposes of this definition,
18+ "control" means (i) the power, direct or indirect, to cause the
19+ direction or management of such entity, whether by contract or
20+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+ outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+ "You" (or "Your") shall mean an individual or Legal Entity
24+ exercising permissions granted by this License.
25+
26+ "Source" form shall mean the preferred form for making modifications,
27+ including but not limited to software source code, documentation
28+ source, and configuration files.
29+
30+ "Object" form shall mean any form resulting from mechanical
31+ transformation or translation of a Source form, including but
32+ not limited to compiled object code, generated documentation,
33+ and conversions to other media types.
34+
35+ "Work" shall mean the work of authorship, whether in Source or
36+ Object form, made available under the License, as indicated by a
37+ copyright notice that is included in or attached to the work
38+ (an example is provided in the Appendix below).
39+
40+ "Derivative Works" shall mean any work, whether in Source or Object
41+ form, that is based on (or derived from) the Work and for which the
42+ editorial revisions, annotations, elaborations, or other modifications
43+ represent, as a whole, an original work of authorship. For the purposes
44+ of this License, Derivative Works shall not include works that remain
45+ separable from, or merely link (or bind by name) to the interfaces of,
46+ the Work and Derivative Works thereof.
47+
48+ "Contribution" shall mean any work of authorship, including
49+ the original version of the Work and any modifications or additions
50+ to that Work or Derivative Works thereof, that is intentionally
51+ submitted to Licensor for inclusion in the Work by the copyright owner
52+ or by an individual or Legal Entity authorized to submit on behalf of
53+ the copyright owner. For the purposes of this definition, "submitted"
54+ means any form of electronic, verbal, or written communication sent
55+ to the Licensor or its representatives, including but not limited to
56+ communication on electronic mailing lists, source code control systems,
57+ and issue tracking systems that are managed by, or on behalf of, the
58+ Licensor for the purpose of discussing and improving the Work, but
59+ excluding communication that is conspicuously marked or otherwise
60+ designated in writing by the copyright owner as "Not a Contribution."
61+
62+ "Contributor" shall mean Licensor and any individual or Legal Entity
63+ on behalf of whom a Contribution has been received by Licensor and
64+ subsequently incorporated within the Work.
65+
66+ 2. Grant of Copyright License. Subject to the terms and conditions of
67+ this License, each Contributor hereby grants to You a perpetual,
68+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+ copyright license to reproduce, prepare Derivative Works of,
70+ publicly display, publicly perform, sublicense, and distribute the
71+ Work and such Derivative Works in Source or Object form.
72+
73+ 3. Grant of Patent License. Subject to the terms and conditions of
74+ this License, each Contributor hereby grants to You a perpetual,
75+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+ (except as stated in this section) patent license to make, have made,
77+ use, offer to sell, sell, import, and otherwise transfer the Work,
78+ where such license applies only to those patent claims licensable
79+ by such Contributor that are necessarily infringed by their
80+ Contribution(s) alone or by combination of their Contribution(s)
81+ with the Work to which such Contribution(s) was submitted. If You
82+ institute patent litigation against any entity (including a
83+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84+ or a Contribution incorporated within the Work constitutes direct
85+ or contributory patent infringement, then any patent licenses
86+ granted to You under this License for that Work shall terminate
87+ as of the date such litigation is filed.
88+
89+ 4. Redistribution. You may reproduce and distribute copies of the
90+ Work or Derivative Works thereof in any medium, with or without
91+ modifications, and in Source or Object form, provided that You
92+ meet the following conditions:
93+
94+ (a) You must give any other recipients of the Work or Derivative
95+ Works a copy of this License; and
96+
97+ (b) You must cause any modified files to carry prominent notices
98+ stating that You changed the files; and
99+
100+ (c) You must retain, in the Source form of any Derivative Works
101+ that You distribute, all copyright, patent, trademark, and
102+ attribution notices from the Source form of the Work,
103+ excluding those notices that do not pertain to any part of
104+ the Derivative Works; and
105+
106+ (d) If the Work includes a "NOTICE" text file as part of its
107+ distribution, then any Derivative Works that You distribute must
108+ include a readable copy of the attribution notices contained
109+ within such NOTICE file, excluding those notices that do not
110+ pertain to any part of the Derivative Works, in at least one
111+ of the following places: within a NOTICE text file distributed
112+ as part of the Derivative Works; within the Source form or
113+ documentation, if provided along with the Derivative Works; or,
114+ within a display generated by the Derivative Works, if and
115+ wherever such third-party notices normally appear. The contents
116+ of the NOTICE file are for informational purposes only and do
117+ not modify the License. You may add Your own attribution notices
118+ within Derivative Works that You distribute, alongside or as an
119+ addendum to the NOTICE text from the Work, provided that such
120+ additional attribution notices cannot be construed as modifying
121+ the License.
122+
123+ You may add Your own copyright statement to Your modifications and
124+ may provide additional or different license terms and conditions
125+ for use, reproduction, or distribution of Your modifications, or
126+ for any such Derivative Works as a whole, provided Your use,
127+ reproduction, and distribution of the Work otherwise complies with
128+ the conditions stated in this License.
129+
130+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131+ any Contribution intentionally submitted for inclusion in the Work
132+ by You to the Licensor shall be under the terms and conditions of
133+ this License, without any additional terms or conditions.
134+ Notwithstanding the above, nothing herein shall supersede or modify
135+ the terms of any separate license agreement you may have executed
136+ with Licensor regarding such Contributions.
137+
138+ 6. Trademarks. This License does not grant permission to use the trade
139+ names, trademarks, service marks, or product names of the Licensor,
140+ except as required for reasonable and customary use in describing the
141+ origin of the Work and reproducing the content of the NOTICE file.
142+
143+ 7. Disclaimer of Warranty. Unless required by applicable law or
144+ agreed to in writing, Licensor provides the Work (and each
145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+ implied, including, without limitation, any warranties or conditions
148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150+ appropriateness of using or redistributing the Work and assume any
151+ risks associated with Your exercise of permissions under this License.
152+
153+ 8. Limitation of Liability. In no event and under no legal theory,
154+ whether in tort (including negligence), contract, or otherwise,
155+ unless required by applicable law (such as deliberate and grossly
156+ negligent acts) or agreed to in writing, shall any Contributor be
157+ liable to You for damages, including any direct, indirect, special,
158+ incidental, or consequential damages of any character arising as a
159+ result of this License or out of the use or inability to use the
160+ Work (including but not limited to damages for loss of goodwill,
161+ work stoppage, computer failure or malfunction, or any and all
162+ other commercial damages or losses), even if such Contributor
163+ has been advised of the possibility of such damages.
164+
165+ 9. Accepting Warranty or Additional Liability. While redistributing
166+ the Work or Derivative Works thereof, You may choose to offer,
167+ and charge a fee for, acceptance of support, warranty, indemnity,
168+ or other liability obligations and/or rights consistent with this
169+ License. However, in accepting such obligations, You may act only
170+ on Your own behalf and on Your sole responsibility, not on behalf
171+ of any other Contributor, and only if You agree to indemnify,
172+ defend, and hold each Contributor harmless for any liability
173+ incurred by, or claims asserted against, such Contributor by reason
174+ of your accepting any such warranty or additional liability.
175+
176+ END OF TERMS AND CONDITIONS
177+
178+ APPENDIX: How to apply the Apache License to your work.
179+
180+ To apply the Apache License to your work, attach the following
181+ boilerplate notice, with the fields enclosed by brackets "[]"
182+ replaced with your own identifying information. (Don't include
183+ the brackets!) The text should be enclosed in the appropriate
184+ comment syntax for the file format. We also recommend that a
185+ file or class name and description of purpose be included on the
186+ same "printed page" as the copyright notice for easier
187+ identification within third-party archives.
188+
189+ Copyright 2026 Mata Network
190+
191+ Licensed under the Apache License, Version 2.0 (the "License");
192+ you may not use this file except in compliance with the License.
193+ You may obtain a copy of the License at
194+
195+ http://www.apache.org/licenses/LICENSE-2.0
196+
197+ Unless required by applicable law or agreed to in writing, software
198+ distributed under the License is distributed on an "AS IS" BASIS,
199+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+ See the License for the specific language governing permissions and
201+ limitations under the License.
vendor/rusty_aac/README.mdadded+280 -0
@@ -0,0 +1,280 @@
1+# rusty_aac
2+
3+[![Remade With Rust](https://img.shields.io/badge/Remade%20With-Rust-000?logo=rust&logoColor=fff)](https://github.com/remade-with-rust)
4+[![By Mata Network](https://img.shields.io/badge/by-Mata%20Network-5b2be0)](https://www.mata.network)
5+[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/LICENSE)
6+
7+A pure-Rust **AAC-LC decoder and encoder**. Zero dependencies, no C, no FFI,
8+Apache-2.0.
9+
10+- **Decoder** — complete AAC-LC: long/short/transition windows with grouped
11+ scalefactors, all spectral Huffman codebooks, M/S and intensity stereo, PNS,
12+ TNS. Verified against FFmpeg: bit-exact on deterministic features.
13+- **Encoder** — to our knowledge the **first pure-Rust AAC encoder on
14+ crates.io** (the alternatives, `fdk-aac` and libxaac bindings, are C FFI).
15+ Psychoacoustic Bark-scale masking model, **level-invariant transient
16+ detection**, block switching, per-band M/S stereo with a **joint pair rate
17+ loop** routed by inter-channel correlation, frame-parallel encoding, an
18+ N/4-FFT MDCT and AVX2 (opt-in AVX-512) quantize kernels.
19+- **Transport** — ADTS, MP4 `esds`, and **LATM/LOAS** (the MPEG-TS / broadcast
20+ carriage format).
21+- **HE-AAC signalling** — SBR/PS configurations are recognised and the core is
22+ decoded at the correct **output** rate (see [HE-AAC](#he-aac-sbr--ps)).
23+- `--no-default-features` turns off the runtime-detected SIMD kernels and gives
24+ a **100%-safe scalar build** (every `unsafe` block in the crate is
25+ feature-gated SIMD).
26+
27+---
28+
29+## Measured against FFmpeg's AAC encoder
30+
31+Everything below is measured, reproducible, and generated by the harness in this
32+repo. **0.5.0 is a large quality step over 0.4.0 — a mean +0.33 ODG across the
33+whole corpus, with gains up to +2.6 ODG on the weakest content — while staying
34+~5x faster than FFmpeg.**
35+
36+<details>
37+<summary><b>How this was measured</b> (click to expand)</summary>
38+
39+- **Encoders**: this crate via its CLI vs `ffmpeg -c:a aac` (FFmpeg's *native*
40+ AAC encoder), FFmpeg 8.1.2.
41+- **Quality metric**: **PEAQ ODG** (ITU-R BS.1387), an external oracle, range
42+ `[-4, 0]` where 0 is imperceptible. Our own NMR metric is *not* used for
43+ ranking — a self-metric provably flatters the encoder it came from.
44+- **Fairness**: both candidates are decoded with the **same neutral decoder**
45+ (system FFmpeg) before scoring, so the comparison isolates the encoders.
46+- **Null arm**: reference-vs-itself through the same path scores **+0.14 ODG**.
47+ That is the harness ceiling — any score at or above it means *transparent*.
48+- **Speed**: both encoders run as subprocesses with identical invocation shape,
49+ best-of-5, ABBA-interleaved, on 24 s clips.
50+- **Corpus**: real CC0/Public-Domain music (piano, guitar, vocal; mono and
51+ stereo) plus a synthetic suite covering content classes the real corpus lacks.
52+ Real and synthetic are reported separately and never averaged together.
53+
54+Reproduce: `python tools/quality/aac_vs_ffmpeg.py` in the
55+[main repo](https://github.com/Remade-With-Rust/remade_ffmpeg_rs).
56+
57+</details>
58+
59+### What changed in 0.5.0
60+
61+Two measured wins shipped, four candidate tools **measured and rejected**. Δ is
62+`ours − ffmpeg`; positive = we sound better.
63+
64+| content | 0.4.0 (64/96/128/192k) | **0.5.0** | gain |
65+| --- | --- | --- | --- |
66+| **percussive** | -1.18 | -1.73 | -1.96 | -2.22 | **+0.49 | -0.01 | -0.17 | -0.31** | **up to +1.91** |
67+| **clean speech** | -2.03 | -2.90 | -3.05 | -2.79 | **-0.94 | -1.58 | -1.28 | -0.19** | **up to +2.61** |
68+| **guitar stereo** | -0.55 | -1.34 | -1.32 | -0.28 | **-0.31 | -0.46 | -0.15 | +0.35** | **up to +1.17** |
69+| piano stereo | -1.12 | -2.11 | -1.73 | -0.16 | -1.11 | -1.98 | -1.50 | -0.01 | up to +0.22 |
70+
71+**1. A level-invariant transient detector.** The previous detector guarded its
72+attack ratio with an *absolute* energy threshold, so it went blind on quiet
73+content — and because its running average decays between attacks, it flagged
74+percussive material **zero times at any level**. Every such frame coded as a long
75+block and took the full pre-echo hit. The replacement floors the average relative
76+to the clip's own energy. Measured mean **+0.267 ODG, worst class +0.000** — it
77+improves the two weakest classes and changes nothing anywhere else.
78+
79+**2. A joint stereo rate loop.** A channel pair's two channels each received a
80+fixed half of the frame budget and ran independent rate loops — so when M/S made
81+the side channel nearly empty, its bits were simply wasted while the mid channel
82+starved. On perfectly-correlated stereo (`L == R`) at 128 kbps that cost
83+**28 dB** of reconstruction SNR versus FFmpeg. 0.5.0 runs **one** rate loop over
84+the pair at a common base, so bits follow demand. It is **routed by inter-channel
85+correlation**, because the change is a large win on correlated stereo and a loss
86+on genuinely wide stereo.
87+
88+**Rejected after measurement** (all built, all measured, all off): TNS
89+(−0.148 mean, and it destroyed the percussive class), PNS (−0.056, damages real
90+tonal music), tonality-adaptive SMR (−0.049), intensity stereo (−0.004, neutral).
91+Shipping a tool that measures worse is not a feature.
92+
93+### Speed — 3.2–7.9× faster (mean 5.0×)
94+
95+| clip (24 s) | rusty_aac | FFmpeg native AAC | speed-up |
96+| --- | --- | --- | --- |
97+| piano | **214× realtime** | 57× realtime | **3.8×** |
98+| guitar | **306× realtime** | 39× realtime | **7.9×** |
99+| vocal | **299× realtime** | 93× realtime | **3.2×** |
100+
101+The 0.5.0 quality work cost no measurable speed.
102+
103+### Current standing, honestly
104+
105+| content | 64k | 96k | 128k | 192k |
106+| --- | --- | --- | --- | --- |
107+| piano (real, CC0) | -1.29 | -0.25 | **+0.28** | **+0.44** |
108+| guitar (real, PD) | -1.02 | -0.03 | **+0.65** | **+0.47** |
109+| vocal (real, PD) | -1.92 | -0.38 | **+0.39** | **+0.60** |
110+| guitar stereo | -0.31 | -0.46 | -0.15 | +0.35 |
111+| percussive | +0.49 | -0.01 | -0.17 | -0.31 |
112+| tonal music | +0.30 | -0.00 | -0.13 | -0.29 |
113+
114+- **We beat FFmpeg's native AAC on real mono music at ≥128 kbps**, reaching the
115+ harness transparency ceiling while FFmpeg sits around −0.3 to −0.6.
116+- **Percussive and clean speech are no longer the disasters they were** — 0.4.0
117+ lost by up to 2.2 and 3.0 ODG; 0.5.0 wins percussive at 64 kbps.
118+- **We are still behind overall**, principally at ≤96 kbps, on piano stereo, and
119+ on noise-like content. The encoder still has no bit reservoir, no VBR mode and
120+ no absolute-threshold-of-hearing term; those are the next levers, tracked with
121+ per-class evidence in
122+ [`docs/codec-aac-quality-plan.md`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/docs/codec-aac-quality-plan.md).
123+- **Rate caveat**: at the 64 k target we emit ~89% of FFmpeg's actual bitrate and
124+ at 192 k ~107%, so neither extreme is a perfectly clean like-for-like.
125+- FFmpeg's native AAC encoder is not the strongest AAC encoder in existence
126+ (libfdk-aac generally beats it); it is the one available in a permissive
127+ default build.
128+
129+## Patents
130+
131+AAC-LC is the oldest, largely-expired, lowest-risk corner of the AAC family —
132+this crate implements **only AAC-LC coding tools**. It does not implement SBR,
133+Parametric Stereo or xHE-AAC, which carry much younger patents; the HE-AAC
134+support here is limited to *reading the configuration* and decoding the AAC-LC
135+core, with no SBR reconstruction. The code is independently written and
136+Apache-2.0-licensed, but **no patent license is granted or implied** by the
137+copyright license. If you distribute products commercially, consult IP counsel
138+about your own position; see the main repo's
139+[patent notes](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/docs/compatibility.md#patents).
140+This is engineering context, not legal advice.
141+
142+## Decode
143+
144+```rust
145+use rusty_aac::{AacDecoder, Error};
146+
147+fn main() -> Result<(), Error> {
148+ let adts = std::fs::read("input.aac").map_err(|e| Error::invalid(e.to_string()))?;
149+
150+ // The decoder reads its configuration from the ADTS headers. For bare MP4
151+ // access units, build it from the esds config instead — prefer the raw-bytes
152+ // form, which also recovers HE-AAC signalling:
153+ // AacDecoder::with_config_bytes(&esds_payload)?
154+ let mut dec = AacDecoder::new();
155+
156+ let mut pcm: Vec<f32> = Vec::new(); // interleaved, [-1, 1]
157+ let mut pos = 0;
158+ while pos + 7 <= adts.len() {
159+ let hdr = rusty_aac::parse_adts(&adts[pos..])?;
160+ let frame = dec.decode(&adts[pos..pos + hdr.frame_length], None)?;
161+ println!("{} Hz, {} ch, {} samples", frame.sample_rate, frame.channels, frame.frames());
162+ pcm.extend_from_slice(&frame.samples);
163+ pos += hdr.frame_length;
164+ }
165+ Ok(())
166+}
167+```
168+
169+## Encode
170+
171+```rust
172+use rusty_aac::{AacEncoder, AacEncoderConfig, AdtsHeader, Error};
173+
174+fn main() -> Result<(), Error> {
175+ // 1 s of a 440 Hz sine, mono 44.1 kHz, interleaved f32 in [-1, 1].
176+ let sr = 44_100u32;
177+ let pcm: Vec<f32> = (0..sr)
178+ .map(|i| (i as f32 / sr as f32 * 440.0 * std::f32::consts::TAU).sin() * 0.5)
179+ .collect();
180+
181+ let mut enc = AacEncoder::new(AacEncoderConfig {
182+ bitrate_bps: 128_000,
183+ ..Default::default()
184+ });
185+ enc.push_pcm(&pcm, 1, sr)?;
186+ enc.finish(); // encodes everything, frame-parallel
187+
188+ // Packets are raw access units; wrap each in ADTS for a playable .aac file
189+ // (or hand `rusty_aac::audio_specific_config_bytes(sr, 1)` to an MP4 muxer
190+ // as the esds DecoderSpecificInfo and store the packets raw).
191+ let mut out = Vec::new();
192+ while let Ok(p) = enc.next_packet() {
193+ out.extend_from_slice(&rusty_aac::write_adts_header(&AdtsHeader {
194+ object_type: 2, // AAC-LC
195+ sample_rate: sr,
196+ channels: 1,
197+ frame_length: 7 + p.data.len(),
198+ header_len: 7,
199+ }));
200+ out.extend_from_slice(&p.data);
201+ }
202+ std::fs::write("tone.aac", &out).map_err(|e| Error::invalid(e.to_string()))?;
203+ Ok(())
204+}
205+```
206+
207+## Channel layouts
208+
209+Mono through 5.1 (`channel_configuration` 1–6) are supported and emitted with the
210+**ISO-correct element sequence** — a 5.1 stream is `SCE, CPE, CPE, LFE` with the
211+channel reordering AAC requires, not six single-channel elements. Interleaved PCM
212+is taken in the standard order (`FL, FR, FC, LFE, BL, BR`) and returned in it.
213+Seven or more channels need a `program_config_element`, which is not implemented,
214+and are **rejected** rather than mis-encoded.
215+
216+## LATM / LOAS
217+
218+```rust
219+use rusty_aac::latm::{LatmReader, write_loas_frame};
220+
221+// Parsing an MPEG-TS / broadcast stream. Use `LatmReader`, not the stateless
222+// helper: real streams send the StreamMuxConfig once and then set
223+// `useSameStreamMux` for long runs of frames.
224+let mut reader = LatmReader::new();
225+// let frame = reader.parse(&loas_bytes)?; // -> config + raw access unit
226+```
227+
228+## HE-AAC (SBR / PS)
229+
230+HE-AAC signalling is parsed in all three forms real streams use — explicit
231+hierarchical (`audioObjectType` 5/29), explicit backward-compatible (the `0x2B7`
232+sync extension), and implicit (SBR payload in the fill element).
233+
234+**The SBR high band is not reconstructed.** What this buys you is that an HE-AAC
235+stream decodes its AAC-LC core correctly and reports the true **output** sample
236+rate (twice the core rate) — without that, an HE-AAC stream plays at half speed.
237+`AacDecoder::sbr_support()` returns `SbrSupport::CoreOnly` so this is visible at
238+the API rather than discovered later.
239+
240+```rust
241+let dec = rusty_aac::AacDecoder::with_config_bytes(&esds_payload)?;
242+println!("{:?} at {:?} Hz", dec.sbr_support(), dec.output_sample_rate());
243+```
244+
245+## Features
246+
247+| feature | default | effect |
248+| --- | --- | --- |
249+| `simd` | yes | runtime-detected AVX2 quantize/`x^0.75` kernels (bit-exact vs scalar) |
250+| `simd-avx512` | no | adds an 8-lane AVX-512 tier (needs Rust ≥ 1.89; falls back at runtime) |
251+| `lab` | no | the quality lab: deterministic corpus, NMR metric, bitrate-ladder runner, WAV I/O. Dev/analysis only |
252+
253+## Part of Remade With Rust
254+
255+`rusty_aac` is the standalone AAC engine of
256+**[remade_ffmpeg_rs](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)** — a
257+ground-up, permissively-licensed Rust rebuild of FFmpeg. Sister project:
258+**[FFAI](https://github.com/Remade-With-Rust/FFAI)** — media for an AI-first
259+world. More at **[github.com/remade-with-rust](https://github.com/remade-with-rust)**.
260+
261+Sibling codec crates: [`rusty_h264`](https://crates.io/crates/rusty_h264),
262+[`rusty_vp9`](https://crates.io/crates/rusty_vp9),
263+[`rusty_mp3`](https://crates.io/crates/rusty_mp3),
264+[`rusty-opus`](https://crates.io/crates/rusty-opus), [`rusty_vorbis`](https://crates.io/crates/rusty_vorbis), and the
265+[rusty-av1-toolkit](https://github.com/Remade-With-Rust/rusty-av1-toolkit) forks.
266+
267+## About Mata Network
268+
269+<!-- ORG BOILERPLATE — keep identical across repos -->
270+
271+[Mata Network](https://www.mata.network) builds sovereign, self-hostable
272+infrastructure. **Remade With Rust** is our open-source home for the
273+permissively-licensed building blocks that work depends on.
274+
275+<!-- /ORG BOILERPLATE -->
276+
277+## License
278+
279+Apache-2.0. See
280+[LICENSE](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/LICENSE).
vendor/rusty_aac/src/bits.rsadded+99 -0
@@ -0,0 +1,99 @@
1+//! MSB-first bit reader for AAC bitstreams.
2+
3+use crate::{Error, Result};
4+
5+/// Reads bits most-significant-first from a byte slice (the order AAC uses).
6+pub struct BitReader<'a> {
7+ data: &'a [u8],
8+ /// Absolute bit position from the start of `data`.
9+ pos: usize,
10+}
11+
12+impl<'a> BitReader<'a> {
13+ pub fn new(data: &'a [u8]) -> BitReader<'a> {
14+ BitReader { data, pos: 0 }
15+ }
16+
17+ /// Total bits remaining.
18+ pub fn bits_left(&self) -> usize {
19+ (self.data.len() * 8).saturating_sub(self.pos)
20+ }
21+
22+ /// Read a single bit.
23+ pub fn read_bit(&mut self) -> Result<u32> {
24+ let byte = self.pos / 8;
25+ if byte >= self.data.len() {
26+ return Err(Error::invalid("aac: bit reader past end of data"));
27+ }
28+ let shift = 7 - (self.pos % 8);
29+ let bit = (self.data[byte] >> shift) & 1;
30+ self.pos += 1;
31+ Ok(bit as u32)
32+ }
33+
34+ /// Read `n` bits (0..=32) into a `u32`, MSB-first.
35+ pub fn read_bits(&mut self, n: u32) -> Result<u32> {
36+ if n > 32 {
37+ return Err(Error::invalid("aac: read_bits > 32"));
38+ }
39+ let mut v = 0u32;
40+ for _ in 0..n {
41+ v = (v << 1) | self.read_bit()?;
42+ }
43+ Ok(v)
44+ }
45+
46+ /// Read one bit as a bool.
47+ pub fn read_bool(&mut self) -> Result<bool> {
48+ Ok(self.read_bit()? != 0)
49+ }
50+
51+ /// Skip `n` bits.
52+ pub fn skip(&mut self, n: usize) -> Result<()> {
53+ if self.pos + n > self.data.len() * 8 {
54+ return Err(Error::invalid("aac: skip past end of data"));
55+ }
56+ self.pos += n;
57+ Ok(())
58+ }
59+
60+ /// Advance to the next byte boundary.
61+ pub fn byte_align(&mut self) {
62+ if self.pos % 8 != 0 {
63+ self.pos += 8 - (self.pos % 8);
64+ }
65+ }
66+}
67+
68+#[cfg(test)]
69+mod tests {
70+ use super::*;
71+
72+ #[test]
73+ fn reads_bits_msb_first() {
74+ // 0b1011_0010, 0b1100_0001
75+ let mut r = BitReader::new(&[0xB2, 0xC1]);
76+ assert_eq!(r.read_bits(4).unwrap(), 0b1011);
77+ assert_eq!(r.read_bits(4).unwrap(), 0b0010);
78+ assert_eq!(r.read_bits(3).unwrap(), 0b110);
79+ assert_eq!(r.read_bit().unwrap(), 0);
80+ assert_eq!(r.read_bits(4).unwrap(), 0b0001);
81+ assert_eq!(r.bits_left(), 0);
82+ }
83+
84+ #[test]
85+ fn skip_and_align() {
86+ let mut r = BitReader::new(&[0xFF, 0x0F]);
87+ r.skip(4).unwrap();
88+ r.byte_align(); // jump to bit 8
89+ assert_eq!(r.read_bits(4).unwrap(), 0x0);
90+ assert_eq!(r.read_bits(4).unwrap(), 0xF);
91+ }
92+
93+ #[test]
94+ fn errors_past_end() {
95+ let mut r = BitReader::new(&[0x00]);
96+ assert!(r.read_bits(8).is_ok());
97+ assert!(r.read_bit().is_err());
98+ }
99+}
vendor/rusty_aac/src/codebook.rsadded+258 -0
@@ -0,0 +1,258 @@
1+//! AAC spectral Huffman codebooks: metadata + the index→coefficient decode
2+//! (ISO 14496-3 §4.6.3, Tables 4.A.2–4.A.13).
3+//!
4+//! Each codebook decodes a Huffman index into a 2- or 4-tuple of quantized
5+//! spectral coefficients. This module owns the *logic* — unpacking the index
6+//! into base-`modulo` digits, applying sign bits for the unsigned books, and
7+//! the codebook-11 escape sequence — all independent of the raw codeword
8+//! tables. The tables themselves (`HuffBook` per codebook) are fixed ISO data
9+//! transcribed separately; the decode here is what turns a correct lookup into
10+//! correct coefficients, and is verified with synthetic codebooks.
11+
12+#![allow(dead_code)]
13+
14+use crate::{Error, Result};
15+
16+use crate::bits::BitReader;
17+use crate::huffman::HuffBook;
18+
19+/// Properties of one spectral Huffman codebook.
20+#[derive(Debug, Clone, Copy)]
21+pub struct Codebook {
22+ /// Tuple size decoded per codeword: 4 (books 1–4) or 2 (books 5–11).
23+ pub dim: u8,
24+ /// `true` → magnitudes only; a sign bit follows each non-zero value.
25+ pub unsigned: bool,
26+ /// Largest absolute value the book codes directly (excludes escapes).
27+ pub lav: u8,
28+ /// `true` for book 11, which escape-codes values ≥ `lav`.
29+ pub esc: bool,
30+}
31+
32+/// Codebook properties indexed by codebook number 0..=11 (0 = ZERO_HCB).
33+pub const CODEBOOKS: [Codebook; 12] = [
34+ Codebook {
35+ dim: 0,
36+ unsigned: false,
37+ lav: 0,
38+ esc: false,
39+ }, // 0 ZERO
40+ Codebook {
41+ dim: 4,
42+ unsigned: false,
43+ lav: 1,
44+ esc: false,
45+ }, // 1
46+ Codebook {
47+ dim: 4,
48+ unsigned: false,
49+ lav: 1,
50+ esc: false,
51+ }, // 2
52+ Codebook {
53+ dim: 4,
54+ unsigned: true,
55+ lav: 2,
56+ esc: false,
57+ }, // 3
58+ Codebook {
59+ dim: 4,
60+ unsigned: true,
61+ lav: 2,
62+ esc: false,
63+ }, // 4
64+ Codebook {
65+ dim: 2,
66+ unsigned: false,
67+ lav: 4,
68+ esc: false,
69+ }, // 5
70+ Codebook {
71+ dim: 2,
72+ unsigned: false,
73+ lav: 4,
74+ esc: false,
75+ }, // 6
76+ Codebook {
77+ dim: 2,
78+ unsigned: true,
79+ lav: 7,
80+ esc: false,
81+ }, // 7
82+ Codebook {
83+ dim: 2,
84+ unsigned: true,
85+ lav: 7,
86+ esc: false,
87+ }, // 8
88+ Codebook {
89+ dim: 2,
90+ unsigned: true,
91+ lav: 12,
92+ esc: false,
93+ }, // 9
94+ Codebook {
95+ dim: 2,
96+ unsigned: true,
97+ lav: 12,
98+ esc: false,
99+ }, // 10
100+ Codebook {
101+ dim: 2,
102+ unsigned: true,
103+ lav: 16,
104+ esc: true,
105+ }, // 11
106+];
107+
108+/// First codebook number for intensity stereo (14, 15) and the special markers.
109+pub const ZERO_HCB: u8 = 0;
110+pub const ESC_HCB: u8 = 11;
111+pub const NOISE_HCB: u8 = 13;
112+pub const INTENSITY_HCB2: u8 = 14;
113+pub const INTENSITY_HCB: u8 = 15;
114+
115+/// Decode one codeword from `book` for codebook `cb` into `out[..cb.dim]`,
116+/// returning quantized (signed) coefficients.
117+pub fn decode_tuple(
118+ cb: &Codebook,
119+ book: &HuffBook,
120+ r: &mut BitReader,
121+ out: &mut [i32],
122+) -> Result<()> {
123+ let idx = book.decode(r)?;
124+ apply_index(cb, idx, r, out)
125+}
126+
127+/// Turn a decoded codebook `idx` into quantized coefficients, reading any sign
128+/// and escape bits that follow the codeword. Split out so it can be tested
129+/// directly with explicit indices.
130+pub fn apply_index(cb: &Codebook, idx: u16, r: &mut BitReader, out: &mut [i32]) -> Result<()> {
131+ let dim = cb.dim as usize;
132+ let modulo = if cb.unsigned {
133+ cb.lav as u32 + 1
134+ } else {
135+ 2 * cb.lav as u32 + 1
136+ };
137+
138+ // Unpack the Huffman index into `dim` base-`modulo` digits (MSB first).
139+ let mut v = idx as u32;
140+ let mut digits = [0u32; 4];
141+ for d in (0..dim).rev() {
142+ digits[d] = v % modulo;
143+ v /= modulo;
144+ }
145+
146+ // Map digits to coefficients (signed books offset by -lav).
147+ for i in 0..dim {
148+ out[i] = if cb.unsigned {
149+ digits[i] as i32
150+ } else {
151+ digits[i] as i32 - cb.lav as i32
152+ };
153+ }
154+
155+ // Unsigned books: one sign bit per non-zero magnitude, in order.
156+ if cb.unsigned {
157+ for o in out.iter_mut().take(dim) {
158+ if *o != 0 && r.read_bool()? {
159+ *o = -*o;
160+ }
161+ }
162+ }
163+
164+ // Book 11: any magnitude equal to lav (16) is replaced by an escape value.
165+ if cb.esc {
166+ for o in out.iter_mut().take(dim) {
167+ if o.unsigned_abs() == cb.lav as u32 {
168+ let mag = read_escape(r)?;
169+ *o = if *o < 0 { -mag } else { mag };
170+ }
171+ }
172+ }
173+ Ok(())
174+}
175+
176+/// Escape sequence (ISO 14496-3 §4.6.3.3): N leading 1-bits, a 0, then `N+4`
177+/// bits give `value = 2^(N+4) + word`.
178+fn read_escape(r: &mut BitReader) -> Result<i32> {
179+ let mut n = 0u32;
180+ while r.read_bool()? {
181+ n += 1;
182+ if n > 24 {
183+ return Err(Error::invalid("aac: runaway escape sequence"));
184+ }
185+ }
186+ let bits = n + 4;
187+ let word = r.read_bits(bits)?;
188+ Ok(((1u32 << bits) + word) as i32)
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+ use crate::tables::spectral_book;
195+
196+ #[test]
197+ fn signed_pair_offsets_by_lav() {
198+ // cb5: dim2, signed, lav4 → modulo 9. index 56 → digits (6,2) → (2,-2).
199+ let mut r = BitReader::new(&[]); // signed → no extra bits
200+ let mut out = [0i32; 4];
201+ apply_index(&CODEBOOKS[5], 56, &mut r, &mut out).unwrap();
202+ assert_eq!(&out[..2], &[2, -2]);
203+ }
204+
205+ #[test]
206+ fn unsigned_pair_reads_sign_bits() {
207+ // cb7: dim2, unsigned, lav7 → modulo 8. index 24 → mags (3,0).
208+ // The non-zero value reads one sign bit (1 → negative).
209+ let mut r = BitReader::new(&[0x80]);
210+ let mut out = [0i32; 4];
211+ apply_index(&CODEBOOKS[7], 24, &mut r, &mut out).unwrap();
212+ assert_eq!(&out[..2], &[-3, 0]);
213+ }
214+
215+ #[test]
216+ fn book11_applies_escape_to_max_magnitude() {
217+ // cb11: index 277 → mags (16,5). signs +,+; escape for 16: N=0, word
218+ // 0011 → 16+3 = 19. bits: 0 0 0 0011 → 0000_0110 = 0x06.
219+ let mut r = BitReader::new(&[0x06]);
220+ let mut out = [0i32; 4];
221+ apply_index(&CODEBOOKS[11], 277, &mut r, &mut out).unwrap();
222+ assert_eq!(&out[..2], &[19, 5]);
223+ }
224+
225+ #[test]
226+ fn escape_with_leading_ones() {
227+ // cb11: index 272 → mags (16,0). sign(16)=+; escape: N=2 (110), word
228+ // 000101 (=5) → 64+5 = 69. bits: 0 110 000101 → 0110_0001 0100_0000.
229+ let mut r = BitReader::new(&[0x61, 0x40]);
230+ let mut out = [0i32; 4];
231+ apply_index(&CODEBOOKS[11], 272, &mut r, &mut out).unwrap();
232+ assert_eq!(&out[..2], &[69, 0]);
233+ }
234+
235+ #[test]
236+ fn metadata_matches_spec() {
237+ assert!(CODEBOOKS[1].dim == 4 && !CODEBOOKS[1].unsigned && CODEBOOKS[1].lav == 1);
238+ assert!(CODEBOOKS[3].unsigned && CODEBOOKS[3].lav == 2);
239+ assert!(CODEBOOKS[5].dim == 2 && !CODEBOOKS[5].unsigned && CODEBOOKS[5].lav == 4);
240+ assert!(CODEBOOKS[11].esc && CODEBOOKS[11].lav == 16);
241+ }
242+
243+ // End-to-end through the *real* codebook tables: Huffman lookup + unpack.
244+ #[test]
245+ fn real_codebook1_decodes_codewords() {
246+ // cb1 (dim4, signed, lav1). codeword 0 (1 bit) → index 40 → (0,0,0,0).
247+ let mut r = BitReader::new(&[0x00]);
248+ let mut out = [9i32; 4];
249+ decode_tuple(&CODEBOOKS[1], spectral_book(1), &mut r, &mut out).unwrap();
250+ assert_eq!(out, [0, 0, 0, 0]);
251+
252+ // codeword 0x011 (5 bits, 10001) → index 13 → digits (0,1,1,1) → (-1,0,0,0).
253+ let mut r = BitReader::new(&[0x88]); // 1000_1000
254+ let mut out = [9i32; 4];
255+ decode_tuple(&CODEBOOKS[1], spectral_book(1), &mut r, &mut out).unwrap();
256+ assert_eq!(out, [-1, 0, 0, 0]);
257+ }
258+}
vendor/rusty_aac/src/decode.rsadded+871 -0
@@ -0,0 +1,871 @@
1+//! AAC-LC decode assembly: `raw_data_block` → individual channels → spectral
2+//! reconstruction → filterbank → PCM (ISO 14496-3 §4.4 / §4.6).
3+//!
4+//! Supports long (`ONLY_LONG`), transition (`LONG_START`/`LONG_STOP`) and short
5+//! (`EIGHT_SHORT`) windows with grouped scalefactors/sections, regular Huffman
6+//! codebooks, pulse data and M/S stereo, synthesised via the verified IMDCT +
7+//! windowed overlap-add (2048 for long, 8×256 for short). Output is normalised
8+//! to float [-1, 1] and is bit-exact against FFmpeg on real AAC-LC files.
9+//!
10+//! **Tool coverage.** TNS is parsed *and applied* (`parse_tns` → `apply_tns`, on
11+//! both the SCE and CPE paths); PNS (`NOISE_HCB`) bands are filled with
12+//! energy-scaled noise; intensity stereo is applied via `apply_is`, including
13+//! the M/S sign flip. Only `gain_control_data` is rejected as unsupported. This
14+//! matters to the encoder campaign: the encoder-side arms for TNS, PNS and
15+//! intensity stereo (see `docs/codec-aac-great-gate.md`) can all be gated on
16+//! round-trip through this decoder, with no decode work needed first.
17+
18+use crate::bits::BitReader;
19+use crate::codebook::{decode_tuple, CODEBOOKS, INTENSITY_HCB2, NOISE_HCB, ZERO_HCB};
20+use crate::dsp;
21+use crate::ics::{parse_ics_info, IcsInfo, WindowSequence};
22+use crate::swb::swb_offsets;
23+use crate::tables::{spectral_book, SCALEFACTOR_BOOK};
24+use crate::{DecodedAudio, Error, Result, SAMPLE_RATES};
25+
26+const FRAME_LEN: usize = 1024;
27+const LONG_N: usize = 2048;
28+const SHORT_N: usize = 256;
29+const SHORT_HALF: usize = 128;
30+/// The ISO reconstruction is on a ~16-bit scale; normalise to float [-1, 1]
31+/// (verified bit-exact vs FFmpeg).
32+const OUTPUT_NORM: f32 = 1.0 / 32768.0;
33+
34+// raw_data_block element identifiers (id_syn_ele).
35+const ID_SCE: u32 = 0;
36+const ID_CPE: u32 = 1;
37+const ID_CCE: u32 = 2;
38+const ID_LFE: u32 = 3;
39+const ID_DSE: u32 = 4;
40+const ID_PCE: u32 = 5;
41+const ID_FIL: u32 = 6;
42+const ID_END: u32 = 7;
43+
44+/// Stateful AAC-LC decoder: holds per-channel overlap memory and the windows.
45+pub struct Decoder {
46+ sample_rate: u32,
47+ fs_index: u8,
48+ /// Per-channel overlap-add memory (second half of the previous frame).
49+ overlap: Vec<[f32; FRAME_LEN]>,
50+ /// Per-channel previous window shape (false = sine, true = KBD).
51+ prev_kbd: Vec<bool>,
52+ /// Set when a fill_element carried SBR payload (implicit HE-AAC signalling).
53+ saw_sbr: bool,
54+ /// Per-channel previous window sequence.
55+ prev_seq: Vec<WindowSequence>,
56+ sine: Vec<f32>,
57+ kbd: Vec<f32>,
58+ sine_s: Vec<f32>,
59+ kbd_s: Vec<f32>,
60+ /// Deterministic PRNG state for PNS noise fill.
61+ rng: u32,
62+}
63+
64+impl Decoder {
65+ pub fn new(sample_rate: u32) -> Decoder {
66+ Decoder {
67+ sample_rate,
68+ fs_index: fs_index_for(sample_rate),
69+ overlap: Vec::new(),
70+ prev_kbd: Vec::new(),
71+ saw_sbr: false,
72+ prev_seq: Vec::new(),
73+ sine: dsp::sine_window(LONG_N),
74+ kbd: dsp::kbd_window(LONG_N, 4.0),
75+ sine_s: dsp::sine_window(SHORT_N),
76+ kbd_s: dsp::kbd_window(SHORT_N, 6.0),
77+ rng: 0x1234_5678,
78+ }
79+ }
80+
81+ /// True once a `fill_element` carrying SBR payload has been seen — implicit
82+ /// HE-AAC signalling. The core still decodes; the high band does not exist.
83+ pub fn saw_sbr(&self) -> bool {
84+ self.saw_sbr
85+ }
86+
87+ /// Decode one raw access unit into interleaved-`f32` PCM.
88+ pub fn decode(&mut self, au: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
89+ let mut r = BitReader::new(au);
90+ let mut outputs: Vec<Vec<f32>> = Vec::new();
91+ let mut ch = 0usize;
92+
93+ loop {
94+ if r.bits_left() < 3 {
95+ break;
96+ }
97+ match r.read_bits(3)? {
98+ ID_SCE | ID_LFE => {
99+ let _tag = r.read_bits(4)?;
100+ let mut c = decode_channel(&mut r, self.fs_index, None, &mut self.rng)?;
101+ apply_tns(&mut c.spec, &c.tns, &c.info, self.fs_index);
102+ outputs.push(self.synthesize(ch, &c.info, &c.spec));
103+ ch += 1;
104+ }
105+ ID_CPE => {
106+ let _tag = r.read_bits(4)?;
107+ let common = r.read_bool()?;
108+ let (info, ms_used) = if common {
109+ let info = parse_ics_info(&mut r, self.fs_index)?;
110+ let ms = read_ms_used(&mut r, &info)?;
111+ (Some(info), ms)
112+ } else {
113+ (None, Vec::new())
114+ };
115+ let info_ref = info.as_ref();
116+ let mut c0 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?;
117+ let mut c1 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?;
118+ let fs = self.fs_index;
119+ // M/S and intensity stereo require a shared window/grouping.
120+ if common {
121+ apply_ms(&c0.info, &ms_used, fs, &c1.cb, &mut c0.spec, &mut c1.spec);
122+ apply_is(
123+ &c0.info,
124+ &ms_used,
125+ fs,
126+ &c1.cb,
127+ &c1.sf,
128+ &c0.spec,
129+ &mut c1.spec,
130+ );
131+ }
132+ apply_tns(&mut c0.spec, &c0.tns, &c0.info, fs);
133+ apply_tns(&mut c1.spec, &c1.tns, &c1.info, fs);
134+ outputs.push(self.synthesize(ch, &c0.info, &c0.spec));
135+ outputs.push(self.synthesize(ch + 1, &c1.info, &c1.spec));
136+ ch += 2;
137+ }
138+ ID_FIL => {
139+ let mut count = r.read_bits(4)? as usize;
140+ if count == 15 {
141+ // count = 15 + next8 - 1; group as (count + next8) - 1 so a
142+ // zero escape byte can't underflow usize (`0usize - 1` panics).
143+ count = count + r.read_bits(8)? as usize - 1;
144+ }
145+ // Peek the 4-bit extension_type before skipping: SBR payload
146+ // here is how *implicit* HE-AAC signalling works, where the
147+ // config says nothing but the fill elements carry SBR anyway
148+ // (a shape MPEG-TS broadcast really produces). Recording it
149+ // lets the caller learn the output rate is doubled instead of
150+ // being handed half-speed audio.
151+ if count > 0 {
152+ let ext = r.read_bits(4)?;
153+ if ext == 13 || ext == 14 {
154+ self.saw_sbr = true;
155+ }
156+ r.skip(count * 8 - 4)?;
157+ }
158+ }
159+ ID_DSE => {
160+ let _tag = r.read_bits(4)?;
161+ let align = r.read_bool()?;
162+ let mut count = r.read_bits(8)? as usize;
163+ if count == 255 {
164+ count += r.read_bits(8)? as usize;
165+ }
166+ if align {
167+ r.byte_align();
168+ }
169+ r.skip(count * 8)?;
170+ }
171+ ID_END => break,
172+ ID_CCE | ID_PCE => {
173+ return Err(Error::unsupported(
174+ "aac: coupling / program-config elements not supported",
175+ ));
176+ }
177+ _ => unreachable!(),
178+ }
179+ }
180+
181+ if outputs.is_empty() {
182+ return Err(Error::invalid("aac: no channel elements in frame"));
183+ }
184+ Ok(interleave(outputs, self.sample_rate, pts))
185+ }
186+
187+ /// Build the 2048-sample analysis window for a long/transition block: left
188+ /// half follows the previous block's shape, right half the current's.
189+ fn long_window(&self, seq: WindowSequence, prev_kbd: bool, cur_kbd: bool) -> Vec<f32> {
190+ let long_prev = if prev_kbd { &self.kbd } else { &self.sine };
191+ let long_cur = if cur_kbd { &self.kbd } else { &self.sine };
192+ let short_prev = if prev_kbd { &self.kbd_s } else { &self.sine_s };
193+ let short_cur = if cur_kbd { &self.kbd_s } else { &self.sine_s };
194+ let mut w = vec![0f32; LONG_N];
195+
196+ if seq == WindowSequence::LongStop {
197+ for n in 0..128 {
198+ w[448 + n] = short_prev[n];
199+ }
200+ for s in w.iter_mut().take(FRAME_LEN).skip(576) {
201+ *s = 1.0;
202+ }
203+ } else {
204+ w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]);
205+ }
206+
207+ if seq == WindowSequence::LongStart {
208+ for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
209+ *s = 1.0;
210+ }
211+ for n in 0..128 {
212+ w[FRAME_LEN + 448 + n] = short_cur[128 + n];
213+ }
214+ } else {
215+ w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]);
216+ }
217+ w
218+ }
219+
220+ /// Synthesise eight 256-IMDCT short windows into a normalised 2048 frame.
221+ fn short_frame(&self, spec: &[f32; FRAME_LEN], cur_kbd: bool) -> Vec<f32> {
222+ let sw = if cur_kbd { &self.kbd_s } else { &self.sine_s };
223+ let mut frame = vec![0f32; LONG_N];
224+ for w in 0..8 {
225+ let time = dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]); // 256
226+ let off = 448 + w * SHORT_HALF;
227+ for n in 0..SHORT_N {
228+ frame[off + n] += time[n] * sw[n] * OUTPUT_NORM;
229+ }
230+ }
231+ frame
232+ }
233+
234+ /// IMDCT + window + overlap-add for one channel's spectrum → 1024 samples.
235+ fn synthesize(&mut self, ch: usize, info: &IcsInfo, spec: &[f32; FRAME_LEN]) -> Vec<f32> {
236+ while self.overlap.len() <= ch {
237+ self.overlap.push([0.0; FRAME_LEN]);
238+ self.prev_kbd.push(false);
239+ self.prev_seq.push(WindowSequence::OnlyLong);
240+ }
241+
242+ let frame = if info.window_sequence == WindowSequence::EightShort {
243+ self.short_frame(spec, info.window_shape_kbd)
244+ } else {
245+ let time = dsp::imdct(spec); // 2048
246+ let win = self.long_window(
247+ info.window_sequence,
248+ self.prev_kbd[ch],
249+ info.window_shape_kbd,
250+ );
251+ (0..LONG_N)
252+ .map(|n| time[n] * win[n] * OUTPUT_NORM)
253+ .collect()
254+ };
255+
256+ let mut out = vec![0.0f32; FRAME_LEN];
257+ for n in 0..FRAME_LEN {
258+ out[n] = frame[n] + self.overlap[ch][n];
259+ }
260+ for n in 0..FRAME_LEN {
261+ self.overlap[ch][n] = frame[FRAME_LEN + n];
262+ }
263+ self.prev_kbd[ch] = info.window_shape_kbd;
264+ self.prev_seq[ch] = info.window_sequence;
265+ out
266+ }
267+}
268+
269+/// Decode one `individual_channel_stream` to a dequantized spectrum. For short
270+/// blocks the layout is window-major (eight 128-bin windows).
271+struct Channel {
272+ info: IcsInfo,
273+ spec: [f32; FRAME_LEN],
274+ cb: Vec<Vec<u8>>,
275+ sf: Vec<Vec<i32>>,
276+ tns: Tns,
277+}
278+
279+fn decode_channel(
280+ r: &mut BitReader,
281+ fs_index: u8,
282+ common_info: Option<&IcsInfo>,
283+ rng: &mut u32,
284+) -> Result<Channel> {
285+ let global_gain = r.read_bits(8)? as i32;
286+ let info = match common_info {
287+ Some(i) => i.clone(),
288+ None => parse_ics_info(r, fs_index)?,
289+ };
290+
291+ let is_short = info.window_sequence == WindowSequence::EightShort;
292+ let swb = swb_offsets(!is_short, fs_index);
293+ let max_sfb = info.max_sfb as usize;
294+ if max_sfb + 1 > swb.len() {
295+ return Err(Error::invalid("aac: max_sfb out of range"));
296+ }
297+ let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
298+
299+ let sfb_cb = read_sections(r, info.num_window_groups, max_sfb, is_short)?;
300+ let sf = read_scalefactors(r, &sfb_cb, global_gain)?;
301+
302+ let pulse = if r.read_bool()? {
303+ Some(read_pulse(r)?)
304+ } else {
305+ None
306+ };
307+ let tns = if r.read_bool()? {
308+ parse_tns(r, &info)?
309+ } else {
310+ Tns::default()
311+ };
312+ if r.read_bool()? {
313+ return Err(Error::unsupported("aac: gain control not supported"));
314+ }
315+
316+ let mut quant = [0i32; FRAME_LEN];
317+ read_spectrum(r, &sfb_cb, &info, swb, window_len, &mut quant)?;
318+ if let (Some(p), false) = (&pulse, is_short) {
319+ apply_pulse(&mut quant, p, swb);
320+ }
321+
322+ // Inverse quantization, per group/window with the group's band scalefactor.
323+ // PNS (NOISE_HCB) bands are filled with energy-scaled random noise instead.
324+ let mut spec = [0f32; FRAME_LEN];
325+ let mut wbase = 0usize;
326+ for (g, group) in sfb_cb.iter().enumerate() {
327+ for (sfb, &cb) in group.iter().enumerate() {
328+ if cb == ZERO_HCB {
329+ continue;
330+ }
331+ if sfb + 1 >= swb.len() {
332+ break; // malformed: more coded bands than the swb offset table holds
333+ }
334+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
335+ for w in 0..info.window_group_length[g] as usize {
336+ let base = (wbase + w) * window_len;
337+ if cb == NOISE_HCB {
338+ fill_noise(rng, &mut spec, base + s, base + e, sf[g][sfb]);
339+ } else {
340+ let gain = dsp::sf_gain(sf[g][sfb]);
341+ for i in s..e {
342+ spec[base + i] = dsp::dequant(quant[base + i]) * gain;
343+ }
344+ }
345+ }
346+ }
347+ wbase += info.window_group_length[g] as usize;
348+ }
349+ Ok(Channel {
350+ info,
351+ spec,
352+ cb: sfb_cb,
353+ sf,
354+ tns,
355+ })
356+}
357+
358+/// section_data: a codebook number per scalefactor band, per group.
359+fn read_sections(
360+ r: &mut BitReader,
361+ groups: usize,
362+ max_sfb: usize,
363+ is_short: bool,
364+) -> Result<Vec<Vec<u8>>> {
365+ let bits = if is_short { 3 } else { 5 };
366+ let esc = (1u32 << bits) - 1;
367+ let mut out = Vec::with_capacity(groups);
368+ for _ in 0..groups {
369+ let mut cbs = vec![0u8; max_sfb];
370+ let mut k = 0usize;
371+ while k < max_sfb {
372+ let cb = r.read_bits(4)? as u8;
373+ let mut len = 0usize;
374+ loop {
375+ let incr = r.read_bits(bits)? as usize;
376+ len += incr;
377+ if incr as u32 != esc {
378+ break;
379+ }
380+ }
381+ if k + len > max_sfb {
382+ return Err(Error::invalid("aac: section overruns max_sfb"));
383+ }
384+ for c in cbs.iter_mut().skip(k).take(len) {
385+ *c = cb;
386+ }
387+ k += len;
388+ }
389+ out.push(cbs);
390+ }
391+ Ok(out)
392+}
393+
394+/// scale_factor_data: differentially-coded scalefactors (regular codebooks).
395+fn read_scalefactors(
396+ r: &mut BitReader,
397+ sfb_cb: &[Vec<u8>],
398+ global_gain: i32,
399+) -> Result<Vec<Vec<i32>>> {
400+ let mut acc = global_gain;
401+ let mut noise = global_gain - 90; // PNS noise-energy accumulator
402+ let mut noise_pcm = true;
403+ let mut is_pos = 0i32; // intensity-stereo position accumulator
404+ let mut out = Vec::with_capacity(sfb_cb.len());
405+ for group in sfb_cb {
406+ let mut sf = vec![0i32; group.len()];
407+ for (sfb, &cb) in group.iter().enumerate() {
408+ if cb == ZERO_HCB {
409+ continue;
410+ } else if cb >= INTENSITY_HCB2 {
411+ is_pos += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
412+ sf[sfb] = is_pos;
413+ } else if cb == NOISE_HCB {
414+ // PNS: first noise energy is a 9-bit PCM delta, rest are Huffman.
415+ if noise_pcm {
416+ noise_pcm = false;
417+ noise += r.read_bits(9)? as i32 - 256;
418+ } else {
419+ noise += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
420+ }
421+ sf[sfb] = noise;
422+ } else {
423+ acc += SCALEFACTOR_BOOK.decode(r)? as i32 - 60;
424+ sf[sfb] = acc;
425+ }
426+ }
427+ out.push(sf);
428+ }
429+ Ok(out)
430+}
431+
432+/// spectral_data: Huffman-decode quantized coefficients per group/band/window.
433+fn read_spectrum(
434+ r: &mut BitReader,
435+ sfb_cb: &[Vec<u8>],
436+ info: &IcsInfo,
437+ swb: &[u16],
438+ window_len: usize,
439+ quant: &mut [i32; FRAME_LEN],
440+) -> Result<()> {
441+ let mut wbase = 0usize;
442+ for (g, group) in sfb_cb.iter().enumerate() {
443+ for (sfb, &cb) in group.iter().enumerate() {
444+ // ZERO, NOISE (PNS) and intensity bands carry no spectral data.
445+ if cb == ZERO_HCB || cb == NOISE_HCB || cb >= INTENSITY_HCB2 {
446+ continue;
447+ }
448+ // Skip books that carry no spectral data or are out of range: the
449+ // filter above misses INTENSITY_HCB (14) and reserved (12), which
450+ // would index CODEBOOKS out of bounds on malformed (or intensity)
451+ // input. `.get` skips them (intensity is applied later in apply_is).
452+ let Some(meta) = CODEBOOKS.get(cb as usize) else {
453+ continue;
454+ };
455+ let book = spectral_book(cb);
456+ let dim = meta.dim as usize;
457+ if sfb + 1 >= swb.len() {
458+ break; // malformed: more coded bands than the swb offset table holds
459+ }
460+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
461+ for w in 0..info.window_group_length[g] as usize {
462+ let base = (wbase + w) * window_len;
463+ let mut i = s;
464+ let mut tuple = [0i32; 4];
465+ while i + dim <= e {
466+ decode_tuple(meta, book, r, &mut tuple)?;
467+ quant[base + i..base + i + dim].copy_from_slice(&tuple[..dim]);
468+ i += dim;
469+ }
470+ }
471+ }
472+ wbase += info.window_group_length[g] as usize;
473+ }
474+ Ok(())
475+}
476+
477+/// xorshift32 → uniform f32 in [-1, 1). Decoder-local; PNS noise is random by
478+/// design, so it is energy-matched (not sample-exact) across decoders.
479+fn next_rand(s: &mut u32) -> f32 {
480+ *s ^= *s << 13;
481+ *s ^= *s >> 17;
482+ *s ^= *s << 5;
483+ (*s as f32 / u32::MAX as f32) * 2.0 - 1.0
484+}
485+
486+/// Fill `spec[start..end]` with random noise whose spectral energy matches the
487+/// transmitted `noise_energy` (ISO 14496-3 §4.6.13): unit-energy random vector
488+/// scaled so band energy = 2^(noise_energy/2).
489+fn fill_noise(rng: &mut u32, spec: &mut [f32], start: usize, end: usize, noise_energy: i32) {
490+ let mut energy = 0f64;
491+ for i in start..end {
492+ let v = next_rand(rng);
493+ spec[i] = v;
494+ energy += (v as f64) * (v as f64);
495+ }
496+ if energy <= 0.0 {
497+ return;
498+ }
499+ let scale = (2f64.powf(0.25 * noise_energy as f64) / energy.sqrt()) as f32;
500+ for v in spec[start..end].iter_mut() {
501+ *v *= scale;
502+ }
503+}
504+
505+struct Pulse {
506+ start_sfb: usize,
507+ offsets: Vec<u32>,
508+ amps: Vec<u32>,
509+}
510+
511+fn read_pulse(r: &mut BitReader) -> Result<Pulse> {
512+ let n = r.read_bits(2)? as usize; // number_pulse - 1
513+ let start_sfb = r.read_bits(6)? as usize;
514+ let mut offsets = Vec::with_capacity(n + 1);
515+ let mut amps = Vec::with_capacity(n + 1);
516+ for _ in 0..=n {
517+ offsets.push(r.read_bits(5)?);
518+ amps.push(r.read_bits(4)?);
519+ }
520+ Ok(Pulse {
521+ start_sfb,
522+ offsets,
523+ amps,
524+ })
525+}
526+
527+fn apply_pulse(quant: &mut [i32; FRAME_LEN], p: &Pulse, swb: &[u16]) {
528+ let mut k = *swb.get(p.start_sfb).unwrap_or(&0) as usize;
529+ for (off, amp) in p.offsets.iter().zip(&p.amps) {
530+ k += *off as usize;
531+ if k < FRAME_LEN {
532+ if quant[k] > 0 {
533+ quant[k] += *amp as i32;
534+ } else {
535+ quant[k] -= *amp as i32;
536+ }
537+ }
538+ }
539+}
540+
541+/// One TNS noise-shaping filter (a span of bands + its LPC synthesis filter).
542+struct TnsFilter {
543+ length: usize, // span in scalefactor bands (from the top down)
544+ order: usize,
545+ direction: bool, // true = downward (high→low) filtering
546+ lpc: Vec<f32>, // lpc[0]=1, lpc[1..=order]
547+}
548+
549+/// TNS data for a channel: filters per window.
550+#[derive(Default)]
551+struct Tns {
552+ windows: Vec<Vec<TnsFilter>>,
553+}
554+
555+/// Max TNS-affected band per sampling-frequency index (ISO Table 4.A.45/46).
556+pub(crate) const TNS_MAX_LONG: [u8; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39];
557+pub(crate) const TNS_MAX_SHORT: [u8; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14];
558+
559+/// Parse TNS, dequantizing PARCOR coefficients and converting them to LPC.
560+fn parse_tns(r: &mut BitReader, info: &IcsInfo) -> Result<Tns> {
561+ use std::f32::consts::PI;
562+ let short = info.window_sequence == WindowSequence::EightShort;
563+ let (nf_bits, len_bits, ord_bits) = if short { (1, 4, 3) } else { (2, 6, 5) };
564+ let mut windows = Vec::with_capacity(info.num_windows);
565+ for _ in 0..info.num_windows {
566+ let mut filters = Vec::new();
567+ let n_filt = r.read_bits(nf_bits)?;
568+ let coef_res = if n_filt > 0 { r.read_bits(1)? } else { 0 };
569+ for _ in 0..n_filt {
570+ let length = r.read_bits(len_bits)? as usize;
571+ let order = r.read_bits(ord_bits)? as usize;
572+ let (mut direction, mut lpc) = (false, Vec::new());
573+ if order > 0 {
574+ direction = r.read_bool()?;
575+ let coef_compress = r.read_bits(1)?;
576+ let res_bits = 3 + coef_res; // 3 or 4
577+ let coef_bits = res_bits - coef_compress;
578+ let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
579+ let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
580+ let mut parcor = vec![0f32; order];
581+ for p in parcor.iter_mut() {
582+ let raw = r.read_bits(coef_bits)? as i32;
583+ let c = if raw & (1 << (coef_bits - 1)) != 0 {
584+ raw - (1 << coef_bits)
585+ } else {
586+ raw
587+ };
588+ let t = if c >= 0 {
589+ c as f32 / iqfac
590+ } else {
591+ c as f32 / iqfac_m
592+ };
593+ *p = t.sin();
594+ }
595+ lpc = parcor_to_lpc(&parcor);
596+ }
597+ filters.push(TnsFilter {
598+ length,
599+ order,
600+ direction,
601+ lpc,
602+ });
603+ }
604+ windows.push(filters);
605+ }
606+ Ok(Tns { windows })
607+}
608+
609+/// PARCOR (reflection) → LPC coefficients via the step-up recursion.
610+fn parcor_to_lpc(parcor: &[f32]) -> Vec<f32> {
611+ let order = parcor.len();
612+ let mut lpc = vec![0f32; order + 1];
613+ lpc[0] = 1.0;
614+ for m in 1..=order {
615+ let mut tmp = lpc.clone();
616+ for i in 1..m {
617+ tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
618+ }
619+ lpc[..m].copy_from_slice(&tmp[..m]);
620+ lpc[m] = parcor[m - 1];
621+ }
622+ lpc
623+}
624+
625+/// Apply TNS: an all-pole (synthesis) filter over each filter's band span,
626+/// per window, in the coded direction (ISO 14496-3 §4.6.9.3).
627+fn apply_tns(spec: &mut [f32; FRAME_LEN], tns: &Tns, info: &IcsInfo, fs_index: u8) {
628+ if tns.windows.iter().all(|w| w.is_empty()) {
629+ return;
630+ }
631+ let short = info.window_sequence == WindowSequence::EightShort;
632+ let swb = swb_offsets(!short, fs_index);
633+ let window_len = if short { SHORT_HALF } else { FRAME_LEN };
634+ let tns_max = if short {
635+ TNS_MAX_SHORT[fs_index as usize]
636+ } else {
637+ TNS_MAX_LONG[fs_index as usize]
638+ } as usize;
639+ let mmm = tns_max.min(info.max_sfb as usize);
640+
641+ for (w, filters) in tns.windows.iter().enumerate() {
642+ let mut bottom = info.num_swb;
643+ for f in filters {
644+ let top = bottom;
645+ bottom = top.saturating_sub(f.length);
646+ if f.order == 0 {
647+ continue;
648+ }
649+ let start = swb[bottom.min(mmm)] as usize;
650+ let end = swb[top.min(mmm)] as usize;
651+ if end <= start {
652+ continue;
653+ }
654+ let size = end - start;
655+ let base = w * window_len;
656+ let (mut idx, inc): (isize, isize) = if f.direction {
657+ ((base + end - 1) as isize, -1)
658+ } else {
659+ ((base + start) as isize, 1)
660+ };
661+ let mut state = vec![0f32; f.order];
662+ for _ in 0..size {
663+ let p = idx as usize;
664+ let mut y = spec[p];
665+ for j in 0..f.order {
666+ y -= state[j] * f.lpc[j + 1];
667+ }
668+ for j in (1..f.order).rev() {
669+ state[j] = state[j - 1];
670+ }
671+ state[0] = y;
672+ spec[p] = y;
673+ idx += inc;
674+ }
675+ }
676+ }
677+}
678+
679+/// M/S stereo flags (`num_window_groups × max_sfb`) for a common-window CPE.
680+fn read_ms_used(r: &mut BitReader, info: &IcsInfo) -> Result<Vec<bool>> {
681+ let n = info.num_window_groups * info.max_sfb as usize;
682+ match r.read_bits(2)? {
683+ 0 => Ok(vec![false; n]),
684+ 2 => Ok(vec![true; n]),
685+ 1 => {
686+ let mut v = vec![false; n];
687+ for slot in v.iter_mut() {
688+ *slot = r.read_bool()?;
689+ }
690+ Ok(v)
691+ }
692+ _ => Err(Error::unsupported("aac: reserved ms_mask_present")),
693+ }
694+}
695+
696+/// Reconstruct L/R from Mid/Side on the flagged bands (group/window aware).
697+/// Intensity-coded bands of the right channel are excluded (handled by IS).
698+fn apply_ms(
699+ info: &IcsInfo,
700+ ms_used: &[bool],
701+ fs_index: u8,
702+ cb1: &[Vec<u8>],
703+ s0: &mut [f32; FRAME_LEN],
704+ s1: &mut [f32; FRAME_LEN],
705+) {
706+ if ms_used.is_empty() {
707+ return;
708+ }
709+ let is_short = info.window_sequence == WindowSequence::EightShort;
710+ let swb = swb_offsets(!is_short, fs_index);
711+ let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
712+ let max_sfb = info.max_sfb as usize;
713+ let mut wbase = 0usize;
714+ for g in 0..info.num_window_groups {
715+ for sfb in 0..max_sfb {
716+ if ms_used[g * max_sfb + sfb] && cb1[g][sfb] < INTENSITY_HCB2 {
717+ if sfb + 1 >= swb.len() {
718+ break; // malformed: more coded bands than the swb offset table holds
719+ }
720+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
721+ for w in 0..info.window_group_length[g] as usize {
722+ let base = (wbase + w) * window_len;
723+ for i in s..e {
724+ let (mid, side) = (s0[base + i], s1[base + i]);
725+ s0[base + i] = mid + side;
726+ s1[base + i] = mid - side;
727+ }
728+ }
729+ }
730+ }
731+ wbase += info.window_group_length[g] as usize;
732+ }
733+}
734+
735+/// Intensity stereo (ISO 14496-3 §4.6.8.2.3): the right channel's IS bands are
736+/// `± 2^(-is_position/4)` times the left channel. Sign is negative for
737+/// INTENSITY_HCB2, and flipped again when the band is M/S-flagged.
738+fn apply_is(
739+ info: &IcsInfo,
740+ ms_used: &[bool],
741+ fs_index: u8,
742+ cb1: &[Vec<u8>],
743+ sf1: &[Vec<i32>],
744+ s0: &[f32; FRAME_LEN],
745+ s1: &mut [f32; FRAME_LEN],
746+) {
747+ let is_short = info.window_sequence == WindowSequence::EightShort;
748+ let swb = swb_offsets(!is_short, fs_index);
749+ let window_len = if is_short { SHORT_HALF } else { FRAME_LEN };
750+ let max_sfb = info.max_sfb as usize;
751+ let mut wbase = 0usize;
752+ for g in 0..info.num_window_groups {
753+ for sfb in 0..max_sfb {
754+ let cb = cb1[g][sfb];
755+ if cb >= INTENSITY_HCB2 {
756+ let mut scale = 0.5f32.powf(0.25 * sf1[g][sfb] as f32);
757+ if cb == INTENSITY_HCB2 {
758+ scale = -scale; // out of phase
759+ }
760+ if !ms_used.is_empty() && ms_used[g * max_sfb + sfb] {
761+ scale = -scale; // M/S flips intensity sign
762+ }
763+ if sfb + 1 >= swb.len() {
764+ break; // malformed: more coded bands than the swb offset table holds
765+ }
766+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
767+ for w in 0..info.window_group_length[g] as usize {
768+ let base = (wbase + w) * window_len;
769+ for i in s..e {
770+ s1[base + i] = scale * s0[base + i];
771+ }
772+ }
773+ }
774+ }
775+ wbase += info.window_group_length[g] as usize;
776+ }
777+}
778+
779+/// Interleave decoded channels, **reordering AAC element order into the standard
780+/// interleave order** the rest of the workspace uses (FL, FR, FC, LFE, BL, BR).
781+///
782+/// AAC carries 5.1 as `C, L, R, Ls, Rs, LFE`; every WAV writer and filter here
783+/// expects `L, R, C, LFE, Ls, Rs`. Emitting element order straight out would put
784+/// the centre channel in the left speaker. Mono and stereo are identity, so this
785+/// changes nothing for the overwhelmingly common cases.
786+fn interleave(outputs: Vec<Vec<f32>>, sample_rate: u32, pts: Option<i64>) -> DecodedAudio {
787+ let nch = outputs.len();
788+ let order = crate::encode::aac_to_interleave_order(nch);
789+ let mut samples = Vec::with_capacity(FRAME_LEN * nch);
790+ for n in 0..FRAME_LEN {
791+ match &order {
792+ Some(map) => {
793+ for &src in map {
794+ samples.push(outputs[src][n]);
795+ }
796+ }
797+ // No defined layout (a PCE stream, once supported): pass elements
798+ // through in stream order rather than guessing.
799+ None => {
800+ for ch in &outputs {
801+ samples.push(ch[n]);
802+ }
803+ }
804+ }
805+ }
806+ DecodedAudio {
807+ sample_rate,
808+ channels: nch as u16,
809+ samples,
810+ pts,
811+ }
812+}
813+
814+fn fs_index_for(rate: u32) -> u8 {
815+ SAMPLE_RATES
816+ .iter()
817+ .position(|&r| r == rate)
818+ .map(|i| i as u8)
819+ .unwrap_or(3) // default 48 kHz layout
820+}
821+
822+#[cfg(test)]
823+mod tests {
824+ use super::*;
825+
826+ #[test]
827+ fn section_and_scalefactors_parse() {
828+ // One group, one cb=1 section of length 2 (long, 5-bit length).
829+ // bits: cb(0001) len_incr(00010) → 0001_0001 0... = 0x11 0x00
830+ let mut r = BitReader::new(&[0x11, 0x00]);
831+ let cb = read_sections(&mut r, 1, 2, false).unwrap();
832+ assert_eq!(cb, vec![vec![1, 1]]);
833+ }
834+
835+ #[test]
836+ fn scalefactors_accumulate_from_global_gain() {
837+ // Two regular bands; SF deltas both index 60 ("0" = delta 0) → both
838+ // equal global_gain. Two "0" bits → 0x00.
839+ let sfb_cb = vec![vec![1u8, 1u8]];
840+ let mut r = BitReader::new(&[0x00]);
841+ let sf = read_scalefactors(&mut r, &sfb_cb, 100).unwrap();
842+ assert_eq!(sf, vec![vec![100, 100]]);
843+ }
844+
845+ /// End-to-end: a hand-built ONLY_LONG SCE frame, one cb1 codeword giving a
846+ /// single non-zero coefficient. Decoded PCM must equal the IMDCT of that
847+ /// spectrum, windowed and normalised — using the verified DSP as oracle.
848+ #[test]
849+ fn hand_built_frame_matches_independent_imdct() {
850+ let au = [0x00, 0xC8, 0x00, 0x84, 0x21, 0x1E];
851+ let mut dec = Decoder::new(48_000);
852+ let af = dec.decode(&au, Some(0)).unwrap();
853+ assert_eq!(af.channels, 1);
854+ assert_eq!(af.frames(), FRAME_LEN);
855+ let got: Vec<f32> = af.samples;
856+
857+ let mut spec = [0f32; FRAME_LEN];
858+ spec[0] = -1.0;
859+ let time = dsp::imdct(&spec);
860+ let win = dsp::sine_window(LONG_N);
861+ for n in 0..FRAME_LEN {
862+ let expected = time[n] * win[n] / 32768.0;
863+ assert!(
864+ (got[n] - expected).abs() < 1e-4,
865+ "sample {n}: got {} want {}",
866+ got[n],
867+ expected
868+ );
869+ }
870+ }
871+}
vendor/rusty_aac/src/dsp.rsadded+423 -0
@@ -0,0 +1,423 @@
1+//! AAC numerical core: inverse quantization and the IMDCT synthesis filterbank
2+//! (windows + overlap-add). These must match ISO 14496-3 exactly — they are the
3+//! parts where any deviation produces audibly wrong / incompatible output, so
4+//! they're written straight from the spec and checked by the MDCT↔IMDCT
5+//! perfect-reconstruction (TDAC) property.
6+//!
7+//! The IMDCT here is a direct O(N²) evaluation — correct and clear; it can be
8+//! swapped for an FFT-based fast path later without changing results.
9+
10+// These primitives are exercised by the tests now and wired into the decode
11+// path in the spectral/synthesis stages; allow until then.
12+#![allow(dead_code)]
13+
14+use std::f64::consts::PI;
15+use std::sync::OnceLock;
16+
17+/// Inverse quantization of a spectral coefficient (ISO 14496-3 §10.3):
18+/// `x = sign(q) · |q|^(4/3)`. The scalefactor gain is applied separately.
19+pub fn dequant(q: i32) -> f32 {
20+ let m = (q.unsigned_abs() as f64).powf(4.0 / 3.0);
21+ (q.signum() as f64 * m) as f32
22+}
23+
24+/// Scalefactor gain `2^(0.25·(sf − 100))`, the per-band multiplier applied to
25+/// dequantized coefficients.
26+pub fn sf_gain(sf: i32) -> f32 {
27+ 2f64.powf(0.25 * (sf as f64 - 100.0)) as f32
28+}
29+
30+/// IMDCT (ISO 14496-3 §4.6.11.2): `N/2` spectral coefficients → `N` time
31+/// samples. `out[i] = (2/N)·Σ_k spec[k]·cos((2π/N)(i+n0)(k+½))`, `n0=(N/2+1)/2`.
32+pub fn imdct(spec: &[f32]) -> Vec<f32> {
33+ let half = spec.len();
34+ let n = half * 2;
35+ if n == 0 {
36+ return Vec::new();
37+ }
38+ // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below --
39+ // the same numbers, looked up instead of called for.
40+ if let Some(matrix) = imdct_matrix(n) {
41+ let mut out = vec![0f32; n];
42+ for (i, o) in out.iter_mut().enumerate() {
43+ let row = &matrix[i * half..(i + 1) * half];
44+ let mut acc = 0f32;
45+ for (k, &s) in spec.iter().enumerate() {
46+ acc += s * row[k];
47+ }
48+ *o = acc;
49+ }
50+ return out;
51+ }
52+ let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2
53+ let scale = 2.0 / n as f64;
54+ let w = 2.0 * PI / n as f64;
55+ let mut out = vec![0f32; n];
56+ for (i, o) in out.iter_mut().enumerate() {
57+ let mut acc = 0f64;
58+ let a = w * (i as f64 + n0);
59+ for (k, &s) in spec.iter().enumerate() {
60+ acc += s as f64 * (a * (k as f64 + 0.5)).cos();
61+ }
62+ *o = (scale * acc) as f32;
63+ }
64+ out
65+}
66+
67+/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block
68+/// size, built once. The direct transform above spends its whole time in `cos`
69+/// -- ~63 ms for one 1024-coefficient channel, three times slower than real
70+/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the
71+/// long block and 128 kB for the short one, and each output sample becomes a
72+/// dot product a compiler can vectorise.
73+fn imdct_matrix(n: usize) -> Option<&'static [f32]> {
74+ static LONG: OnceLock<Vec<f32>> = OnceLock::new();
75+ static SHORT: OnceLock<Vec<f32>> = OnceLock::new();
76+ fn build(n: usize) -> Vec<f32> {
77+ let half = n / 2;
78+ let n0 = (n / 2 + 1) as f64 / 2.0;
79+ let scale = 2.0 / n as f64;
80+ let w = 2.0 * PI / n as f64;
81+ let mut m = vec![0f32; n * half];
82+ for i in 0..n {
83+ let a = w * (i as f64 + n0);
84+ for k in 0..half {
85+ m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32;
86+ }
87+ }
88+ m
89+ }
90+ match n {
91+ 2048 => Some(LONG.get_or_init(|| build(2048))),
92+ 256 => Some(SHORT.get_or_init(|| build(256))),
93+ _ => None,
94+ }
95+}
96+
97+/// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate
98+/// the IMDCT via perfect reconstruction (and useful for an eventual encoder).
99+/// `N` time samples → `N/2` coefficients.
100+///
101+/// The `2.0` factor makes this the exact inverse of the spec's `2/N` IMDCT under
102+/// Princen-Bradley windows, so `imdct(mdct(·))` with overlap-add is identity.
103+pub fn mdct(time: &[f32]) -> Vec<f32> {
104+ let n = time.len();
105+ let half = n / 2;
106+ if n == 0 {
107+ return Vec::new();
108+ }
109+ let n0 = (n / 2 + 1) as f64 / 2.0;
110+ let w = 2.0 * PI / n as f64;
111+ let mut out = vec![0f32; half];
112+ for (k, o) in out.iter_mut().enumerate() {
113+ let mut acc = 0f64;
114+ for (i, &t) in time.iter().enumerate() {
115+ acc += t as f64 * (w * (i as f64 + n0) * (k as f64 + 0.5)).cos();
116+ }
117+ *o = (2.0 * acc) as f32;
118+ }
119+ out
120+}
121+
122+/// In-place radix-2 Cooley–Tukey FFT (forward, `exp(-i2πkn/N)`); `re.len()` must be
123+/// a power of two and equal `im.len()`. Pure in-house `f64` — the fast MDCT's engine.
124+/// Uses precomputed per-stage twiddles (`tw_c`/`tw_s`, flattened over stages) so a
125+/// transform is pure multiply-add — no runtime trig or twiddle recurrence.
126+fn fft(re: &mut [f64], im: &mut [f64], tw_c: &[f64], tw_s: &[f64]) {
127+ let n = re.len();
128+ // Bit-reversal permutation.
129+ let mut j = 0usize;
130+ for i in 1..n {
131+ let mut bit = n >> 1;
132+ while j & bit != 0 {
133+ j ^= bit;
134+ bit >>= 1;
135+ }
136+ j |= bit;
137+ if i < j {
138+ re.swap(i, j);
139+ im.swap(i, j);
140+ }
141+ }
142+ // Butterfly stages, indexing the flattened per-stage twiddle tables.
143+ let mut off = 0usize;
144+ let mut len = 2usize;
145+ while len <= n {
146+ let half = len / 2;
147+ let mut base = 0;
148+ while base < n {
149+ for k in 0..half {
150+ let (a, b) = (base + k, base + k + half);
151+ let (cr, ci) = (tw_c[off + k], tw_s[off + k]);
152+ let tr = cr * re[b] - ci * im[b];
153+ let ti = cr * im[b] + ci * re[b];
154+ re[b] = re[a] - tr;
155+ im[b] = im[a] - ti;
156+ re[a] += tr;
157+ im[a] += ti;
158+ }
159+ base += len;
160+ }
161+ off += half;
162+ len <<= 1;
163+ }
164+}
165+
166+/// Precomputed MDCT twiddles for one block size: pre-rotation, post-rotation, and
167+/// the FFT's per-stage factors — so a transform touches no `cos`/`sin` at runtime.
168+struct MdctTwiddles {
169+ pre_c: Vec<f64>,
170+ pre_s: Vec<f64>,
171+ post_c: Vec<f64>,
172+ post_s: Vec<f64>,
173+ fft_c: Vec<f64>,
174+ fft_s: Vec<f64>,
175+}
176+
177+impl MdctTwiddles {
178+ fn build(n: usize) -> MdctTwiddles {
179+ // N/4-FFT MDCT: fold N→L=N/2, an M=N/4 complex FFT, pre/post rotations
180+ // (derived + verified against the direct oracle — see mdct_fast).
181+ let l = n / 2;
182+ let m = n / 4;
183+ let (mut pre_c, mut pre_s) = (vec![0f64; m], vec![0f64; m]);
184+ for p in 0..m {
185+ let th = PI * (4.0 * p as f64 + 1.0) / (4.0 * l as f64);
186+ pre_c[p] = th.cos();
187+ pre_s[p] = th.sin();
188+ }
189+ let (mut post_c, mut post_s) = (vec![0f64; m], vec![0f64; m]);
190+ for p in 0..m {
191+ let ph = PI * p as f64 / l as f64;
192+ post_c[p] = ph.cos();
193+ post_s[p] = ph.sin();
194+ }
195+ // FFT stage twiddles for the M-point transform (flattened over stages).
196+ let (mut fft_c, mut fft_s) = (Vec::new(), Vec::new());
197+ let mut len = 2usize;
198+ while len <= m {
199+ for k in 0..len / 2 {
200+ let ang = -2.0 * PI * k as f64 / len as f64;
201+ fft_c.push(ang.cos());
202+ fft_s.push(ang.sin());
203+ }
204+ len <<= 1;
205+ }
206+ MdctTwiddles {
207+ pre_c,
208+ pre_s,
209+ post_c,
210+ post_s,
211+ fft_c,
212+ fft_s,
213+ }
214+ }
215+}
216+
217+/// The AAC block sizes (2048 long, 256 short) get cached twiddles; any other size
218+/// (tests) builds a fresh set.
219+fn mdct_twiddles(n: usize) -> Option<&'static MdctTwiddles> {
220+ static LONG: OnceLock<MdctTwiddles> = OnceLock::new();
221+ static SHORT: OnceLock<MdctTwiddles> = OnceLock::new();
222+ match n {
223+ 2048 => Some(LONG.get_or_init(|| MdctTwiddles::build(2048))),
224+ 256 => Some(SHORT.get_or_init(|| MdctTwiddles::build(256))),
225+ _ => None,
226+ }
227+}
228+
229+/// Fast forward MDCT (O(N log N)) — numerically matches the direct [`mdct`] (kept as
230+/// the scalar oracle). The textbook N/4 method: fold the N real inputs to L=N/2 (TDAC),
231+/// pack into M=N/4 complex with a pre-rotation, one **M-point** FFT, then a post-rotation
232+/// unpacks the N/2 coefficients. 4× fewer FFT points than a length-N transform. `N` is a
233+/// power of two (≥4); time samples → `N/2` coeffs.
234+pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
235+ let n = x.len();
236+ if n < 4 {
237+ return mdct(x); // tiny sizes: fall back to the direct oracle
238+ }
239+ let (l, m) = (n / 2, n / 4);
240+ let owned;
241+ let tw = match mdct_twiddles(n) {
242+ Some(t) => t,
243+ None => {
244+ owned = MdctTwiddles::build(n);
245+ &owned
246+ }
247+ };
248+ // TDAC fold x[0..N] → y[mm] (computed on the fly), for the two indices each p needs.
249+ let (l2, l32) = (l / 2, 3 * l / 2);
250+ let fold = |mm: usize| -> f64 {
251+ if mm < l2 {
252+ -(x[l32 - 1 - mm] as f64) - (x[mm + l32] as f64)
253+ } else {
254+ (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)
255+ }
256+ };
257+ // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}.
258+ let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);
259+ for p in 0..m {
260+ let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p));
261+ re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];
262+ im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];
263+ }
264+ fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s);
265+ // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2.
266+ let mut out = vec![0f32; l];
267+ for p in 0..m {
268+ let (vr, vi) = (re[p], im[p]);
269+ out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32;
270+ out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32;
271+ }
272+ out
273+}
274+
275+/// AAC sine analysis/synthesis window: `w[n] = sin(π/N·(n+½))`.
276+pub fn sine_window(n: usize) -> Vec<f32> {
277+ (0..n)
278+ .map(|i| (PI / n as f64 * (i as f64 + 0.5)).sin() as f32)
279+ .collect()
280+}
281+
282+/// Modified Bessel function of the first kind, order 0 (series form).
283+fn bessel_i0(x: f64) -> f64 {
284+ let mut sum = 1.0;
285+ let mut term = 1.0;
286+ let half_x = x / 2.0;
287+ for k in 1..50 {
288+ term *= (half_x / k as f64).powi(2);
289+ sum += term;
290+ if term < 1e-12 * sum {
291+ break;
292+ }
293+ }
294+ sum
295+}
296+
297+/// Kaiser-Bessel-derived window of length `n` (ISO 14496-3 §4.6.11.2.4).
298+/// `alpha` is 4 for long blocks (N=2048), 6 for short (N=256).
299+pub fn kbd_window(n: usize, alpha: f64) -> Vec<f32> {
300+ let half = n / 2;
301+ // Cumulative Kaiser window over the first half.
302+ let mut cumulative = vec![0f64; half + 1];
303+ let mut running = 0.0;
304+ for p in 0..=half {
305+ let r = 2.0 * p as f64 / half as f64 - 1.0; // -1..1
306+ running += bessel_i0(PI * alpha * (1.0 - r * r).max(0.0).sqrt());
307+ cumulative[p] = running;
308+ }
309+ let total = cumulative[half];
310+ let mut w = vec![0f32; n];
311+ for i in 0..half {
312+ w[i] = (cumulative[i] / total).sqrt() as f32;
313+ w[n - 1 - i] = w[i];
314+ }
315+ w
316+}
317+
318+#[cfg(test)]
319+mod tests {
320+ use super::*;
321+
322+ /// The fast FFT-based MDCT must match the direct O(N²) oracle at both block
323+ /// sizes, on raw and encoder-scaled (×32768) input.
324+ #[test]
325+ fn mdct_fast_matches_direct() {
326+ for &n in &[256usize, 2048] {
327+ for &scale in &[1.0f32, 32768.0] {
328+ let x: Vec<f32> = (0..n)
329+ .map(|i| {
330+ scale
331+ * (0.3 * (i as f64 * 0.021).sin() + 0.2 * (i as f64 * 0.005).cos())
332+ as f32
333+ })
334+ .collect();
335+ let (a, b) = (mdct(&x), mdct_fast(&x));
336+ let tol = 2e-3 * scale.max(1.0);
337+ for k in 0..n / 2 {
338+ assert!(
339+ (a[k] - b[k]).abs() < tol,
340+ "n={n} scale={scale} k={k}: {} vs {}",
341+ a[k],
342+ b[k]
343+ );
344+ }
345+ }
346+ }
347+ }
348+
349+ #[test]
350+ fn dequant_matches_spec_curve() {
351+ assert_eq!(dequant(0), 0.0);
352+ assert_eq!(dequant(1), 1.0);
353+ assert!((dequant(2) - 2f32.powf(4.0 / 3.0)).abs() < 1e-5);
354+ assert!((dequant(-3) + 3f32.powf(4.0 / 3.0)).abs() < 1e-4);
355+ // Monotonic and sign-preserving.
356+ assert!(dequant(10) > dequant(9));
357+ assert!(dequant(-5) < 0.0);
358+ }
359+
360+ #[test]
361+ fn sf_gain_is_quarter_db_steps() {
362+ assert!((sf_gain(100) - 1.0).abs() < 1e-6); // sf 100 → unity
363+ assert!((sf_gain(104) - 2.0).abs() < 1e-5); // +4 → ×2
364+ assert!((sf_gain(96) - 0.5).abs() < 1e-6); // −4 → ×0.5
365+ }
366+
367+ /// w[n]² + w[n+N/2]² = 1 is the Princen-Bradley condition both AAC windows
368+ /// must satisfy for the filterbank to reconstruct perfectly.
369+ fn assert_princen_bradley(w: &[f32]) {
370+ let half = w.len() / 2;
371+ for n in 0..half {
372+ let s = w[n] * w[n] + w[n + half] * w[n + half];
373+ assert!((s - 1.0).abs() < 1e-4, "PB violated at {n}: {s}");
374+ }
375+ }
376+
377+ #[test]
378+ fn sine_window_satisfies_princen_bradley() {
379+ assert_princen_bradley(&sine_window(256));
380+ }
381+
382+ #[test]
383+ fn kbd_window_satisfies_princen_bradley() {
384+ assert_princen_bradley(&kbd_window(256, 4.0));
385+ assert_princen_bradley(&kbd_window(256, 6.0));
386+ }
387+
388+ /// The decisive correctness check: windowed MDCT → IMDCT → windowed
389+ /// overlap-add reconstructs the original signal in the steady-state region
390+ /// (TDAC). If the IMDCT/window math is wrong, this fails.
391+ #[test]
392+ fn mdct_imdct_overlap_add_perfectly_reconstructs() {
393+ let n = 64usize;
394+ let half = n / 2;
395+ let w = sine_window(n);
396+ // A deterministic, broadband test signal.
397+ let len = 4 * n;
398+ let signal: Vec<f32> = (0..len)
399+ .map(|i| (0.3 * (i as f64 * 0.21).sin() + 0.2 * (i as f64 * 0.05).cos()) as f32)
400+ .collect();
401+
402+ let mut out = vec![0f32; len];
403+ let mut p = 0;
404+ while p + n <= len {
405+ let framed: Vec<f32> = (0..n).map(|i| signal[p + i] * w[i]).collect();
406+ let synth = imdct(&mdct(&framed));
407+ for i in 0..n {
408+ out[p + i] += synth[i] * w[i];
409+ }
410+ p += half;
411+ }
412+
413+ // Interior (≥ one full frame from each edge) must match the input.
414+ for i in n..(len - n) {
415+ assert!(
416+ (out[i] - signal[i]).abs() < 1e-3,
417+ "reconstruction error at {i}: {} vs {}",
418+ out[i],
419+ signal[i]
420+ );
421+ }
422+ }
423+}
vendor/rusty_aac/src/encode.rsadded+4940 -0

Diff too large; view file

@@ -0,0 +1,4940 @@
1+//! In-house **AAC-LC encoder** (see `docs/codec-aac-encoder.md` for the brick
2+//! ledger). Bricks 1–7 are complete: encode-side primitives inverting the decoder
3+//! (bit writer, spectral-codebook encoder, header/config serializers), the forward
4+//! filterbank, the quantizer + rate loop, a Bark-spreading psychoacoustic model,
5+//! block switching, M/S stereo, and container/CLI integration.
6+//!
7+//! **What this encoder does NOT yet do** — the arms tracked by
8+//! `docs/codec-aac-great-gate.md`. Naming them here keeps a fit from being run
9+//! against a mis-documented encoder:
10+//!
11+//! * The psy model drives **long blocks only**; short blocks code with flat
12+//! scalefactors and a single window group (arm A1).
13+//! * The signal-to-mask ratio is a **constant 18 dB** — no tonality/SFM term
14+//! (arm A2), and no absolute threshold of hearing, so nothing here is a
15+//! function of absolute level (arm A4).
16+//! * **TNS, PNS and intensity stereo are never emitted** (arms A3/A6/A7), though
17+//! `crate::decode` implements all three.
18+//! * The rate loop searches **one global base offset** against a **constant
19+//! per-frame budget** — there is no outer per-band distortion loop (arm A12)
20+//! and no bit reservoir or VBR mode (arm A5).
21+//! * Window shape is hardcoded sine (arm A8) and the transient detector uses an
22+//! absolute energy ratio (arm A9).
23+
24+#![allow(dead_code)]
25+
26+use crate::codebook::{Codebook, CODEBOOKS, INTENSITY_HCB, INTENSITY_HCB2, NOISE_HCB};
27+use crate::ics::{IcsInfo, WindowSequence};
28+use crate::swb::swb_offsets;
29+use crate::tables::spectral_book;
30+use crate::{AdtsHeader, AudioSpecificConfig, Error, Result};
31+use std::collections::{HashMap, VecDeque};
32+use std::sync::{Arc, Mutex, OnceLock};
33+
34+// ---------------------------------------------------------------------------
35+// Bit writer — MSB-first, the mirror of the decoder's `BitReader`.
36+// ---------------------------------------------------------------------------
37+pub struct BitWriter {
38+ buf: Vec<u8>,
39+ cur: u8,
40+ nbits: u8,
41+}
42+
43+impl BitWriter {
44+ pub fn new() -> Self {
45+ BitWriter {
46+ buf: Vec::new(),
47+ cur: 0,
48+ nbits: 0,
49+ }
50+ }
51+
52+ /// Append the low `n` bits of `val`, most-significant bit first.
53+ pub fn write(&mut self, val: u32, n: u32) {
54+ for i in (0..n).rev() {
55+ self.cur = (self.cur << 1) | ((val >> i) & 1) as u8;
56+ self.nbits += 1;
57+ if self.nbits == 8 {
58+ self.buf.push(self.cur);
59+ self.cur = 0;
60+ self.nbits = 0;
61+ }
62+ }
63+ }
64+
65+ pub fn write_bool(&mut self, b: bool) {
66+ self.write(b as u32, 1);
67+ }
68+
69+ /// Total bits written so far.
70+ pub fn bit_len(&self) -> usize {
71+ self.buf.len() * 8 + self.nbits as usize
72+ }
73+
74+ /// Pad to a byte boundary with zero bits and return the bytes.
75+ pub fn into_bytes(mut self) -> Vec<u8> {
76+ if self.nbits != 0 {
77+ self.cur <<= 8 - self.nbits;
78+ self.buf.push(self.cur);
79+ }
80+ self.buf
81+ }
82+}
83+
84+impl Default for BitWriter {
85+ fn default() -> Self {
86+ Self::new()
87+ }
88+}
89+
90+// ---------------------------------------------------------------------------
91+// Spectral codebook encoding — the inverse of `codebook::apply_index`.
92+// ---------------------------------------------------------------------------
93+
94+/// Pack a `dim`-tuple of quantized coefficients into codebook `cb`'s base-`modulo`
95+/// Huffman index, or None if the tuple isn't representable by that codebook.
96+fn tuple_index(cb: &Codebook, tuple: &[i32]) -> Option<u32> {
97+ let dim = cb.dim as usize;
98+ let lav = cb.lav as u32;
99+ let modulo = if cb.unsigned { lav + 1 } else { 2 * lav + 1 };
100+ let mut index = 0u32;
101+ for &c in &tuple[..dim] {
102+ let mag = c.unsigned_abs();
103+ let digit = if cb.unsigned {
104+ if cb.esc {
105+ mag.min(lav) // book 11: a magnitude ≥ lav clamps to lav and escapes
106+ } else if mag <= lav {
107+ mag
108+ } else {
109+ return None;
110+ }
111+ } else if mag <= lav {
112+ (c + lav as i32) as u32
113+ } else {
114+ return None;
115+ };
116+ index = index * modulo + digit;
117+ }
118+ Some(index)
119+}
120+
121+/// Bits to code `tuple` with codebook `cb_num`, or None if unrepresentable.
122+pub fn spectral_bits(cb_num: usize, tuple: &[i32]) -> Option<usize> {
123+ let cb = &CODEBOOKS[cb_num];
124+ let idx = tuple_index(cb, tuple)?;
125+ let (_, len) = spectral_book(cb_num as u8).code(idx as usize);
126+ let dim = cb.dim as usize;
127+ let mut bits = len as usize;
128+ if cb.unsigned {
129+ bits += tuple[..dim].iter().filter(|&&c| c != 0).count(); // one sign bit each
130+ }
131+ if cb.esc {
132+ for &c in &tuple[..dim] {
133+ if c.unsigned_abs() >= cb.lav as u32 {
134+ bits += escape_bits(c.unsigned_abs());
135+ }
136+ }
137+ }
138+ Some(bits)
139+}
140+
141+/// Emit `tuple` with codebook `cb_num`: codeword, then sign bits (unsigned books),
142+/// then escape sequences (book 11). Caller ensures `spectral_bits` is Some.
143+pub fn spectral_emit(cb_num: usize, tuple: &[i32], w: &mut BitWriter) {
144+ let cb = &CODEBOOKS[cb_num];
145+ let dim = cb.dim as usize;
146+ let idx = tuple_index(cb, tuple).expect("representable tuple");
147+ let (code, len) = spectral_book(cb_num as u8).code(idx as usize);
148+ w.write(code, len as u32);
149+ if cb.unsigned {
150+ for &c in &tuple[..dim] {
151+ if c != 0 {
152+ w.write_bool(c < 0);
153+ }
154+ }
155+ }
156+ if cb.esc {
157+ for &c in &tuple[..dim] {
158+ if c.unsigned_abs() >= cb.lav as u32 {
159+ emit_escape(c.unsigned_abs(), w);
160+ }
161+ }
162+ }
163+}
164+
165+/// Escape length for magnitude `m` (≥ 16): `2N+5` bits, `2^(N+4) ≤ m < 2^(N+5)`.
166+fn escape_bits(m: u32) -> usize {
167+ let n = (31 - m.leading_zeros()) - 4;
168+ 2 * n as usize + 5
169+}
170+
171+/// Escape sequence (ISO §4.6.3.3): N leading 1-bits, a 0, then N+4 bits of
172+/// `m - 2^(N+4)`.
173+fn emit_escape(m: u32, w: &mut BitWriter) {
174+ let n = (31 - m.leading_zeros()) - 4;
175+ for _ in 0..n {
176+ w.write_bool(true);
177+ }
178+ w.write_bool(false);
179+ let bits = n + 4;
180+ w.write(m - (1 << bits), bits);
181+}
182+
183+// ---------------------------------------------------------------------------
184+// Header / config serializers — inverses of the decoder's parsers.
185+// ---------------------------------------------------------------------------
186+
187+/// The `AudioSpecificConfig` bytes for an AAC-LC stream — the MP4 `esds`
188+/// DecoderSpecificInfo the muxer needs (2 bytes for standard rates).
189+pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
190+ write_audio_specific_config(&AudioSpecificConfig {
191+ object_type: 2, // AAC-LC
192+ sample_rate,
193+ channels,
194+ })
195+}
196+
197+/// Serialize an `AudioSpecificConfig` (ISO §1.6.2.1) — the `esds`/`stsd` config
198+/// bytes the MP4 muxer needs. Inverse of `parse_audio_specific_config`.
199+pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
200+ let mut w = BitWriter::new();
201+ if cfg.object_type >= 31 {
202+ w.write(31, 5);
203+ w.write((cfg.object_type - 32) as u32, 6);
204+ } else {
205+ w.write(cfg.object_type as u32, 5);
206+ }
207+ match crate::sf_index_for_rate(cfg.sample_rate) {
208+ Some(i) => w.write(i as u32, 4),
209+ None => {
210+ w.write(0x0F, 4);
211+ w.write(cfg.sample_rate, 24);
212+ }
213+ }
214+ w.write(cfg.channels as u32, 4);
215+ w.into_bytes()
216+}
217+
218+/// Serialize a 7-byte ADTS frame header (no CRC) — inverse of `parse_adts`.
219+/// `hdr.frame_length` must include this 7-byte header.
220+pub fn write_adts_header(hdr: &AdtsHeader) -> Vec<u8> {
221+ let sf = crate::sf_index_for_rate(hdr.sample_rate).expect("standard rate for ADTS");
222+ let mut w = BitWriter::new();
223+ w.write(0xFFF, 12); // syncword
224+ w.write(0, 1); // MPEG-4
225+ w.write(0, 2); // layer (00)
226+ w.write_bool(true); // protection_absent → 7-byte header, no CRC
227+ w.write((hdr.object_type - 1) as u32, 2); // profile
228+ w.write(sf as u32, 4);
229+ w.write(0, 1); // private
230+ w.write(hdr.channels as u32, 3); // channel config
231+ w.write(0, 4); // orig/home/copyright id+start
232+ w.write(hdr.frame_length as u32, 13);
233+ w.write(0x7FF, 11); // buffer fullness (VBR marker)
234+ w.write(0, 2); // num_raw_data_blocks - 1
235+ w.into_bytes()
236+}
237+
238+/// Serialize `ics_info` for AAC-LC — inverse of `parse_ics_info`.
239+pub fn encode_ics_info(w: &mut BitWriter, info: &IcsInfo) {
240+ w.write(0, 1); // ics_reserved
241+ w.write(info.window_sequence.to_bits(), 2);
242+ w.write_bool(info.window_shape_kbd);
243+ if info.window_sequence.is_short() {
244+ w.write(info.max_sfb as u32, 4);
245+ w.write(grouping_bits(&info.window_group_length), 7);
246+ } else {
247+ w.write(info.max_sfb as u32, 6);
248+ w.write(0, 1); // predictor_data_present (AAC-LC = 0)
249+ }
250+}
251+
252+/// The 7 `scale_factor_grouping` bits from window-group lengths (inverse of the
253+/// parser's grouping walk): the bit for window i+1 is 1 if it continues the
254+/// current group, 0 if it starts a new one.
255+fn grouping_bits(group_lengths: &[u8]) -> u32 {
256+ let mut is_start = [false; 8];
257+ let mut w = 0usize;
258+ for &len in group_lengths {
259+ if w < 8 {
260+ is_start[w] = true;
261+ }
262+ w += len as usize;
263+ }
264+ let mut sfg = 0u32;
265+ for i in 0..7 {
266+ if !is_start[i + 1] {
267+ sfg |= 1 << (6 - i);
268+ }
269+ }
270+ sfg
271+}
272+
273+// ---------------------------------------------------------------------------
274+// Filterbank — forward long-block MDCT (inverse of the decoder's synthesis).
275+// ---------------------------------------------------------------------------
276+pub const FRAME_LEN: usize = 1024;
277+pub const LONG_N: usize = 2048;
278+const SHORT_N: usize = 256;
279+const SHORT_HALF: usize = 128;
280+/// 1 / OUTPUT_NORM: the decoder scales its output by 1/32768, so the encoder
281+/// scales the spectrum up by 32768 to land in the AAC coefficient domain.
282+const SPEC_SCALE: f32 = 32768.0;
283+
284+/// Forward long-block filterbank: window the overlapping 2048 input samples
285+/// (previous frame's 1024 ++ current 1024) and forward-MDCT to 1024 coefficients,
286+/// scaled so the decoder's `imdct · window · (1/32768) + overlap-add` reconstructs
287+/// the input (TDAC). `win` is the 2048-length window (sine or KBD).
288+pub fn analyze_long(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], win: &[f32]) -> Vec<f32> {
289+ let mut windowed = vec![0f32; LONG_N];
290+ for n in 0..FRAME_LEN {
291+ windowed[n] = prev[n] * win[n] * SPEC_SCALE;
292+ windowed[FRAME_LEN + n] = cur[n] * win[FRAME_LEN + n] * SPEC_SCALE;
293+ }
294+ crate::dsp::mdct_fast(&windowed)
295+}
296+
297+/// Forward short-block filterbank: eight 256-sample windows (128-hop) tiled across
298+/// [448, 1600) of the prev++cur 2048 buffer, each windowed + MDCT'd to 128 coeffs,
299+/// laid out window-major (the exact inverse of the decoder's `short_frame`). The
300+/// uncovered [0,448)/[1600,2048) regions are bridged by the LongStart/LongStop
301+/// neighbours — which is why EightShort must sit between transition blocks.
302+pub fn analyze_short(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], sw: &[f32]) -> Vec<f32> {
303+ let mut buf = [0f32; LONG_N];
304+ buf[..FRAME_LEN].copy_from_slice(prev);
305+ buf[FRAME_LEN..].copy_from_slice(cur);
306+ let mut spec = vec![0f32; FRAME_LEN];
307+ for w in 0..8 {
308+ let off = 448 + w * SHORT_HALF;
309+ let mut windowed = [0f32; SHORT_N];
310+ for (n, s) in windowed.iter_mut().enumerate() {
311+ *s = buf[off + n] * sw[n] * SPEC_SCALE;
312+ }
313+ let coeffs = crate::dsp::mdct_fast(&windowed);
314+ spec[w * SHORT_HALF..(w + 1) * SHORT_HALF].copy_from_slice(&coeffs);
315+ }
316+ spec
317+}
318+
319+/// The 2048-sample analysis window for a long or transition block — the exact
320+/// encode-side twin of the decoder's `long_window`.
321+///
322+/// **The left half follows the PREVIOUS block's shape, the right half the
323+/// current's** (`prev_kbd` / `cur_kbd`), because that is what the decoder does:
324+/// each overlap region must be windowed identically on both sides or TDAC fails
325+/// and the overlap-add leaves audible seams. LongStart/LongStop taper one side to
326+/// a short window so the sequence stays TDAC-exact.
327+///
328+/// The decoder seeds `prev_kbd = false` for the first frame of a stream
329+/// (`decode.rs`), so the encoder must too.
330+#[allow(clippy::too_many_arguments)]
331+fn long_window(
332+ seq: WindowSequence,
333+ prev_kbd: bool,
334+ cur_kbd: bool,
335+ sine_l: &[f32],
336+ kbd_l: &[f32],
337+ sine_s: &[f32],
338+ kbd_s: &[f32],
339+) -> Vec<f32> {
340+ let long_prev = if prev_kbd { kbd_l } else { sine_l };
341+ let long_cur = if cur_kbd { kbd_l } else { sine_l };
342+ let short_prev = if prev_kbd { kbd_s } else { sine_s };
343+ let short_cur = if cur_kbd { kbd_s } else { sine_s };
344+
345+ let mut w = vec![0f32; LONG_N];
346+ if seq == WindowSequence::LongStop {
347+ w[448..448 + SHORT_HALF].copy_from_slice(&short_prev[..SHORT_HALF]);
348+ for s in w.iter_mut().take(FRAME_LEN).skip(576) {
349+ *s = 1.0;
350+ }
351+ } else {
352+ w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]);
353+ }
354+ if seq == WindowSequence::LongStart {
355+ for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) {
356+ *s = 1.0;
357+ }
358+ w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&short_cur[SHORT_HALF..]);
359+ } else {
360+ w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]);
361+ }
362+ w
363+}
364+
365+/// **The Rung 0 gate signal**: order-2 LPC prediction gain over the frame's time
366+/// samples — a cheap tonality proxy.
367+///
368+/// Chosen over the spectral flatness measure the lab validates because SFM needs
369+/// a spectrum, and the window shape must be decided *before* the spectrum exists
370+/// (the shape determines the window that produces it). Computing a probe MDCT per
371+/// frame just to pick a window would roughly double filterbank cost for a
372+/// small-by-design win — dominated on `bits-per-op` grounds before it started.
373+///
374+/// This is O(3n) multiply-adds and needs no transform. Tonal signals are strongly
375+/// predictable from two past samples; noise is not. Validated against the
376+/// per-class truth table in `lab::signals` before being wired here.
377+///
378+/// Returns `R[0] / E₂ ≥ 1`.
379+pub(crate) fn time_tonality(x: &[f32]) -> f32 {
380+ let n = x.len();
381+ if n < 8 {
382+ return 1.0;
383+ }
384+ let mut r = [0f64; 3];
385+ for (lag, slot) in r.iter_mut().enumerate() {
386+ let mut acc = 0f64;
387+ for i in 0..n - lag {
388+ acc += x[i] as f64 * x[i + lag] as f64;
389+ }
390+ *slot = acc;
391+ }
392+ if r[0] <= 1e-12 {
393+ return 1.0;
394+ }
395+ let r0 = r[0] * 1.0001; // white-noise correction — keeps Levinson stable
396+ let k1 = r[1] / r0;
397+ let e1 = r0 * (1.0 - k1 * k1);
398+ if e1 <= 1e-12 {
399+ return 1.0;
400+ }
401+ let k2 = (r[2] - k1 * r[1]) / e1;
402+ let e2 = e1 * (1.0 - k2 * k2);
403+ ((r0 / e2.max(1e-12)) as f32).max(1.0)
404+}
405+
406+// ---------------------------------------------------------------------------
407+// Psychoacoustic model (brick 4) — per-SFB masking thresholds drive per-band
408+// scalefactor allocation, so quantization noise is shaped to the audible floor.
409+// ---------------------------------------------------------------------------
410+
411+/// Traunmüller's Hz→Bark (critical-band rate).
412+fn hz_to_bark(f: f64) -> f64 {
413+ let f = f.max(1.0);
414+ 26.81 * f / (1960.0 + f) - 0.53
415+}
416+
417+/// Spreading of a masker's energy to a maskee `dz` Bark away (`dz` = maskee −
418+/// masker): steep ~27 dB/Bark toward lower bands, gentle ~10 dB/Bark upward.
419+fn spreading(dz: f64) -> f64 {
420+ let slope_db = if dz >= 0.0 { -10.0 } else { -27.0 };
421+ 10f64.powf(slope_db * dz.abs() / 10.0)
422+}
423+
424+/// The Bark-spreading matrix `S[i·n+j] = spreading(bark[i]-bark[j])` for one band
425+/// geometry — fixed per (sample_rate, band count), so it's built once and cached,
426+/// turning each frame's masking into a matrix-vector product (no runtime powf).
427+/// `n_coeffs` is the number of spectral coefficients the band table spans — 1024
428+/// for a long block, 128 for one short window. It sets the coefficient→Hz
429+/// mapping, so passing the long value for a short block would place every band
430+/// eight octaves too low and spread the mask against the wrong neighbours.
431+fn spreading_matrix(swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Arc<Vec<f64>> {
432+ type Cache = Mutex<HashMap<(u32, usize, usize), Arc<Vec<f64>>>>;
433+ static CACHE: OnceLock<Cache> = OnceLock::new();
434+ let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
435+ let key = (sample_rate, swb.len(), n_coeffs);
436+ let mut c = cache.lock().unwrap();
437+ if let Some(m) = c.get(&key) {
438+ return m.clone();
439+ }
440+ let num_swb = swb.len() - 1;
441+ let bark: Vec<f64> = (0..num_swb)
442+ .map(|sfb| {
443+ let center = (swb[sfb] as f64 + swb[sfb + 1] as f64) / 2.0;
444+ // n_coeffs coefficients span 0..sr/2.
445+ hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64)
446+ })
447+ .collect();
448+ let mut mat = vec![0f64; num_swb * num_swb];
449+ for i in 0..num_swb {
450+ for j in 0..num_swb {
451+ mat[i * num_swb + j] = spreading(bark[i] - bark[j]);
452+ }
453+ }
454+ let arc = Arc::new(mat);
455+ c.insert(key, arc.clone());
456+ arc
457+}
458+
459+/// Per-SFB masking threshold (energy units): spread the band energies on the
460+/// Bark scale, then sit the mask a fixed ratio below the spread signal.
461+///
462+/// `pub(crate)` so [`crate::lab::quality`] can score coding noise against the
463+/// encoder's own mask (the NMR metric), in the same band geometry and energy
464+/// domain the encoder allocates in.
465+pub(crate) fn masking_thresholds(spec: &[f32], swb: &[u16], sample_rate: u32) -> Vec<f64> {
466+ let num_swb = swb.len() - 1;
467+ let mut energy = vec![0.0f64; num_swb];
468+ for sfb in 0..num_swb {
469+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
470+ energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::<f64>() + 1e-3;
471+ }
472+ masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, None)
473+}
474+
475+/// The default signal-to-mask ratio: the mask sits 18 dB below the spread signal,
476+/// for every band and every kind of content.
477+///
478+/// **Arm A2** replaces this constant with a function of tonality. It is census
479+/// category 4 — a knob whose own doc-comment names the physical signal it tracks,
480+/// shipping as a constant. Kept as the byte-identical fallback.
481+const SMR_FLAT: f64 = 0.0158; // 10^(-18/10)
482+
483+/// The psychoacoustic arms in flight, threaded down to every coding path.
484+///
485+/// A struct rather than loose bools because these arms compose: A1 decides
486+/// *whether* short blocks get a mask at all, A2 decides *what* that mask is, and
487+/// both must reach the CPE path and the SCE path identically or the two paths
488+/// silently encode to different models — the inconsistency great-gate's P0.9
489+/// hygiene batch exists to prevent.
490+///
491+/// `PsyCfg::default()` is all-off = the encoder exactly as it shipped.
492+#[derive(Debug, Clone, Copy, Default)]
493+pub(crate) struct PsyCfg {
494+ /// Arm A1 — psy model on short blocks (else flat scalefactors).
495+ pub short_block_psy: bool,
496+ /// Arm A2 — tonality-adaptive SMR (else flat 18 dB).
497+ pub tonality_smr: bool,
498+ /// Arm A3 — emit TNS on long blocks.
499+ pub tns: bool,
500+ /// Arm A6 — Perceptual Noise Substitution.
501+ pub pns: bool,
502+ /// Arm A7 — intensity stereo.
503+ pub intensity: bool,
504+ /// Arm A13 — demand-proportional stereo bit split.
505+ pub stereo_bit_split: bool,
506+}
507+
508+/// Per-band masking threshold from precomputed band energies.
509+///
510+/// Split out from [`masking_thresholds`] so short blocks (whose band energies are
511+/// summed across the eight windows of a group) and long blocks share one masking
512+/// model — great-gate P1: consolidate duplicated probe skeletons into one path,
513+/// or a fit spanning both learns the inconsistency rather than the content.
514+///
515+/// `tonality` is **arm A2**: `None` uses the flat 18 dB [`SMR_FLAT`] (the shipped
516+/// behavior, byte-identical); `Some(t)` interpolates the classic tonal/noise
517+/// masker offsets per band.
518+fn masking_from_energy(
519+ energy: &[f64],
520+ swb: &[u16],
521+ sample_rate: u32,
522+ n_coeffs: usize,
523+ tonality: Option<&[f32]>,
524+) -> Vec<f64> {
525+ let num_swb = swb.len() - 1;
526+ let mat = spreading_matrix(swb, sample_rate, n_coeffs);
527+ (0..num_swb)
528+ .map(|i| {
529+ let row = &mat[i * num_swb..(i + 1) * num_swb];
530+ let spread: f64 = (0..num_swb).map(|j| energy[j] * row[j]).sum();
531+ let smr = match tonality {
532+ None => SMR_FLAT,
533+ Some(t) => {
534+ let center = (swb[i] as f64 + swb[i + 1] as f64) / 2.0;
535+ let bark = hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64);
536+ smr_for(t[i] as f64, bark)
537+ }
538+ };
539+ spread * smr
540+ })
541+ .collect()
542+}
543+
544+/// **Arm A2.** Signal-to-mask ratio as a function of band tonality and Bark.
545+///
546+/// The classic asymmetry: a *tonal* masker hides noise poorly, so the mask must
547+/// sit far below it (≈ 14.5 + bark dB); a *noise-like* masker hides noise well
548+/// (≈ 5.5 dB). Interpolating on the tonality index is the standard MPEG form.
549+///
550+/// Today's encoder applies 18 dB to everything, so a pure tone and band-limited
551+/// noise at equal energy get identical treatment — which is what this replaces.
552+///
553+/// Returned as a linear energy ratio (`10^(−dB/10)`), matching [`SMR_FLAT`].
554+///
555+/// # The noise end is 5.5 dB — and pinning it to 18 dB was measured and REFUTED
556+///
557+/// The obvious-looking "safety" tweak is to pin the noise end to the shipped flat
558+/// 18 dB, so arm A2 can only ever give a band *more* protection than today and
559+/// never less. Measured on the corpus, that made things **worse**, not safer:
560+///
561+/// | noise end | mean Δaudible% | worst class |
562+/// |---|---|---|
563+/// | 5.5 dB (textbook) | **−0.312** | +0.720 |
564+/// | 18.0 dB (pinned) | −0.006 | **+2.185** |
565+///
566+/// The reason is that an SMR pair is a **bit-allocation balance, not two
567+/// independent protections**. Raising the tonal end buys precision only because
568+/// lowering the noise end frees the bits to pay for it. Pin the noise end and the
569+/// tonal end becomes pure extra demand against a fixed budget — the rate loop
570+/// answers by lifting the global base, and *every* band gets coarser. The
571+/// "conservative" variant regressed three times as hard as the one it was meant
572+/// to protect against.
573+///
574+/// Keep the textbook pair. A2's remaining per-class failures are a **dispatch**
575+/// problem (route the arm by content class), not a constant to retune.
576+const SMR_NOISE_DB: f64 = 5.5;
577+fn smr_for(tonality: f64, bark: f64) -> f64 {
578+ let t = tonality.clamp(0.0, 1.0);
579+ let db = t * (14.5 + bark) + (1.0 - t) * SMR_NOISE_DB;
580+ // Clamp to a sane band: below ~5 dB the mask stops protecting anything, and
581+ // above ~30 dB the rate loop is asked for precision no bitrate can buy.
582+ let db = db.clamp(5.0, 30.0);
583+ 10f64.powf(-db / 10.0)
584+}
585+
586+/// Per-SFB scalefactor offsets (relative to a common base the rate loop sets):
587+/// higher where masking is generous, lower where noise would be audible. From
588+/// `noise ∝ 2^(0.375·sf)·Σ√|X|`, the sf hitting `noise = threshold` is
589+/// `log2(threshold/Σ√|X|)/0.375`; we normalize + clamp so deltas stay codeable.
590+/// Per-SFB tonality index in `[0, 1]` from the spectral flatness measure — **arm
591+/// A2's signal**. 0 = noise-like, 1 = pure tone.
592+///
593+/// `SFM = geometric_mean(|X|²) / arithmetic_mean(|X|²)`, in dB, through the
594+/// classic `min(SFM_dB / −60, 1)`.
595+pub(crate) fn band_tonality(spec: &[f32], swb: &[u16], nwin: usize, wlen: usize) -> Vec<f32> {
596+ let n = swb.len() - 1;
597+ let mut out = vec![0f32; n];
598+ for b in 0..n {
599+ let (s, e) = (swb[b] as usize, swb[b + 1] as usize);
600+ let (mut log_sum, mut lin_sum, mut cnt) = (0f64, 0f64, 0usize);
601+ for w in 0..nwin {
602+ let base = w * wlen;
603+ for k in s..e {
604+ let Some(&x) = spec.get(base + k) else { continue };
605+ // Floored well below any audible coefficient so a single exact
606+ // zero cannot drag the geometric mean to 0 and fake a pure tone.
607+ let p = ((x as f64) * (x as f64)).max(1e-10);
608+ log_sum += p.ln();
609+ lin_sum += p;
610+ cnt += 1;
611+ }
612+ }
613+ if cnt == 0 {
614+ continue;
615+ }
616+ let gm = (log_sum / cnt as f64).exp();
617+ let am = lin_sum / cnt as f64;
618+ let sfm_db = 10.0 * (gm / am.max(1e-30)).log10();
619+ out[b] = ((sfm_db / -60.0) as f32).clamp(0.0, 1.0);
620+ }
621+ out
622+}
623+
624+fn perceptual_offsets(
625+ spec: &[f32],
626+ swb: &[u16],
627+ sample_rate: u32,
628+ tonality_smr: bool,
629+) -> Vec<i32> {
630+ let num_swb = swb.len() - 1;
631+ let mut energy = vec![0.0f64; num_swb];
632+ for sfb in 0..num_swb {
633+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
634+ energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::<f64>() + 1e-3;
635+ }
636+ let ton = tonality_smr.then(|| band_tonality(spec, swb, 1, FRAME_LEN));
637+ let thr = masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, ton.as_deref());
638+
639+ let mut raw = vec![0.0f64; num_swb];
640+ for sfb in 0..num_swb {
641+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
642+ energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum();
643+ let noise_scale: f64 = spec[s..e]
644+ .iter()
645+ .map(|&x| (x.abs() as f64).sqrt())
646+ .sum::<f64>()
647+ + 1e-6;
648+ raw[sfb] = (thr[sfb] / noise_scale).log2() / 0.375;
649+ }
650+ // Center on the energy-bearing bands — empty bands have huge `thr/noise_scale`
651+ // (they quantize to ZERO anyway) and would otherwise skew a plain mean.
652+ let etot: f64 = energy.iter().sum::<f64>() + 1e-9;
653+ let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::<f64>() / etot;
654+ raw.iter()
655+ .map(|&r| ((r - center).round() as i32).clamp(-60, 60))
656+ .collect()
657+}
658+
659+// ---------------------------------------------------------------------------
660+// Quantization + coding — brick 4: per-band scalefactors (psy-driven), cheapest
661+// codebook per band, rate loop over the common base, raw_data_block assembly.
662+// ---------------------------------------------------------------------------
663+
664+/// The Rung 0 gate's transient-veto threshold, as a percentile of the clip's own
665+/// frame-attack distribution. Frames above it always take the sine window.
666+///
667+/// PROVISIONAL. 0.75 is a placeholder pending a calculator fit; it is set high
668+/// (veto only the top quartile) so the veto is conservative — it gives up KBD on
669+/// some stationary frames rather than risk smearing an onset.
670+const SHAPE_ATTACK_VETO_PCT: f32 = 0.75;
671+
672+/// Arm A13's routing threshold: how correlated a channel pair must be before the
673+/// joint rate loop replaces the even per-channel split. Sits in the measured gap
674+/// between wide content (0.25, where joint loses) and real stereo music
675+/// (0.47-0.84, where it wins).
676+const JOINT_STEREO_MIN_CORR: f32 = 0.35;
677+
678+/// Spectral correlation of a channel pair, `|<L,R>| / sqrt(<L,L><R,R>)`.
679+/// 1 = identical, 0 = orthogonal. O(n) over the spectra the caller already has.
680+fn pair_correlation(l: &[f32], r: &[f32]) -> f32 {
681+ let n = l.len().min(r.len());
682+ let (mut dot, mut el, mut er) = (0f64, 0f64, 0f64);
683+ for i in 0..n {
684+ let (a, b) = (l[i] as f64, r[i] as f64);
685+ dot += a * b;
686+ el += a * a;
687+ er += b * b;
688+ }
689+ if el <= 1e-9 || er <= 1e-9 {
690+ return 1.0; // a silent channel is trivially "agreeable"
691+ }
692+ (dot.abs() / (el.sqrt() * er.sqrt())) as f32
693+}
694+
695+const ID_SCE: u32 = 0;
696+const ID_CPE: u32 = 1;
697+const ID_LFE: u32 = 3;
698+const ID_END: u32 = 7;
699+const ZERO_HCB: u8 = 0;
700+const ESC_HCB: u8 = 11;
701+
702+// ---------------------------------------------------------------------------
703+// Channel element layout (ISO 14496-3 Table 1.19).
704+//
705+// `channel_configuration` in the ADTS header / AudioSpecificConfig does not just
706+// count channels — it *names the element sequence a decoder will expect*. Writing
707+// `channel_config = 6` and then emitting six SCEs is not "6 channels", it is a
708+// non-conformant stream: a conforming decoder reads SCE, CPE, CPE, LFE.
709+//
710+// Our own decoder happened to tolerate it (it appends elements in order), which
711+// is exactly how the bug survived — self-round-trip is not conformance.
712+// ---------------------------------------------------------------------------
713+
714+/// One channel element to emit, naming its source channels **in input order**.
715+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
716+pub(crate) enum Elem {
717+ /// single_channel_element carrying input channel `.0`.
718+ Sce(usize),
719+ /// channel_pair_element carrying input channels `.0` (left) and `.1` (right).
720+ Cpe(usize, usize),
721+ /// lfe_channel_element carrying input channel `.0`. Long blocks only.
722+ Lfe(usize),
723+}
724+
725+impl Elem {
726+ /// The 3-bit element id written to the bitstream.
727+ fn id(self) -> u32 {
728+ match self {
729+ Elem::Sce(_) => ID_SCE,
730+ Elem::Cpe(_, _) => ID_CPE,
731+ Elem::Lfe(_) => ID_LFE,
732+ }
733+ }
734+}
735+
736+/// The element sequence for `channels`, with source indices in the **standard
737+/// interleave order** the caller pushes (WAVE_FORMAT_EXTENSIBLE / FFmpeg order:
738+/// FL, FR, FC, LFE, BL, BR).
739+///
740+/// The reordering is the substance here. AAC orders a 5.1 stream
741+/// `C, L, R, Ls, Rs, LFE`; interleaved PCM arrives `L, R, C, LFE, Ls, Rs`. Emitting
742+/// them in arrival order would put the centre channel in the left speaker.
743+///
744+/// Returns `None` for channel counts with no defined `channel_configuration`
745+/// (0, or > 6): those need a program_config_element, which we do not yet write.
746+pub(crate) fn element_plan(channels: usize) -> Option<Vec<Elem>> {
747+ Some(match channels {
748+ // config 1 — mono.
749+ 1 => vec![Elem::Sce(0)],
750+ // config 2 — stereo.
751+ 2 => vec![Elem::Cpe(0, 1)],
752+ // config 3 — 3.0: C, L/R.
753+ 3 => vec![Elem::Sce(2), Elem::Cpe(0, 1)],
754+ // config 4 — 4.0: C, L/R, rear centre.
755+ 4 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Sce(3)],
756+ // config 5 — 5.0: C, L/R, Ls/Rs.
757+ 5 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(3, 4)],
758+ // config 6 — 5.1: C, L/R, Ls/Rs, LFE.
759+ 6 => vec![
760+ Elem::Sce(2),
761+ Elem::Cpe(0, 1),
762+ Elem::Cpe(4, 5),
763+ Elem::Lfe(3),
764+ ],
765+ _ => return None,
766+ })
767+}
768+
769+/// Inverse of [`element_plan`]'s ordering: for each **output** slot in standard
770+/// interleave order, which decoded element-order channel supplies it.
771+///
772+/// The decoder emits channels in element order (AAC order); this maps them back
773+/// so a 5.1 decode interleaves as FL, FR, FC, LFE, BL, BR like every other
774+/// decoder in the workspace.
775+pub(crate) fn aac_to_interleave_order(channels: usize) -> Option<Vec<usize>> {
776+ Some(match channels {
777+ 1 => vec![0],
778+ 2 => vec![0, 1],
779+ // AAC order C,L,R -> interleave L,R,C
780+ 3 => vec![1, 2, 0],
781+ // AAC order C,L,R,Cs -> interleave L,R,C,Cs
782+ 4 => vec![1, 2, 0, 3],
783+ // AAC order C,L,R,Ls,Rs -> interleave L,R,C,Ls,Rs
784+ 5 => vec![1, 2, 0, 3, 4],
785+ // AAC order C,L,R,Ls,Rs,LFE -> interleave L,R,C,LFE,Ls,Rs
786+ 6 => vec![1, 2, 0, 5, 3, 4],
787+ _ => return None,
788+ })
789+}
790+
791+const MAX_QUANT: i32 = 8191;
792+
793+/// Quantize one coefficient at global gain `gg` (used by tests / the noise metric).
794+fn quantize(x: f32, gg: i32) -> i32 {
795+ if x == 0.0 {
796+ return 0;
797+ }
798+ let scale = 2f64.powf(-0.1875 * (gg - 100) as f64);
799+ let q = (((x.abs() as f64).powf(0.75) * scale).round() as i32).min(MAX_QUANT);
800+ if x < 0.0 {
801+ -q
802+ } else {
803+ q
804+ }
805+}
806+
807+/// `2^(-0.1875·(sf-100))`, the quantizer scale, tabulated once over all 256 gains
808+/// so the rate loop never repeats the exponent.
809+fn scale_table() -> &'static [f64; 256] {
810+ static T: OnceLock<[f64; 256]> = OnceLock::new();
811+ T.get_or_init(|| {
812+ let mut t = [0f64; 256];
813+ for (sf, e) in t.iter_mut().enumerate() {
814+ *e = 2f64.powf(-0.1875 * (sf as f64 - 100.0));
815+ }
816+ t
817+ })
818+}
819+
820+/// Per-magnitude coefficient bit cost (half a book-11 pair), tabulated so the rate
821+/// loop's *search* can price a frame in O(n) without the full codebook selection —
822+/// only the exact refinement does the real search.
823+fn coef_bits() -> &'static [u16] {
824+ static T: OnceLock<Vec<u16>> = OnceLock::new();
825+ T.get_or_init(|| {
826+ (0..=MAX_QUANT)
827+ .map(|m| (spectral_bits(ESC_HCB as usize, &[m, m]).unwrap_or(64) / 2) as u16)
828+ .collect()
829+ })
830+}
831+
832+/// Per-coefficient `|x|^0.75` and sign, precomputed once per frame so the rate
833+/// loop can re-quantize at each candidate gain without repeating the 0.75-power
834+/// (the single hottest op after the MDCT). Bit-exact with [`quantize`].
835+struct Xpow {
836+ pow: Vec<f64>,
837+ sign: Vec<i32>,
838+}
839+
840+impl Xpow {
841+ fn new(spec: &[f32]) -> Xpow {
842+ let mut pow = vec![0f64; spec.len()];
843+ let mut sign = vec![0i32; spec.len()];
844+ #[cfg(all(feature = "simd", target_arch = "x86_64"))]
845+ {
846+ if has_avx2() {
847+ // SAFETY: runtime AVX2 check; `pow`/`sign` are `spec.len()` long.
848+ unsafe { xpow_avx2(spec, &mut pow, &mut sign) };
849+ return Xpow { pow, sign };
850+ }
851+ }
852+ for (i, &x) in spec.iter().enumerate() {
853+ // |x|^0.75 = |x|^½·|x|^¼ = √|x|·√√|x| — two sqrts vectorize; `powf` doesn't.
854+ // (For x=0, pow=0 so the sign is irrelevant — the quant is 0 either way.)
855+ let s = (x.abs() as f64).sqrt();
856+ pow[i] = s * s.sqrt();
857+ sign[i] = if x < 0.0 { -1 } else { 1 };
858+ }
859+ Xpow { pow, sign }
860+ }
861+
862+ /// Max `|x|^0.75` over `[s, e)` — the no-clamp-floor input (= `(max|x|)^0.75`).
863+ fn max_pow(&self, s: usize, e: usize) -> f64 {
864+ self.pow[s..e].iter().copied().fold(0.0, f64::max)
865+ }
866+
867+ fn len(&self) -> usize {
868+ self.pow.len()
869+ }
870+}
871+
872+/// The cheapest representable spectral codebook for one SFB's coefficients, and
873+/// its bit cost. ZERO for a silent band; dim-4 books only for 4-aligned bands.
874+/// Books whose LAV can't hold the band's peak are skipped up front (only the
875+/// escape book covers arbitrarily large values).
876+fn best_codebook_for_band(quant: &[i32], s: usize, e: usize) -> (u8, usize) {
877+ let maxq = quant[s..e]
878+ .iter()
879+ .map(|&q| q.unsigned_abs())
880+ .max()
881+ .unwrap_or(0);
882+ if maxq == 0 {
883+ return (ZERO_HCB, 0);
884+ }
885+ let mut best = (ESC_HCB, usize::MAX);
886+ for cb in 1..=11u8 {
887+ let meta = &CODEBOOKS[cb as usize];
888+ let dim = meta.dim as usize;
889+ if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) {
890+ continue;
891+ }
892+ let mut bits = 0usize;
893+ let mut ok = true;
894+ let mut i = s;
895+ while i < e {
896+ match spectral_bits(cb as usize, &quant[i..i + dim]) {
897+ Some(b) => bits += b,
898+ None => {
899+ ok = false;
900+ break;
901+ }
902+ }
903+ i += dim;
904+ }
905+ if ok && bits < best.1 {
906+ best = (cb, bits);
907+ }
908+ }
909+ best
910+}
911+
912+/// Bits for section_data given per-SFB codebooks (adjacent equal cbs merge into
913+/// one 4-bit codebook + 5-bit run-length increments).
914+fn section_bits(cbs: &[u8]) -> usize {
915+ let esc = 31usize;
916+ let mut bits = 0usize;
917+ let mut k = 0usize;
918+ while k < cbs.len() {
919+ let cb = cbs[k];
920+ let mut len = 1usize;
921+ while k + len < cbs.len() && cbs[k + len] == cb {
922+ len += 1;
923+ }
924+ bits += 4;
925+ let mut l = len;
926+ while l >= esc {
927+ bits += 5;
928+ l -= esc;
929+ }
930+ bits += 5;
931+ k += len;
932+ }
933+ bits
934+}
935+
936+/// Per-band scalefactors from a common `base` plus the psy offsets, each clamped
937+/// to the codeable range. Offsets span ≤48, so band-to-band deltas stay < 60.
938+fn scalefactors(offsets: &[i32], base: i32) -> Vec<i32> {
939+ offsets.iter().map(|&o| (base + o).clamp(0, 255)).collect()
940+}
941+
942+/// global_gain = the first coded band's scalefactor (the differential reference);
943+/// 100 for a silent frame with no coded bands.
944+fn global_gain(cbs: &[u8], sf: &[i32]) -> i32 {
945+ // Only a REGULAR band seeds the differential chain. A PNS band's `sf` is a
946+ // noise-energy value on its own accumulator and an intensity band's is a
947+ // stereo position — seeding global_gain from either desynchronizes every
948+ // scalefactor that follows.
949+ cbs.iter()
950+ .position(|&cb| cb != ZERO_HCB && cb < NOISE_HCB)
951+ .map(|sfb| sf[sfb])
952+ .unwrap_or(100)
953+}
954+
955+/// Bits to code the per-band scalefactors as `SCALEFACTOR_BOOK` deltas from a
956+/// running accumulator seeded at `gg`.
957+fn scalefactor_bits(cbs: &[u8], sf: &[i32], gg: i32) -> usize {
958+ let mut acc = gg;
959+ let mut noise = gg - 90;
960+ let mut noise_pcm = true;
961+ let mut is_pos = 0i32;
962+ let mut bits = 0usize;
963+ for (sfb, &cb) in cbs.iter().enumerate() {
964+ if cb == ZERO_HCB {
965+ continue;
966+ } else if cb >= crate::codebook::INTENSITY_HCB2 {
967+ let d = (sf[sfb] - is_pos).clamp(-60, 60);
968+ bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
969+ is_pos += d;
970+ } else if cb == NOISE_HCB {
971+ if noise_pcm {
972+ noise_pcm = false;
973+ let d = (sf[sfb] - noise).clamp(-256, 255);
974+ bits += 9;
975+ noise += d;
976+ } else {
977+ let d = (sf[sfb] - noise).clamp(-60, 60);
978+ bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
979+ noise += d;
980+ }
981+ } else {
982+ let d = (sf[sfb] - acc).clamp(-60, 60);
983+ bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize;
984+ acc += d;
985+ }
986+ }
987+ bits
988+}
989+
990+/// Runtime AVX2 availability (detected once).
991+#[cfg(all(feature = "simd", target_arch = "x86_64"))]
992+fn has_avx2() -> bool {
993+ static AVX2: OnceLock<bool> = OnceLock::new();
994+ *AVX2.get_or_init(|| std::is_x86_feature_detected!("avx2"))
995+}
996+
997+#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
998+fn has_avx512() -> bool {
999+ static AVX512: OnceLock<bool> = OnceLock::new();
1000+ *AVX512.get_or_init(|| std::is_x86_feature_detected!("avx512f"))
1001+}
1002+
1003+/// Quantize one band into `out`: `out[k] = sign[k]·min(round(pow[k]·scale), MAX_QUANT)`.
1004+/// This is the encoder's hottest kernel — the rate loop runs it ~11× per frame — so it
1005+/// has an AVX2 path. `pow·scale ≥ 0`, so `floor(v+0.5)` equals `round(v)`, making the
1006+/// vector path **bit-exact** with the scalar reference (verified by every gate test).
1007+fn quantize_band(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1008+ // SAFETY (all SIMD branches): entered only when the ISA is detected at runtime; the
1009+ // three slices share a length and vector bodies touch full lane-chunks, the remainder
1010+ // falling to the scalar tail. Every path is bit-exact with the scalar reference.
1011+ #[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
1012+ if has_avx512() {
1013+ unsafe { quantize_band_avx512(pow, sign, scale, out) };
1014+ return;
1015+ }
1016+ #[cfg(all(feature = "simd", target_arch = "x86_64"))]
1017+ if has_avx2() {
1018+ unsafe { quantize_band_avx2(pow, sign, scale, out) };
1019+ return;
1020+ }
1021+ quantize_band_scalar(pow, sign, scale, out);
1022+}
1023+
1024+fn quantize_band_scalar(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1025+ for k in 0..out.len() {
1026+ let q = ((pow[k] * scale).round() as i32).min(MAX_QUANT);
1027+ out[k] = sign[k] * q;
1028+ }
1029+}
1030+
1031+/// AVX2 quantize — four coefficients per iteration. Bit-exact with the scalar path
1032+/// (`floor(v+0.5) == round(v)` for `v ≥ 0`, and the clamp is applied before the
1033+/// f64→i32 narrowing so nothing overflows).
1034+#[cfg(all(feature = "simd", target_arch = "x86_64"))]
1035+#[target_feature(enable = "avx2")]
1036+unsafe fn quantize_band_avx2(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1037+ use std::arch::x86_64::*;
1038+ let n = out.len();
1039+ let vscale = _mm256_set1_pd(scale);
1040+ let vhalf = _mm256_set1_pd(0.5);
1041+ let vmax = _mm256_set1_pd(MAX_QUANT as f64);
1042+ let mut i = 0;
1043+ while i + 4 <= n {
1044+ let v = _mm256_mul_pd(_mm256_loadu_pd(pow.as_ptr().add(i)), vscale);
1045+ let r = _mm256_floor_pd(_mm256_add_pd(v, vhalf)); // = round(v), v ≥ 0
1046+ let qabs = _mm256_cvttpd_epi32(_mm256_min_pd(r, vmax)); // clamp then f64→i32
1047+ let s = _mm_loadu_si128(sign.as_ptr().add(i) as *const __m128i);
1048+ _mm_storeu_si128(
1049+ out.as_mut_ptr().add(i) as *mut __m128i,
1050+ _mm_mullo_epi32(qabs, s),
1051+ );
1052+ i += 4;
1053+ }
1054+ while i < n {
1055+ let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT);
1056+ out[i] = sign[i] * q;
1057+ i += 1;
1058+ }
1059+}
1060+
1061+/// AVX-512 quantize — eight coefficients per iteration (2× the AVX2 width). Bit-exact:
1062+/// for the quantizer's always-nonnegative input, `trunc(min(v+0.5, MAX+0.5))` equals
1063+/// `min(round(v), MAX)`, so a single truncating narrow does round+clamp in one step.
1064+/// Runtime-gated above AVX2; on AVX2-only hosts this path never runs (untested there —
1065+/// the math mirrors the AVX2 kernel exactly, and its tail is the shared scalar reference).
1066+#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))]
1067+#[target_feature(enable = "avx512f,avx2")]
1068+unsafe fn quantize_band_avx512(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) {
1069+ use std::arch::x86_64::*;
1070+ let n = out.len();
1071+ let vscale = _mm512_set1_pd(scale);
1072+ let vhalf = _mm512_set1_pd(0.5);
1073+ let vmaxph = _mm512_set1_pd(MAX_QUANT as f64 + 0.5); // clamp v+0.5 so trunc yields MAX
1074+ let mut i = 0;
1075+ while i + 8 <= n {
1076+ let v = _mm512_mul_pd(_mm512_loadu_pd(pow.as_ptr().add(i)), vscale);
1077+ let c = _mm512_min_pd(_mm512_add_pd(v, vhalf), vmaxph);
1078+ let qabs = _mm512_cvttpd_epi32(c); // 8 f64 → 8 i32; trunc = floor for c ≥ 0
1079+ let s = _mm256_loadu_si256(sign.as_ptr().add(i) as *const __m256i);
1080+ _mm256_storeu_si256(
1081+ out.as_mut_ptr().add(i) as *mut __m256i,
1082+ _mm256_mullo_epi32(qabs, s),
1083+ );
1084+ i += 8;
1085+ }
1086+ while i < n {
1087+ let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT);
1088+ out[i] = sign[i] * q;
1089+ i += 1;
1090+ }
1091+}
1092+
1093+/// AVX2 `Xpow` builder: `pow[i] = |x|^0.75` via `√|x|·√√|x|` (two vector sqrts), and
1094+/// `sign[i] = ±1` from the sign bit — four coefficients per iteration.
1095+#[cfg(all(feature = "simd", target_arch = "x86_64"))]
1096+#[target_feature(enable = "avx2")]
1097+unsafe fn xpow_avx2(spec: &[f32], pow: &mut [f64], sign: &mut [i32]) {
1098+ use std::arch::x86_64::*;
1099+ let n = spec.len();
1100+ let absmask = _mm256_castsi256_pd(_mm256_set1_epi64x(0x7fff_ffff_ffff_ffffu64 as i64));
1101+ let one = _mm256_set1_pd(1.0);
1102+ let mut i = 0;
1103+ while i + 4 <= n {
1104+ let x = _mm256_cvtps_pd(_mm_loadu_ps(spec.as_ptr().add(i))); // 4 f32 → 4 f64
1105+ let a = _mm256_and_pd(x, absmask); // |x|
1106+ let s = _mm256_sqrt_pd(a); // |x|^½
1107+ _mm256_storeu_pd(pow.as_mut_ptr().add(i), _mm256_mul_pd(s, _mm256_sqrt_pd(s)));
1108+ // ±1.0 carrying x's sign bit → i32 (x=0 gives +1; harmless, pow is 0).
1109+ let signed = _mm256_or_pd(one, _mm256_andnot_pd(absmask, x));
1110+ _mm_storeu_si128(
1111+ sign.as_mut_ptr().add(i) as *mut __m128i,
1112+ _mm256_cvttpd_epi32(signed),
1113+ );
1114+ i += 4;
1115+ }
1116+ while i < n {
1117+ let s = (spec[i].abs() as f64).sqrt();
1118+ pow[i] = s * s.sqrt();
1119+ sign[i] = if spec[i] < 0.0 { -1 } else { 1 };
1120+ }
1121+}
1122+
1123+/// **Deterministic work counters** (feature `lab`) — the PRIMARY evidence for any
1124+/// gate's speed half, per `codec-measurement` §15.
1125+///
1126+/// A counter is immune to scheduler drift, needs one run, and SIZES the effect;
1127+/// a clock at these magnitudes cannot be promoted to a verdict no matter how many
1128+/// pairs it gets. The gate-calculator's `work` column is fed from here.
1129+///
1130+/// Counts the rate loop's exact-coder evaluations — the encoder's dominant inner
1131+/// cost and precisely the quantity a psy arm moves, because changing the offsets
1132+/// changes how many bases the loop must try.
1133+#[cfg(feature = "lab")]
1134+pub mod work {
1135+ use std::sync::atomic::{AtomicU64, Ordering};
1136+
1137+ // GLOBAL, not thread-local. `encode_stream` fans frames out across worker
1138+ // threads, so a thread-local counter is drained on the main thread AFTER the
1139+ // workers have exited and reads **zero** — which is exactly what the first
1140+ // harvest reported (`WORK NULL: 0 vs 0`). A counter that reads flat is a
1141+ // defect report, not reassurance (`codec-measurement`, order of instruments).
1142+ static CODE_FRAME_EVALS: AtomicU64 = AtomicU64::new(0);
1143+ static QUANT_BANDS: AtomicU64 = AtomicU64::new(0);
1144+
1145+ #[inline]
1146+ pub(crate) fn bump_code_frame() {
1147+ CODE_FRAME_EVALS.fetch_add(1, Ordering::Relaxed);
1148+ }
1149+
1150+ #[inline]
1151+ pub(crate) fn bump_quant_bands(n: u64) {
1152+ QUANT_BANDS.fetch_add(n, Ordering::Relaxed);
1153+ }
1154+
1155+ /// Read and clear both counters.
1156+ ///
1157+ /// `Relaxed` is sufficient: these are pure counters, never used to order
1158+ /// other memory, and the harvest reads them only after `finish()` has joined
1159+ /// every worker — so the joins provide the happens-before edge.
1160+ pub fn take() -> (u64, u64) {
1161+ (
1162+ CODE_FRAME_EVALS.swap(0, Ordering::Relaxed),
1163+ QUANT_BANDS.swap(0, Ordering::Relaxed),
1164+ )
1165+ }
1166+}
1167+
1168+#[cfg(not(feature = "lab"))]
1169+mod work {
1170+ #[inline]
1171+ pub(crate) fn bump_code_frame() {}
1172+ #[inline]
1173+ pub(crate) fn bump_quant_bands(_: u64) {}
1174+}
1175+
1176+/// Shared coder body: quantize the frame into the caller-owned `quant` (per-band
1177+/// scalefactors `sf`, which cover the whole spectrum so no pre-zeroing is needed),
1178+/// pick per-band codebooks, and return (codebooks, ICS body bits, max_sfb). Splitting
1179+/// this out lets the rate loop reuse one buffer instead of allocating per candidate.
1180+fn code_core(xp: &Xpow, swb: &[u16], sf: &[i32], quant: &mut [i32]) -> (Vec<u8>, usize, usize) {
1181+ work::bump_code_frame();
1182+ let num_swb = swb.len() - 1;
1183+ work::bump_quant_bands((swb.len() - 1) as u64);
1184+ let scale = scale_table();
1185+ for sfb in 0..num_swb {
1186+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1187+ let sc = scale[sf[sfb].clamp(0, 255) as usize];
1188+ quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut quant[s..e]);
1189+ }
1190+ let mut max_sfb = 0usize;
1191+ for sfb in 0..num_swb {
1192+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1193+ if quant[s..e].iter().any(|&q| q != 0) {
1194+ max_sfb = sfb + 1;
1195+ }
1196+ }
1197+ let mut cbs = Vec::with_capacity(max_sfb);
1198+ let mut spec_bits = 0usize;
1199+ for sfb in 0..max_sfb {
1200+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1201+ let (cb, bits) = best_codebook_for_band(quant, s, e);
1202+ cbs.push(cb);
1203+ spec_bits += bits;
1204+ }
1205+ let gg = global_gain(&cbs, sf);
1206+ // global_gain(8) + ics_info(~11) + 3 flag bits + sections + scalefactors + spectrum.
1207+ let body = 8 + 11 + 3 + section_bits(&cbs) + scalefactor_bits(&cbs, sf, gg) + spec_bits;
1208+ (cbs, body, max_sfb)
1209+}
1210+
1211+/// Owned-buffer wrapper over [`code_core`] for the one-shot callers (final coding).
1212+fn code_frame(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec<u8>, usize, usize, Vec<i32>) {
1213+ let mut quant = vec![0i32; xp.len()];
1214+ let (cbs, body, max_sfb) = code_core(xp, swb, sf, &mut quant);
1215+ (cbs, body, max_sfb, quant)
1216+}
1217+
1218+/// The smallest common `base` such that no band clamps its loudest coefficient
1219+/// past `MAX_QUANT` (each band's own no-clamp floor, minus that band's offset).
1220+fn min_base(xp: &Xpow, swb: &[u16], offsets: &[i32]) -> i32 {
1221+ let num_swb = swb.len() - 1;
1222+ let mut floor = 0i32;
1223+ for sfb in 0..num_swb {
1224+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1225+ let maxp = xp.max_pow(s, e); // = (max|x|)^0.75
1226+ if maxp <= 1e-9 {
1227+ continue;
1228+ }
1229+ let min_sf = (100.0 - (MAX_QUANT as f64 / maxp).log2() / 0.1875).ceil() as i32;
1230+ floor = floor.max(min_sf - offsets[sfb]);
1231+ }
1232+ floor.clamp(0, 255)
1233+}
1234+
1235+/// Fast body-bit estimate at a candidate `base`: quantize (cheap) and price each
1236+/// coefficient from the `coef_bits` table — no codebook search. Monotone in `base`,
1237+/// so it seeds the search; the exact refinement corrects it.
1238+fn estimate_bits(xp: &Xpow, swb: &[u16], offsets: &[i32], base: i32) -> usize {
1239+ let scale = scale_table();
1240+ let ct = coef_bits();
1241+ let num_swb = swb.len() - 1;
1242+ let mut bits = 22usize; // global_gain + ics_info + flags, approx
1243+ let mut qbuf = [0i32; 128]; // one band (max long SWB width is 96)
1244+ for sfb in 0..num_swb {
1245+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1246+ let w = e - s;
1247+ let sc = scale[(base + offsets[sfb]).clamp(0, 255) as usize];
1248+ quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut qbuf[..w]);
1249+ let mut band = 0usize;
1250+ let mut nonzero = false;
1251+ for &q in &qbuf[..w] {
1252+ let m = q.unsigned_abs() as usize;
1253+ if m != 0 {
1254+ nonzero = true;
1255+ band += ct[m] as usize;
1256+ }
1257+ }
1258+ if nonzero {
1259+ bits += 9 + band; // ~section + scalefactor + spectrum for the band
1260+ }
1261+ }
1262+ bits
1263+}
1264+
1265+/// The smallest common `base` (≥ the no-clamp floor) whose ICS body fits
1266+/// `target_bits` — finest quality within budget. A fast estimate seeds the search;
1267+/// the exact coder then walks to the true boundary (identical to a full search, but
1268+/// only a couple of exact evaluations instead of eight). Body bits fall as `base`
1269+/// rises.
1270+fn rate_loop(xp: &Xpow, swb: &[u16], offsets: &[i32], target_bits: usize) -> i32 {
1271+ let min_b = min_base(xp, swb, offsets);
1272+ // Phase 1: binary-search the cheap estimate.
1273+ let (mut lo, mut hi) = (min_b, 255i32);
1274+ while lo < hi {
1275+ let mid = (lo + hi) / 2;
1276+ if estimate_bits(xp, swb, offsets, mid) <= target_bits {
1277+ hi = mid;
1278+ } else {
1279+ lo = mid + 1;
1280+ }
1281+ }
1282+ // Phase 2: refine to the exact smallest fitting base with the real coder, reusing
1283+ // one quant buffer across the (few) exact evaluations.
1284+ let mut quant = vec![0i32; xp.len()];
1285+ let mut exact =
1286+ |b: i32| code_core(xp, swb, &scalefactors(offsets, b), &mut quant).1 <= target_bits;
1287+ let mut base = lo;
1288+ if exact(base) {
1289+ while base > min_b && exact(base - 1) {
1290+ base -= 1;
1291+ }
1292+ } else {
1293+ while base < 255 && !exact(base) {
1294+ base += 1;
1295+ }
1296+ }
1297+ base
1298+}
1299+
1300+/// section_data (single group, long block): 4-bit codebook + 5-bit run-length
1301+/// increments (esc = 31 continues the run).
1302+fn write_sections(w: &mut BitWriter, cbs: &[u8]) {
1303+ let esc = 31u32;
1304+ let mut k = 0usize;
1305+ while k < cbs.len() {
1306+ let cb = cbs[k];
1307+ let mut len = 1usize;
1308+ while k + len < cbs.len() && cbs[k + len] == cb {
1309+ len += 1;
1310+ }
1311+ w.write(cb as u32, 4);
1312+ let mut l = len as u32;
1313+ while l >= esc {
1314+ w.write(esc, 5);
1315+ l -= esc;
1316+ }
1317+ w.write(l, 5);
1318+ k += len;
1319+ }
1320+}
1321+
1322+/// scale_factor_data: each coded band's scalefactor as a `SCALEFACTOR_BOOK` delta
1323+/// from a running accumulator seeded at `gg` (matching the decoder).
1324+fn write_scalefactors(w: &mut BitWriter, cbs: &[u8], sf: &[i32], gg: i32) {
1325+ // THREE independent accumulators, exactly as `decode::read_scalefactors`
1326+ // maintains them. Folding PNS or intensity values into the regular chain
1327+ // desynchronizes every later band, which decodes as garbage rather than as a
1328+ // slightly wrong gain.
1329+ let mut acc = gg;
1330+ let mut noise = gg - 90;
1331+ let mut noise_pcm = true;
1332+ let mut is_pos = 0i32;
1333+ for (sfb, &cb) in cbs.iter().enumerate() {
1334+ if cb == ZERO_HCB {
1335+ continue;
1336+ } else if cb >= crate::codebook::INTENSITY_HCB2 {
1337+ let d = (sf[sfb] - is_pos).clamp(-60, 60);
1338+ let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1339+ w.write(code, len as u32);
1340+ is_pos += d;
1341+ } else if cb == NOISE_HCB {
1342+ if noise_pcm {
1343+ // The first PNS band is a 9-bit PCM delta, not a Huffman one.
1344+ noise_pcm = false;
1345+ let d = (sf[sfb] - noise).clamp(-256, 255);
1346+ w.write((d + 256) as u32, 9);
1347+ noise += d;
1348+ } else {
1349+ let d = (sf[sfb] - noise).clamp(-60, 60);
1350+ let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1351+ w.write(code, len as u32);
1352+ noise += d;
1353+ }
1354+ } else {
1355+ let d = (sf[sfb] - acc).clamp(-60, 60);
1356+ let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize);
1357+ w.write(code, len as u32);
1358+ acc += d;
1359+ }
1360+ }
1361+}
1362+
1363+/// **Arm A6 — Perceptual Noise Substitution.**
1364+///
1365+/// Replace a noise-like band's coefficients with a single transmitted *energy*;
1366+/// the decoder refills it with scaled random noise (`decode::fill_noise`). The
1367+/// band costs a scalefactor instead of a spectrum, which at low rates is the
1368+/// difference between coding a band and zeroing it.
1369+///
1370+/// The P0 baseline is the motivation: `speech-noisy` and `noise-like` sit at
1371+/// 99%+ audible from 64-128k and only clear at 192k — broadband noise has no
1372+/// maskers to hide under and is unaffordable, which is exactly the problem PNS
1373+/// exists to solve.
1374+///
1375+/// The gate is deliberately conservative on all three axes, because PNS destroys
1376+/// phase and is audibly destructive on a harmonic band (the `music-tonal`
1377+/// anti-class):
1378+///
1379+/// * **frequency** — only above `PNS_MIN_HZ`; PNS on the bass is never right,
1380+/// * **tonality** — only bands the SFM calls noise-like,
1381+/// * **energy** — only bands actually carrying signal.
1382+///
1383+/// Returns the noise-energy value to transmit for each substituted band.
1384+/// `fill_noise` produces band energy `2^(ne/2)`, so `ne = 2*log2(E)`.
1385+fn pns_bands(
1386+ spec: &[f32],
1387+ swb: &[u16],
1388+ sample_rate: u32,
1389+ tonality: &[f32],
1390+ max_sfb: usize,
1391+) -> Vec<Option<i32>> {
1392+ const PNS_MIN_HZ: f64 = 4000.0;
1393+ const PNS_MAX_TONALITY: f32 = 0.10;
1394+ /// A frame this tonal overall gets NO PNS at all, whatever individual bands
1395+ /// say. See the band-level trap below.
1396+ const PNS_MAX_FRAME_TONALITY: f32 = 0.15;
1397+ /// A band must carry at least this fraction of the frame's MEAN band energy
1398+ /// to be worth substituting — population-relative (law 1), not absolute.
1399+ const PNS_MIN_ENERGY_FRAC: f64 = 0.5;
1400+
1401+ let num_swb = swb.len() - 1;
1402+ let mut out = vec![None; num_swb];
1403+
1404+ // Band energies once, and the frame's energy-weighted tonality.
1405+ let mut energies = vec![0f64; num_swb];
1406+ for sfb in 0..num_swb {
1407+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1408+ energies[sfb] = spec[s..e.min(spec.len())]
1409+ .iter()
1410+ .map(|&x| (x as f64) * (x as f64))
1411+ .sum();
1412+ }
1413+ let total: f64 = energies.iter().sum::<f64>() + 1e-9;
1414+ let frame_tonality =
1415+ (0..num_swb).map(|i| energies[i] * tonality[i] as f64).sum::<f64>() / total;
1416+
1417+ // **The band-level trap, measured.** A near-EMPTY band has a flat spectrum,
1418+ // so its spectral flatness measure reads as maximally *noise-like* — SFM
1419+ // cannot distinguish "broadband noise" from "almost nothing". A band-only
1420+ // gate therefore substitutes noise into the empty bands surrounding a pure
1421+ // tone, which is how the first version of this fired on a 6 kHz sine.
1422+ //
1423+ // Two guards, because they fail in different directions: the frame-level veto
1424+ // refuses tonal CONTENT outright, and the relative energy floor refuses
1425+ // individual bands with nothing in them.
1426+ if frame_tonality as f32 > PNS_MAX_FRAME_TONALITY {
1427+ return out;
1428+ }
1429+ let mean_band = total / num_swb as f64;
1430+
1431+ for sfb in 0..num_swb.min(max_sfb) {
1432+ let lo_hz = swb[sfb] as f64 * sample_rate as f64 * 0.5 / FRAME_LEN as f64;
1433+ if lo_hz < PNS_MIN_HZ || tonality[sfb] > PNS_MAX_TONALITY {
1434+ continue;
1435+ }
1436+ let energy = energies[sfb];
1437+ if energy <= 1.0 || energy < mean_band * PNS_MIN_ENERGY_FRAC {
1438+ continue; // nothing meaningful there to substitute
1439+ }
1440+ let ne = (2.0 * energy.log2()).round() as i32;
1441+ out[sfb] = Some(ne.clamp(-100, 255));
1442+ }
1443+ out
1444+}
1445+
1446+/// spectral_data: per regular SFB, code coefficient tuples with the band's book.
1447+fn write_spectrum(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) {
1448+ for (sfb, &cb) in cbs.iter().enumerate() {
1449+ // ZERO, NOISE (PNS) and intensity bands carry no spectral data — their
1450+ // whole point is that the coefficients are not transmitted.
1451+ if cb == ZERO_HCB || cb >= NOISE_HCB {
1452+ continue;
1453+ }
1454+ let dim = CODEBOOKS[cb as usize].dim as usize;
1455+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1456+ let mut i = s;
1457+ while i + dim <= e {
1458+ spectral_emit(cb as usize, &quant[i..i + dim], w);
1459+ i += dim;
1460+ }
1461+ }
1462+}
1463+
1464+/// Encode one channel as a single_channel_element for a long or transition block
1465+/// (`seq` ∈ {OnlyLong, LongStart, LongStop}): psy offsets → rate loop over the
1466+/// common base → per-band scalefactors → coded ICS.
1467+#[allow(clippy::too_many_arguments)]
1468+fn encode_channel_element(
1469+ w: &mut BitWriter,
1470+ tag: u32,
1471+ spec: &[f32],
1472+ swb: &[u16],
1473+ seq: WindowSequence,
1474+ sample_rate: u32,
1475+ target_bits: usize,
1476+ cur_kbd: bool,
1477+ psy: PsyCfg,
1478+ elem_id: u32,
1479+) {
1480+ // Pass 1, un-filtered: the TNS span depends on max_sfb, which only exists
1481+ // after quantization. This pass exists to learn it.
1482+ let offsets0 = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr);
1483+ let xp0 = Xpow::new(spec);
1484+ let base0 = rate_loop(&xp0, swb, &offsets0, target_bits);
1485+ let sf0 = scalefactors(&offsets0, base0);
1486+ let (cbs0, _, max_sfb0, quant0) = code_frame(&xp0, swb, &sf0);
1487+
1488+ // Arm A3. Only engage when the coded range already reaches TNS_MAX_LONG, so
1489+ // the decoder's span `min(TNS_MAX_LONG, max_sfb)` is pinned to TNS_MAX_LONG
1490+ // on BOTH sides regardless of what the re-quantization does to max_sfb. The
1491+ // alternative (span depending on a max_sfb that pass 2 can move) is a
1492+ // bitstream desync waiting to happen.
1493+ let fs_index = crate::sf_index_for_rate(sample_rate).unwrap_or(4);
1494+ let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
1495+ let mut tns: Option<TnsEnc> = None;
1496+ // ARM A3 ROUTING GATE. Spectral LPC prediction gain alone is NOT a transient
1497+ // detector: a peaky TONAL spectrum predicts just as well as an impulsive one,
1498+ // so a gain-only gate fires on sustained content, where temporal noise
1499+ // shaping has nothing to shape and simply costs bits. Measured (PEAQ, vs the
1500+ // previous default): tonal -1.02, mixed -1.14, quiet -1.05, while percussive
1501+ // moved only -0.01. It was firing almost exclusively on the wrong content.
1502+ //
1503+ // The fix is to require the frame to be transient-ADJACENT: only the
1504+ // LongStart / LongStop frames that bracket a detected attack. Those are
1505+ // exactly the long blocks that carry pre-echo, and the window sequence
1506+ // already names them, so the gate is free.
1507+ let tns_frame_ok = seq != WindowSequence::OnlyLong;
1508+ let (cbs, sf, max_sfb, quant) = if psy.tns && tns_frame_ok && max_sfb0 >= tns_max {
1509+ let mut filtered = spec.to_vec();
1510+ match tns_analyze_long(&mut filtered, swb, fs_index, max_sfb0) {
1511+ Some(t) => {
1512+ let offsets = perceptual_offsets(&filtered, swb, sample_rate, psy.tonality_smr);
1513+ let xp = Xpow::new(&filtered);
1514+ let base = rate_loop(&xp, swb, &offsets, target_bits);
1515+ let sf = scalefactors(&offsets, base);
1516+ let (mut cbs, _, msfb, quant) = code_frame(&xp, swb, &sf);
1517+ // Hold max_sfb at or above tns_max, padding with ZERO bands, so
1518+ // the decoder's TNS span is exactly the one we filtered.
1519+ let msfb = msfb.max(tns_max);
1520+ cbs.resize(msfb, ZERO_HCB);
1521+ tns = Some(t);
1522+ (cbs, sf, msfb, quant)
1523+ }
1524+ None => (cbs0, sf0, max_sfb0, quant0),
1525+ }
1526+ } else {
1527+ (cbs0, sf0, max_sfb0, quant0)
1528+ };
1529+ // Arm A6 — PNS. Substituted bands trade their spectrum for one energy value.
1530+ //
1531+ // Skipped when TNS fired: the decoder fills noise BEFORE inverse-filtering,
1532+ // so with TNS active the transmitted energy would have to be expressed in the
1533+ // filtered domain. That combination is not yet validated, and a wrong energy
1534+ // there is not a small error - it is a band of noise at the wrong level.
1535+ let (mut cbs, mut sf) = (cbs, sf);
1536+ if psy.pns && tns.is_none() {
1537+ let ton = band_tonality(spec, swb, 1, FRAME_LEN);
1538+ for (b, ne) in pns_bands(spec, swb, sample_rate, &ton, max_sfb)
1539+ .into_iter()
1540+ .enumerate()
1541+ {
1542+ if let (Some(ne), Some(cb)) = (ne, cbs.get_mut(b)) {
1543+ if *cb != ZERO_HCB && *cb < NOISE_HCB {
1544+ *cb = NOISE_HCB;
1545+ sf[b] = ne;
1546+ }
1547+ }
1548+ }
1549+ }
1550+ let gg = global_gain(&cbs, &sf);
1551+
1552+ w.write(elem_id, 3);
1553+ w.write(tag, 4);
1554+ w.write(gg as u32, 8);
1555+ let info = IcsInfo {
1556+ window_sequence: seq,
1557+ window_shape_kbd: cur_kbd,
1558+ max_sfb: max_sfb as u8,
1559+ num_windows: 1,
1560+ num_window_groups: 1,
1561+ window_group_length: vec![1],
1562+ num_swb: swb.len() - 1,
1563+ };
1564+ encode_ics_info(w, &info);
1565+ write_sections(w, &cbs);
1566+ write_scalefactors(w, &cbs, &sf, gg);
1567+ w.write(0, 1); // pulse_data_present
1568+ match &tns {
1569+ Some(t) => {
1570+ w.write(1, 1); // tns_data_present
1571+ write_tns_long(w, t);
1572+ }
1573+ None => w.write(0, 1),
1574+ }
1575+ w.write(0, 1); // gain_control_data_present
1576+ write_spectrum(w, &quant, &cbs, swb);
1577+}
1578+
1579+
1580+// ---------------------------------------------------------------------------
1581+// Arm A3 (Rung 3) — Temporal Noise Shaping.
1582+//
1583+// The AAC tool for pre-echo, and a large part of why AAC beats MP3 on speech.
1584+// The decoder has implemented it since day one (`decode::apply_tns`); the encoder
1585+// emitted `tns_data_present = 0` at all three sites.
1586+//
1587+// The decoder runs an ALL-POLE (synthesis) filter over the spectrum:
1588+// orig[n] = resid[n] - SUM_k lpc[k] * orig[n-k]
1589+// so the encoder must run the matching ALL-ZERO (analysis) filter:
1590+// resid[n] = orig[n] + SUM_k lpc[k] * orig[n-k]
1591+// with the state holding past *inputs* (the original spectrum), not past outputs.
1592+// Getting that inversion backwards does not sound slightly worse; it diverges.
1593+// ---------------------------------------------------------------------------
1594+
1595+/// One TNS filter the encoder decided to apply, in emit form.
1596+#[derive(Debug, Clone)]
1597+pub(crate) struct TnsEnc {
1598+ /// Span in scalefactor bands, counted down from the top.
1599+ pub length: usize,
1600+ pub order: usize,
1601+ /// Quantized PARCOR indices (4-bit two's complement, `coef_res = 1`).
1602+ pub idx: Vec<i32>,
1603+ /// The de-quantized PARCOR values the decoder will reconstruct — the encoder
1604+ /// must filter with *these*, not with the unquantized ones, or encoder and
1605+ /// decoder run different filters.
1606+ pub parcor: Vec<f32>,
1607+}
1608+
1609+/// Coefficient resolution we emit: `coef_res = 1` (4-bit), `coef_compress = 0`.
1610+/// The widest grid AAC-LC offers, so quantization error in the filter itself is
1611+/// as small as the syntax allows.
1612+const TNS_COEF_RES: u32 = 1;
1613+const TNS_COEF_BITS: u32 = 4;
1614+/// Max order for AAC-LC long blocks (the syntax allows 5 bits; 12 is the ISO cap).
1615+const TNS_MAX_ORDER: usize = 12;
1616+/// Prediction gain below which TNS is not worth its bits. PROVISIONAL — the
1617+/// classic value; the calculator has not fitted it.
1618+const TNS_MIN_GAIN: f64 = 1.4;
1619+
1620+/// Quantize one PARCOR value to the 4-bit grid and return `(index, dequantized)`.
1621+///
1622+/// Exact inverse of the decoder's dequantizer, including its **asymmetric**
1623+/// scale factors (`iqfac` for non-negative, `iqfac_m` for negative) — a single
1624+/// shared factor would round half the coefficients to the wrong index.
1625+fn quantize_parcor(p: f32) -> (i32, f32) {
1626+ use std::f32::consts::PI;
1627+ let res_bits = 3 + TNS_COEF_RES;
1628+ let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0);
1629+ let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0);
1630+ let t = p.clamp(-0.999, 0.999).asin();
1631+ let lo = -(1i32 << (TNS_COEF_BITS - 1));
1632+ let hi = (1i32 << (TNS_COEF_BITS - 1)) - 1;
1633+ let c = if t >= 0.0 {
1634+ (t * iqfac).round() as i32
1635+ } else {
1636+ (t * iqfac_m).round() as i32
1637+ }
1638+ .clamp(lo, hi);
1639+ // Reconstruct exactly as the decoder will.
1640+ let t_back = if c >= 0 {
1641+ c as f32 / iqfac
1642+ } else {
1643+ c as f32 / iqfac_m
1644+ };
1645+ (c, t_back.sin())
1646+}
1647+
1648+/// PARCOR (reflection coefficients) -> LPC, matching `decode::parcor_to_lpc`.
1649+fn parcor_to_lpc_enc(parcor: &[f32]) -> Vec<f32> {
1650+ let order = parcor.len();
1651+ let mut lpc = vec![0f32; order + 1];
1652+ lpc[0] = 1.0;
1653+ for m in 1..=order {
1654+ let mut tmp = lpc.clone();
1655+ for i in 1..m {
1656+ tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i];
1657+ }
1658+ lpc[..m].copy_from_slice(&tmp[..m]);
1659+ lpc[m] = parcor[m - 1];
1660+ }
1661+ lpc
1662+}
1663+
1664+/// Levinson-Durbin over `spec[start..end]`, returning `(parcor, prediction_gain)`.
1665+fn spectral_parcor(spec: &[f32], start: usize, end: usize, order: usize) -> (Vec<f32>, f64) {
1666+ let n = end.saturating_sub(start);
1667+ if n <= order + 1 {
1668+ return (Vec::new(), 1.0);
1669+ }
1670+ let x = &spec[start..end];
1671+ let mut r = vec![0f64; order + 1];
1672+ for (lag, slot) in r.iter_mut().enumerate() {
1673+ let mut acc = 0f64;
1674+ for i in 0..n - lag {
1675+ acc += x[i] as f64 * x[i + lag] as f64;
1676+ }
1677+ *slot = acc;
1678+ }
1679+ if r[0] <= 1e-12 {
1680+ return (Vec::new(), 1.0);
1681+ }
1682+ let r0 = r[0] * 1.0001; // white-noise correction
1683+ r[0] = r0;
1684+ let mut a = vec![0f64; order + 1];
1685+ let mut parcor = Vec::with_capacity(order);
1686+ let mut err = r0;
1687+ for i in 1..=order {
1688+ let mut acc = r[i];
1689+ for j in 1..i {
1690+ acc -= a[j] * r[i - j];
1691+ }
1692+ let k = acc / err;
1693+ if !k.is_finite() || k.abs() >= 0.999 {
1694+ break;
1695+ }
1696+ let prev: Vec<f64> = a[1..i].to_vec();
1697+ for j in 1..i {
1698+ a[j] = prev[j - 1] - k * prev[i - j - 1];
1699+ }
1700+ a[i] = k;
1701+ parcor.push(k as f32);
1702+ err *= 1.0 - k * k;
1703+ if err <= 1e-12 {
1704+ break;
1705+ }
1706+ }
1707+ (parcor, r0 / err.max(1e-12))
1708+}
1709+
1710+/// **The Rung 3 gate + arm.** Decide whether to apply TNS to a long block and, if
1711+/// so, filter `spec` in place and return the data to emit.
1712+///
1713+/// `max_sfb_hint` must be the `max_sfb` that will be written, because the decoder
1714+/// filters over `min(TNS_MAX_LONG, max_sfb)` bands — encoder and decoder must
1715+/// agree on the span exactly or the inverse filter runs over the wrong region.
1716+///
1717+/// Returns `None` when the gate declines (prediction gain below threshold, span
1718+/// too short, or a degenerate fit), in which case `spec` is untouched and the
1719+/// caller emits `tns_data_present = 0` — the byte-identical fallback.
1720+pub(crate) fn tns_analyze_long(
1721+ spec: &mut [f32],
1722+ swb: &[u16],
1723+ fs_index: u8,
1724+ max_sfb: usize,
1725+) -> Option<TnsEnc> {
1726+ let num_swb = swb.len() - 1;
1727+ let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize;
1728+ let mmm = tns_max.min(max_sfb);
1729+ if mmm < 4 {
1730+ return None;
1731+ }
1732+ // One filter spanning the top of the coded range down to band `bottom`. The
1733+ // decoder derives `start`/`end` from `length` the same way.
1734+ let bottom = mmm / 4; // skip the lowest quarter: TNS on the bass is harmful
1735+ let length = num_swb.saturating_sub(bottom);
1736+ let start = swb[bottom.min(mmm)] as usize;
1737+ let end = swb[mmm] as usize;
1738+ if end <= start + TNS_MAX_ORDER + 1 {
1739+ return None;
1740+ }
1741+
1742+ let (parcor_raw, gain) = spectral_parcor(spec, start, end, TNS_MAX_ORDER);
1743+ if parcor_raw.is_empty() || gain < TNS_MIN_GAIN {
1744+ return None; // the gate: not worth its bits
1745+ }
1746+
1747+ // Quantize to the shipping 4-bit grid, and keep the DEQUANTIZED values —
1748+ // filtering with the unquantized ones would leave the decoder running a
1749+ // slightly different filter, which shows up as drift across the band.
1750+ let mut idx = Vec::with_capacity(parcor_raw.len());
1751+ let mut parcor = Vec::with_capacity(parcor_raw.len());
1752+ for &p in &parcor_raw {
1753+ let (c, dq) = quantize_parcor(p);
1754+ idx.push(c);
1755+ parcor.push(dq);
1756+ }
1757+ // Drop trailing zero-index coefficients: they cost 4 bits each and do nothing.
1758+ while idx.len() > 1 && *idx.last().unwrap() == 0 {
1759+ idx.pop();
1760+ parcor.pop();
1761+ }
1762+ let order = idx.len();
1763+ if order == 0 {
1764+ return None;
1765+ }
1766+
1767+ let lpc = parcor_to_lpc_enc(&parcor);
1768+
1769+ // The ANALYSIS filter (all-zero), upward direction, state = past inputs.
1770+ // Indexed rather than iterated: the filter reads and writes the same slice
1771+ // element each step, which an iterator form cannot express without a copy.
1772+ #[allow(clippy::needless_range_loop)]
1773+ let mut state = vec![0f32; order];
1774+ #[allow(clippy::needless_range_loop)]
1775+ for p in start..end {
1776+ let xn = spec[p];
1777+ let mut y = xn;
1778+ for j in 0..order {
1779+ y += state[j] * lpc[j + 1];
1780+ }
1781+ for j in (1..order).rev() {
1782+ state[j] = state[j - 1];
1783+ }
1784+ state[0] = xn;
1785+ spec[p] = y;
1786+ }
1787+
1788+ Some(TnsEnc {
1789+ length,
1790+ order,
1791+ idx,
1792+ parcor,
1793+ })
1794+}
1795+
1796+/// Emit `tns_data` for a long block (`n_filt` 2 bits, `length` 6, `order` 5).
1797+/// Mirrors `decode::parse_tns` exactly.
1798+pub(crate) fn write_tns_long(w: &mut BitWriter, tns: &TnsEnc) {
1799+ w.write(1, 2); // n_filt = 1
1800+ w.write(TNS_COEF_RES, 1); // coef_res
1801+ w.write(tns.length as u32, 6);
1802+ w.write(tns.order as u32, 5);
1803+ if tns.order > 0 {
1804+ w.write(0, 1); // direction: upward (low -> high)
1805+ w.write(0, 1); // coef_compress = 0
1806+ for &c in &tns.idx {
1807+ let masked = (c as u32) & ((1u32 << TNS_COEF_BITS) - 1);
1808+ w.write(masked, TNS_COEF_BITS);
1809+ }
1810+ }
1811+}
1812+
1813+// ---------------------------------------------------------------------------
1814+// Block switching (brick 5) — transient detection, window-sequence assignment,
1815+// and the short-block coding path (eight 128-bin windows, one group).
1816+// ---------------------------------------------------------------------------
1817+
1818+/// Flag each 1024-sample frame that contains a transient: a 128-sample sub-block
1819+/// whose energy leaps above the recent running average (an attack). Frame 0 is
1820+/// never flagged — nothing precedes it to open a LongStart transition from.
1821+///
1822+/// `pub(crate)` so [`crate::lab::signals`] can record what the *shipping*
1823+/// detector decides alongside the campaign's replacement signal — the
1824+/// gate-calculator's `shipped` column (arm A9).
1825+pub(crate) fn detect_transients(chan: &[f32], nframes: usize) -> Vec<bool> {
1826+ const RATIO: f64 = 10.0;
1827+ // (arm A9 replaces the guard below; see `detect_transients_relative`)
1828+ let mut flags = vec![false; nframes];
1829+ let mut avg = 0.0f64;
1830+ for (f, flag) in flags.iter_mut().enumerate() {
1831+ let mut attack = 1.0f64;
1832+ for sb in 0..8 {
1833+ let start = f * FRAME_LEN + sb * SHORT_HALF;
1834+ let e: f64 = (0..SHORT_HALF)
1835+ .map(|i| {
1836+ let x = chan.get(start + i).copied().unwrap_or(0.0) as f64;
1837+ x * x
1838+ })
1839+ .sum();
1840+ if avg > 1e-3 {
1841+ attack = attack.max(e / avg);
1842+ }
1843+ avg = 0.75 * avg + 0.25 * e;
1844+ }
1845+ if f > 0 && attack > RATIO {
1846+ *flag = true;
1847+ }
1848+ }
1849+ flags
1850+}
1851+
1852+/// Per-frame **population-relative** max attack ratio — the level-invariant
1853+/// replacement for [`detect_transients`]'s absolute `avg > 1e-3` guard (arm A9).
1854+///
1855+/// The running average is floored at a fraction of *this clip's own* mean
1856+/// sub-block energy, so both numerator and floor scale with level and the ratio
1857+/// is unchanged by a gain change. The shipping detector's absolute floor makes it
1858+/// blind on quiet content and, because the average decays 0.75× per sub-block, on
1859+/// sparse attacks over a quiet floor at *any* level.
1860+///
1861+/// Used by the Rung 0 shape gate as a transient veto; it is also the signal arm
1862+/// A9 will replace the detector's threshold with.
1863+pub(crate) fn frame_attack_ratios(chan: &[f32], nframes: usize) -> Vec<f32> {
1864+ let mut sub: Vec<f64> = Vec::with_capacity(nframes * 8);
1865+ for f in 0..nframes {
1866+ for sb in 0..8 {
1867+ let start = f * FRAME_LEN + sb * SHORT_HALF;
1868+ let e: f64 = (0..SHORT_HALF)
1869+ .map(|i| {
1870+ let x = chan.get(start + i).copied().unwrap_or(0.0) as f64;
1871+ x * x
1872+ })
1873+ .sum();
1874+ sub.push(e);
1875+ }
1876+ }
1877+ let mean_e = sub.iter().sum::<f64>() / sub.len().max(1) as f64;
1878+ let floor = (mean_e * 1e-3).max(f64::MIN_POSITIVE);
1879+
1880+ let mut avg = 0.0f64;
1881+ let mut out = Vec::with_capacity(nframes);
1882+ for f in 0..nframes {
1883+ let mut amax = 1.0f32;
1884+ for sb in 0..8 {
1885+ let e = sub[f * 8 + sb];
1886+ amax = amax.max((e / avg.max(floor)) as f32);
1887+ avg = 0.75 * avg + 0.25 * e;
1888+ }
1889+ out.push(amax);
1890+ }
1891+ out
1892+}
1893+
1894+/// **Arm A9 — the level-invariant transient detector.**
1895+///
1896+/// Same decision rule as [`detect_transients`] (`attack ratio > 10`), on a signal
1897+/// that is actually defined. The shipped detector guards its ratio with
1898+/// `avg > 1e-3` — an **absolute** energy floor — which has two consequences the
1899+/// P1 truth table pinned:
1900+///
1901+/// * the identical waveform 40 dB quieter stops being detected at all, and
1902+/// * because the running average decays 0.75x per sub-block, it falls under the
1903+/// floor across the quiet stretch between sparse attacks, so castanet-like
1904+/// content is missed **at any level** — measured: zero frames flagged on the
1905+/// percussive corpus class whose p95 attack ratio is ~30000x.
1906+///
1907+/// The ratio itself is already scale-invariant; only the guard was not. This
1908+/// version floors the running average relative to the clip's own mean sub-block
1909+/// energy instead, which is the law-1 form and leaves the threshold meaning what
1910+/// it says.
1911+///
1912+/// This is not merely a quality knob: arm A1 (short-block psy) can only reach
1913+/// frames that are coded as short blocks, so a detector that never fires makes A1
1914+/// unmeasurable. A9 is A1's prerequisite.
1915+pub(crate) fn detect_transients_relative(chan: &[f32], nframes: usize) -> Vec<bool> {
1916+ const RATIO: f32 = 10.0;
1917+ let ratios = frame_attack_ratios(chan, nframes);
1918+ (0..nframes)
1919+ .map(|f| f > 0 && ratios.get(f).copied().unwrap_or(1.0) > RATIO)
1920+ .collect()
1921+}
1922+
1923+/// Assign a valid AAC window sequence to each frame from the transient flags. A
1924+/// short run is bracketed by LongStart/LongStop; runs a single frame apart are
1925+/// merged (a lone gap can't be both a stop and a start).
1926+fn assign_sequences(transient: &[bool]) -> Vec<WindowSequence> {
1927+ use WindowSequence::*;
1928+ let n = transient.len();
1929+ let mut short = transient.to_vec();
1930+ for i in 1..n.saturating_sub(1) {
1931+ if !short[i] && short[i - 1] && short[i + 1] {
1932+ short[i] = true;
1933+ }
1934+ }
1935+ let mut seq = vec![OnlyLong; n];
1936+ let mut i = 0;
1937+ while i < n {
1938+ if short[i] {
1939+ let a = i;
1940+ while i < n && short[i] {
1941+ seq[i] = EightShort;
1942+ i += 1;
1943+ }
1944+ if a > 0 {
1945+ seq[a - 1] = LongStart;
1946+ }
1947+ if i < n {
1948+ seq[i] = LongStop;
1949+ }
1950+ } else {
1951+ i += 1;
1952+ }
1953+ }
1954+ seq
1955+}
1956+
1957+/// Cheapest codebook (and its bit cost) for one SFB across all short windows of a
1958+/// single group, matched to how the decoder reads it (per-SFB codebook, per-window
1959+/// coefficients).
1960+fn best_codebook_short(quant: &[i32], swb: &[u16], sfb: usize, nwin: usize) -> (u8, usize) {
1961+ let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize);
1962+ let mut maxq = 0u32;
1963+ for win in 0..nwin {
1964+ let base = win * SHORT_HALF;
1965+ for &q in &quant[base + s..base + e] {
1966+ maxq = maxq.max(q.unsigned_abs());
1967+ }
1968+ }
1969+ if maxq == 0 {
1970+ return (ZERO_HCB, 0);
1971+ }
1972+ let mut best = (ESC_HCB, usize::MAX);
1973+ for cb in 1..=11u8 {
1974+ let meta = &CODEBOOKS[cb as usize];
1975+ let dim = meta.dim as usize;
1976+ if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) {
1977+ continue;
1978+ }
1979+ let mut bits = 0usize;
1980+ let mut ok = true;
1981+ 'windows: for win in 0..nwin {
1982+ let base = win * SHORT_HALF;
1983+ let mut i = s;
1984+ while i < e {
1985+ match spectral_bits(cb as usize, &quant[base + i..base + i + dim]) {
1986+ Some(b) => bits += b,
1987+ None => {
1988+ ok = false;
1989+ break 'windows;
1990+ }
1991+ }
1992+ i += dim;
1993+ }
1994+ }
1995+ if ok && bits < best.1 {
1996+ best = (cb, bits);
1997+ }
1998+ }
1999+ best
2000+}
vendor/rusty_aac/src/error.rsadded+58 -0
@@ -0,0 +1,58 @@
1+//! The crate's dependency-free error type.
2+//!
3+//! [`Error::Again`] and [`Error::Eof`] follow EAGAIN-style pull semantics:
4+//! they are not failures. `Again` means "more input is required before output
5+//! can be produced" (feed more data, then pull again); `Eof` means "the stream
6+//! is finished and fully drained" (stop pulling). Everything else is a real
7+//! error.
8+
9+/// Crate-wide result alias.
10+pub type Result<T> = std::result::Result<T, Error>;
11+
12+/// All the ways AAC decoding/encoding can fail — or, for [`Error::Again`] /
13+/// [`Error::Eof`], signal normal stream flow control.
14+#[derive(Debug)]
15+#[non_exhaustive]
16+pub enum Error {
17+ /// A code path that is scaffolded but not yet implemented. Carries a short
18+ /// static label so logs point straight at the missing piece.
19+ Unimplemented(&'static str),
20+
21+ /// End of stream — the codec has no more data to give.
22+ Eof,
23+
24+ /// More input is required before output can be produced (codec drain/fill).
25+ Again,
26+
27+ /// The input bytes were malformed for AAC-LC.
28+ InvalidData(String),
29+
30+ /// A requested capability exists in concept but isn't supported here.
31+ Unsupported(String),
32+}
33+
34+impl Error {
35+ /// Convenience constructor for `InvalidData` from anything string-like.
36+ pub fn invalid(msg: impl Into<String>) -> Self {
37+ Error::InvalidData(msg.into())
38+ }
39+
40+ /// Convenience constructor for `Unsupported`.
41+ pub fn unsupported(msg: impl Into<String>) -> Self {
42+ Error::Unsupported(msg.into())
43+ }
44+}
45+
46+impl std::fmt::Display for Error {
47+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48+ match self {
49+ Error::Unimplemented(what) => write!(f, "not yet implemented: {what}"),
50+ Error::Eof => write!(f, "end of stream"),
51+ Error::Again => write!(f, "more input required"),
52+ Error::InvalidData(msg) => write!(f, "invalid data: {msg}"),
53+ Error::Unsupported(msg) => write!(f, "unsupported: {msg}"),
54+ }
55+ }
56+}
57+
58+impl std::error::Error for Error {}
vendor/rusty_aac/src/huffman.rsadded+116 -0
@@ -0,0 +1,116 @@
1+//! Generic canonical-prefix Huffman decoder for the AAC spectral and
2+//! scalefactor codebooks (ISO 14496-3 §4.A.3).
3+//!
4+//! Each codebook is two parallel `'static` arrays — `codes[i]` is the codeword
5+//! and `lens[i]` its bit length — exactly the form the spec/reference tables
6+//! ship in. Decoding reads bits MSB-first, accumulating until a `(len, code)`
7+//! pair matches; the codes are prefix-free, so the first match is the symbol.
8+//! `decode` returns the array index `i`, which the codebook layer unpacks into
9+//! spectral coefficients. O(maxlen·count) per codeword — codebooks are small,
10+//! so it is plenty fast and trivially verifiable.
11+
12+#![allow(dead_code)]
13+
14+use crate::{Error, Result};
15+
16+use crate::bits::BitReader;
17+
18+/// A Huffman codebook: parallel codeword / bit-length tables.
19+pub struct HuffBook {
20+ codes: &'static [u32],
21+ lens: &'static [u8],
22+ max_len: u8,
23+}
24+
25+impl HuffBook {
26+ pub const fn new(codes: &'static [u32], lens: &'static [u8]) -> HuffBook {
27+ let mut max = 0u8;
28+ let mut i = 0;
29+ while i < lens.len() {
30+ if lens[i] > max {
31+ max = lens[i];
32+ }
33+ i += 1;
34+ }
35+ HuffBook {
36+ codes,
37+ lens,
38+ max_len: max,
39+ }
40+ }
41+
42+ pub fn count(&self) -> usize {
43+ self.codes.len()
44+ }
45+
46+ /// The `(codeword, bit-length)` for symbol index `i` — the encoder side.
47+ pub fn code(&self, i: usize) -> (u32, u8) {
48+ (self.codes[i], self.lens[i])
49+ }
50+
51+ /// Decode the next codeword, returning its symbol index.
52+ pub fn decode(&self, r: &mut BitReader) -> Result<u16> {
53+ let mut code = 0u32;
54+ for len in 1..=self.max_len {
55+ code = (code << 1) | r.read_bit()?;
56+ for i in 0..self.codes.len() {
57+ if self.lens[i] == len && self.codes[i] == code {
58+ return Ok(i as u16);
59+ }
60+ }
61+ }
62+ Err(Error::invalid("aac: invalid Huffman codeword"))
63+ }
64+
65+ /// Kraft sum Σ 2^-len — 1.0 for a complete code, slightly less if incomplete.
66+ #[cfg(test)]
67+ pub fn kraft_sum(&self) -> f64 {
68+ self.lens.iter().map(|&l| 2f64.powi(-(l as i32))).sum()
69+ }
70+
71+ /// True if no codeword is a prefix of another.
72+ #[cfg(test)]
73+ pub fn is_prefix_free(&self) -> bool {
74+ for a in 0..self.codes.len() {
75+ for b in (a + 1)..self.codes.len() {
76+ let (la, ca) = (self.lens[a], self.codes[a]);
77+ let (lb, cb) = (self.lens[b], self.codes[b]);
78+ let (short_l, short_c, long_l, long_c) = if la <= lb {
79+ (la, ca, lb, cb)
80+ } else {
81+ (lb, cb, la, ca)
82+ };
83+ if long_c >> (long_l - short_l) == short_c {
84+ return false;
85+ }
86+ }
87+ }
88+ true
89+ }
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+
96+ // A tiny prefix-free book: index 0→"0", 1→"10", 2→"110", 3→"111".
97+ static TEST_CODES: &[u32] = &[0b0, 0b10, 0b110, 0b111];
98+ static TEST_LENS: &[u8] = &[1, 2, 3, 3];
99+
100+ #[test]
101+ fn decodes_prefix_free_sequence() {
102+ let book = HuffBook::new(TEST_CODES, TEST_LENS);
103+ // Stream 0 10 110 111 0 → indices 0 1 2 3 0
104+ // bits: 0 10 110 111 0 → 0101 1011 10.. = 0x5B 0x80
105+ let mut r = BitReader::new(&[0x5B, 0x80]);
106+ let got: Vec<u16> = (0..5).map(|_| book.decode(&mut r).unwrap()).collect();
107+ assert_eq!(got, vec![0, 1, 2, 3, 0]);
108+ }
109+
110+ #[test]
111+ fn structural_helpers() {
112+ let book = HuffBook::new(TEST_CODES, TEST_LENS);
113+ assert!((book.kraft_sum() - 1.0).abs() < 1e-12);
114+ assert!(book.is_prefix_free());
115+ }
116+}
vendor/rusty_aac/src/ics.rsadded+175 -0
@@ -0,0 +1,175 @@
1+//! `ics_info` — per-channel window/grouping configuration (ISO 14496-3
2+//! §4.4.2.1) and the derived short-window grouping.
3+
4+#![allow(dead_code)]
5+
6+use crate::{Error, Result};
7+
8+use crate::bits::BitReader;
9+use crate::swb::swb_offsets;
10+
11+/// AAC window sequence (transform block structure).
12+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13+pub enum WindowSequence {
14+ OnlyLong,
15+ LongStart,
16+ EightShort,
17+ LongStop,
18+}
19+
20+impl WindowSequence {
21+ fn from_bits(v: u32) -> WindowSequence {
22+ match v {
23+ 0 => WindowSequence::OnlyLong,
24+ 1 => WindowSequence::LongStart,
25+ 2 => WindowSequence::EightShort,
26+ _ => WindowSequence::LongStop,
27+ }
28+ }
29+
30+ pub fn is_short(self) -> bool {
31+ self == WindowSequence::EightShort
32+ }
33+
34+ /// The 2-bit window-sequence code (the encode side of `from_bits`).
35+ pub fn to_bits(self) -> u32 {
36+ match self {
37+ WindowSequence::OnlyLong => 0,
38+ WindowSequence::LongStart => 1,
39+ WindowSequence::EightShort => 2,
40+ WindowSequence::LongStop => 3,
41+ }
42+ }
43+}
44+
45+/// Parsed `ics_info` plus the derived grouping for this channel.
46+#[derive(Debug, Clone)]
47+pub struct IcsInfo {
48+ pub window_sequence: WindowSequence,
49+ /// Window shape for this block: false = sine, true = KBD.
50+ pub window_shape_kbd: bool,
51+ pub max_sfb: u8,
52+ /// Number of transform windows (8 for EIGHT_SHORT, else 1).
53+ pub num_windows: usize,
54+ /// Number of window groups.
55+ pub num_window_groups: usize,
56+ /// Windows per group (`num_window_groups` entries summing to `num_windows`).
57+ pub window_group_length: Vec<u8>,
58+ /// Number of scalefactor bands per window for this block type.
59+ pub num_swb: usize,
60+}
61+
62+/// Parse `ics_info` from the bitstream for sampling-frequency index `fs_index`.
63+pub fn parse_ics_info(r: &mut BitReader, fs_index: u8) -> Result<IcsInfo> {
64+ let _ics_reserved = r.read_bit()?;
65+ let window_sequence = WindowSequence::from_bits(r.read_bits(2)?);
66+ let window_shape_kbd = r.read_bool()?;
67+
68+ let (max_sfb, scale_factor_grouping) = if window_sequence.is_short() {
69+ let max_sfb = r.read_bits(4)? as u8;
70+ let sfg = r.read_bits(7)?;
71+ (max_sfb, Some(sfg))
72+ } else {
73+ let max_sfb = r.read_bits(6)? as u8;
74+ let predictor_data_present = r.read_bool()?;
75+ if predictor_data_present {
76+ // AAC-LC has no prediction; a set bit means a non-LC stream.
77+ return Err(Error::unsupported(
78+ "aac: predictor_data_present (non-LC profile) not supported",
79+ ));
80+ }
81+ (max_sfb, None)
82+ };
83+
84+ let (num_windows, num_window_groups, window_group_length) = match scale_factor_grouping {
85+ Some(sfg) => {
86+ // Each of the 7 grouping bits (MSB first) ties window i+1 to the
87+ // current group (1) or starts a new one (0).
88+ let mut groups = vec![1u8];
89+ for i in 0..7 {
90+ if (sfg >> (6 - i)) & 1 == 1 {
91+ *groups.last_mut().unwrap() += 1;
92+ } else {
93+ groups.push(1);
94+ }
95+ }
96+ (8, groups.len(), groups)
97+ }
98+ None => (1, 1, vec![1u8]),
99+ };
100+
101+ let num_swb = swb_offsets(!window_sequence.is_short(), fs_index).len() - 1;
102+
103+ Ok(IcsInfo {
104+ window_sequence,
105+ window_shape_kbd,
106+ max_sfb,
107+ num_windows,
108+ num_window_groups,
109+ window_group_length,
110+ num_swb,
111+ })
112+}
113+
114+#[cfg(test)]
115+mod tests {
116+ use super::*;
117+
118+ #[test]
119+ fn parses_only_long() {
120+ // ics_reserved(0) ws(00=OnlyLong) shape(0) max_sfb(49=110001) pred(0)
121+ // bits: 0 00 0 110001 0 → 0000 1100 010. = 0x0C 0x40
122+ let mut r = BitReader::new(&[0x0C, 0x40]);
123+ let info = parse_ics_info(&mut r, 4).unwrap();
124+ assert_eq!(info.window_sequence, WindowSequence::OnlyLong);
125+ assert!(!info.window_shape_kbd);
126+ assert_eq!(info.max_sfb, 49);
127+ assert_eq!(info.num_windows, 1);
128+ assert_eq!(info.num_window_groups, 1);
129+ assert_eq!(info.window_group_length, vec![1]);
130+ assert_eq!(info.num_swb, 49); // 44.1 kHz long
131+ }
132+
133+ #[test]
134+ fn parses_eight_short_all_grouped() {
135+ // ics_reserved(0) ws(10=EightShort) shape(1=KBD) max_sfb(13=1101)
136+ // sfg(1111111 → one group of 8)
137+ // bits: 0 10 1 1101 1111111 → 0101 1101 1111 111. = 0x5D 0xFE
138+ let mut r = BitReader::new(&[0x5D, 0xFE]);
139+ let info = parse_ics_info(&mut r, 3).unwrap();
140+ assert_eq!(info.window_sequence, WindowSequence::EightShort);
141+ assert!(info.window_shape_kbd);
142+ assert_eq!(info.max_sfb, 13);
143+ assert_eq!(info.num_windows, 8);
144+ assert_eq!(info.num_window_groups, 1);
145+ assert_eq!(info.window_group_length, vec![8]);
146+ assert_eq!(info.num_swb, 14); // 48 kHz short
147+ }
148+
149+ #[test]
150+ fn parses_eight_short_split_groups() {
151+ // sfg = 0b0101010 → bits decide grouping: produces several groups.
152+ // ics_reserved(0) ws(10) shape(0) max_sfb(0000) sfg(0101010)
153+ // bits: 0 10 0 0000 0101010 → 0100 0000 0101 0100 = 0x40 0x54
154+ let mut r = BitReader::new(&[0x40, 0x54]);
155+ let info = parse_ics_info(&mut r, 3).unwrap();
156+ assert_eq!(info.num_windows, 8);
157+ // 0,1,0,1,0,1,0 grouping bits → groups: [1,2,2,2,1] (sum 8).
158+ assert_eq!(
159+ info.window_group_length
160+ .iter()
161+ .map(|&x| x as usize)
162+ .sum::<usize>(),
163+ 8
164+ );
165+ assert_eq!(info.num_window_groups, info.window_group_length.len());
166+ }
167+
168+ #[test]
169+ fn rejects_prediction() {
170+ // OnlyLong with predictor_data_present=1 → unsupported (non-LC).
171+ // 0 00 0 000000 1 → 0000 0000 0010 0000 = 0x00 0x20
172+ let mut r = BitReader::new(&[0x00, 0x20]);
173+ assert!(parse_ics_info(&mut r, 4).is_err());
174+ }
175+}
vendor/rusty_aac/src/latm.rsadded+463 -0
@@ -0,0 +1,463 @@
1+//! **LATM / LOAS** — the low-overhead transport (ISO 14496-3 §1.7).
2+//!
3+//! ADTS carries AAC in `.aac` files; MP4 carries it in `esds`. Broadcast and
4+//! MPEG-TS carry it in **LOAS** (Low Overhead Audio Stream), whose payload is a
5+//! **LATM** (Low Overhead Audio Transport Multiplex) `AudioMuxElement`. Without
6+//! it, an AAC decoder cannot read a TS stream at all — which matters here because
7+//! this workspace ships `rff-format-ts`.
8+//!
9+//! The layering, outermost first:
10+//!
11+//! ```text
12+//! AudioSyncStream syncword 0x2B7 (11b) + audioMuxLengthBytes (13b)
13+//! AudioMuxElement muxConfigPresent = 1 (the LOAS case)
14+//! useSameStreamMux (1b) 0 -> a StreamMuxConfig follows
15+//! StreamMuxConfig audioMuxVersion, framing flags, AudioSpecificConfig
16+//! PayloadLengthInfo the AU length, as a chain of 8-bit values
17+//! PayloadMux the raw_data_block bytes
18+//! ```
19+//!
20+//! # Scope
21+//!
22+//! This implements the profile broadcast actually uses and that every encoder
23+//! emits: `audioMuxVersion = 0`, `allStreamsSameTimeFraming = 1`,
24+//! `numSubFrames = 0`, `numProgram = 0`, `numLayer = 0`, `frameLengthType = 0`.
25+//! Anything else is rejected with a clear error rather than mis-parsed — the
26+//! same policy `decode` applies to `gain_control_data`. Multiple programs and
27+//! layers are a genuine gap, not something silently mishandled.
28+
29+use crate::bits::BitReader;
30+use crate::encode::BitWriter;
31+use crate::{AudioSpecificConfig, Error, Result};
32+
33+/// The 11-bit LOAS sync pattern.
34+const LOAS_SYNC: u32 = 0x2B7;
35+/// `AudioSyncStream` header size in bytes (11-bit sync + 13-bit length = 24 bits).
36+pub const LOAS_HEADER_LEN: usize = 3;
37+
38+/// One parsed LOAS frame.
39+#[derive(Debug, Clone)]
40+pub struct LoasFrame {
41+ /// Stream parameters from the embedded `AudioSpecificConfig`.
42+ pub config: AudioSpecificConfig,
43+ /// The raw access unit (a `raw_data_block`), ready for `decode::Decoder`.
44+ pub au: Vec<u8>,
45+ /// Total bytes consumed, so a caller can walk a stream.
46+ pub frame_length: usize,
47+}
48+
49+/// Does `data` start with a LOAS `audioSyncStream` header?
50+pub fn is_loas(data: &[u8]) -> bool {
51+ data.len() >= LOAS_HEADER_LEN
52+ && data[0] == 0x56
53+ && (data[1] & 0xE0) == 0xE0
54+}
55+
56+/// Byte offset of the next LOAS syncword, for resynchronising a damaged stream.
57+pub fn find_sync(data: &[u8]) -> Option<usize> {
58+ (0..data.len().saturating_sub(LOAS_HEADER_LEN)).find(|&i| is_loas(&data[i..]))
59+}
60+
61+/// Parse an `AudioSpecificConfig` from a **bit position** (LATM embeds it
62+/// unaligned, so the byte-oriented `parse_audio_specific_config` cannot be used).
63+///
64+/// Returns the config and the number of bits it occupied — the caller needs the
65+/// length because `StreamMuxConfig` records it for `audioMuxVersion == 1`.
66+fn read_asc(r: &mut BitReader) -> Result<(AudioSpecificConfig, usize)> {
67+ let start = r.bits_left();
68+ let mut object_type = r.read_bits(5)? as u8;
69+ if object_type == 31 {
70+ object_type = 32 + r.read_bits(6)? as u8;
71+ }
72+ let sf_index = r.read_bits(4)? as u8;
73+ let sample_rate = if sf_index == 0x0F {
74+ r.read_bits(24)?
75+ } else {
76+ crate::sample_rate_for_index(sf_index)
77+ };
78+ if sample_rate == 0 {
79+ return Err(Error::invalid("latm: unknown sample rate index"));
80+ }
81+ let channels = r.read_bits(4)? as u16;
82+ // GASpecificConfig for AAC-LC: three flags, all zero for the plain case.
83+ let frame_length_flag = r.read_bool()?;
84+ if frame_length_flag {
85+ return Err(Error::unsupported("latm: 960-sample frames not supported"));
86+ }
87+ if r.read_bool()? {
88+ return Err(Error::unsupported("latm: core-coder delay not supported"));
89+ }
90+ let extension_flag = r.read_bool()?;
91+ if extension_flag {
92+ return Err(Error::unsupported("latm: AAC extension flag not supported"));
93+ }
94+ Ok((
95+ AudioSpecificConfig {
96+ object_type,
97+ sample_rate,
98+ channels,
99+ },
100+ start - r.bits_left(),
101+ ))
102+}
103+
104+/// Parse `StreamMuxConfig`, returning the embedded stream parameters.
105+fn read_stream_mux_config(r: &mut BitReader) -> Result<AudioSpecificConfig> {
106+ let audio_mux_version = r.read_bool()?;
107+ let audio_mux_version_a = if audio_mux_version { r.read_bool()? } else { false };
108+ if audio_mux_version_a {
109+ return Err(Error::unsupported("latm: audioMuxVersionA not supported"));
110+ }
111+ if audio_mux_version {
112+ // taraBufferFullness, an escaped value we do not consume correctly for
113+ // any stream we would then decode — refuse rather than desynchronise.
114+ return Err(Error::unsupported("latm: audioMuxVersion 1 not supported"));
115+ }
116+ if !r.read_bool()? {
117+ return Err(Error::unsupported(
118+ "latm: allStreamsSameTimeFraming = 0 not supported",
119+ ));
120+ }
121+ let num_sub_frames = r.read_bits(6)?;
122+ let num_program = r.read_bits(4)?;
123+ let num_layer = r.read_bits(3)?;
124+ if num_sub_frames != 0 || num_program != 0 || num_layer != 0 {
125+ return Err(Error::unsupported(
126+ "latm: multiple subframes/programs/layers not supported",
127+ ));
128+ }
129+ let (cfg, _bits) = read_asc(r)?;
130+ let frame_length_type = r.read_bits(3)?;
131+ match frame_length_type {
132+ 0 => {
133+ let _latm_buffer_fullness = r.read_bits(8)?;
134+ }
135+ _ => {
136+ return Err(Error::unsupported(
137+ "latm: only frameLengthType 0 (variable, byte-counted) is supported",
138+ ))
139+ }
140+ }
141+ let other_data_present = r.read_bool()?;
142+ if other_data_present {
143+ // otherDataLenBits, escaped in 8-bit chunks.
144+ let mut more = true;
145+ while more {
146+ let _ = r.read_bits(8)?;
147+ more = r.read_bool()?;
148+ }
149+ }
150+ if r.read_bool()? {
151+ let _crc = r.read_bits(8)?; // crcCheckSum
152+ }
153+ Ok(cfg)
154+}
155+
156+/// Parse one LOAS frame starting at `data[0]`.
157+///
158+/// `muxConfigPresent` is 1 by definition inside an `audioSyncStream`, so a
159+/// `StreamMuxConfig` is expected unless `useSameStreamMux` says to reuse the
160+/// previous one — which this function cannot do, since it is stateless. Callers
161+/// walking a stream should use [`LatmReader`], which carries that state.
162+pub fn parse_loas_frame(data: &[u8]) -> Result<LoasFrame> {
163+ LatmReader::new().parse(data)
164+}
165+
166+/// A stateful LOAS reader.
167+///
168+/// Real streams send the `StreamMuxConfig` on the first frame and then set
169+/// `useSameStreamMux = 1` for a long run of frames afterwards — that is the whole
170+/// point of "low overhead". A stateless parser therefore fails on the *majority*
171+/// of frames in any real capture, which is why this type exists.
172+#[derive(Debug, Default, Clone)]
173+pub struct LatmReader {
174+ config: Option<AudioSpecificConfig>,
175+}
176+
177+impl LatmReader {
178+ pub fn new() -> LatmReader {
179+ LatmReader::default()
180+ }
181+
182+ /// The most recently seen stream configuration, if any.
183+ pub fn config(&self) -> Option<AudioSpecificConfig> {
184+ self.config
185+ }
186+
187+ /// Parse one LOAS frame, remembering its `StreamMuxConfig` for later frames.
188+ pub fn parse(&mut self, data: &[u8]) -> Result<LoasFrame> {
189+ if !is_loas(data) {
190+ return Err(Error::invalid("latm: no audioSyncStream syncword"));
191+ }
192+ let mut r = BitReader::new(data);
193+ let sync = r.read_bits(11)?;
194+ debug_assert_eq!(sync, LOAS_SYNC);
195+ let mux_len = r.read_bits(13)? as usize;
196+ let frame_length = LOAS_HEADER_LEN + mux_len;
197+ if data.len() < frame_length {
198+ return Err(Error::Again);
199+ }
200+
201+ // AudioMuxElement(muxConfigPresent = 1)
202+ let use_same = r.read_bool()?;
203+ let cfg = if use_same {
204+ self.config
205+ .ok_or_else(|| Error::invalid("latm: useSameStreamMux before any config"))?
206+ } else {
207+ let c = read_stream_mux_config(&mut r)?;
208+ self.config = Some(c);
209+ c
210+ };
211+
212+ // PayloadLengthInfo for frameLengthType 0: 8-bit values, 255 continues.
213+ let mut au_len = 0usize;
214+ loop {
215+ let v = r.read_bits(8)? as usize;
216+ au_len += v;
217+ if v != 255 {
218+ break;
219+ }
220+ }
221+
222+ // PayloadMux — au_len bytes, still bit-aligned to the reader position.
223+ let mut au = Vec::with_capacity(au_len);
224+ for _ in 0..au_len {
225+ au.push(r.read_bits(8)? as u8);
226+ }
227+
228+ Ok(LoasFrame {
229+ config: cfg,
230+ au,
231+ frame_length,
232+ })
233+ }
234+}
235+
236+/// Serialize one LOAS frame carrying `au`, with a full `StreamMuxConfig`.
237+///
238+/// Every frame gets its own config (`useSameStreamMux = 0`). That costs ~3 bytes
239+/// per frame versus the minimum, and buys random access: a receiver can start
240+/// decoding at any frame, which is what broadcast actually needs.
241+pub fn write_loas_frame(cfg: &AudioSpecificConfig, au: &[u8]) -> Vec<u8> {
242+ let mut w = BitWriter::new();
243+ // --- AudioMuxElement(muxConfigPresent = 1) ---
244+ w.write_bool(false); // useSameStreamMux = 0 -> StreamMuxConfig follows
245+
246+ // --- StreamMuxConfig ---
247+ w.write_bool(false); // audioMuxVersion = 0
248+ w.write_bool(true); // allStreamsSameTimeFraming = 1
249+ w.write(0, 6); // numSubFrames = 0
250+ w.write(0, 4); // numProgram = 0
251+ w.write(0, 3); // numLayer = 0
252+
253+ // --- AudioSpecificConfig, bit-packed (NOT byte aligned here) ---
254+ if cfg.object_type >= 31 {
255+ w.write(31, 5);
256+ w.write((cfg.object_type - 32) as u32, 6);
257+ } else {
258+ w.write(cfg.object_type as u32, 5);
259+ }
260+ match crate::sf_index_for_rate(cfg.sample_rate) {
261+ Some(i) => w.write(i as u32, 4),
262+ None => {
263+ w.write(0x0F, 4);
264+ w.write(cfg.sample_rate, 24);
265+ }
266+ }
267+ w.write(cfg.channels as u32, 4);
268+ // GASpecificConfig: frameLengthFlag, dependsOnCoreCoder, extensionFlag.
269+ w.write(0, 3);
270+
271+ w.write(0, 3); // frameLengthType = 0
272+ w.write(0xFF, 8); // latmBufferFullness = 255 (VBR / "don't care")
273+ w.write_bool(false); // otherDataPresent
274+ w.write_bool(false); // crcCheckPresent
275+
276+ // --- PayloadLengthInfo: 255-escaped byte count ---
277+ let mut remaining = au.len();
278+ while remaining >= 255 {
279+ w.write(255, 8);
280+ remaining -= 255;
281+ }
282+ w.write(remaining as u32, 8);
283+
284+ // --- PayloadMux ---
285+ for &b in au {
286+ w.write(b as u32, 8);
287+ }
288+
289+ let body = w.into_bytes();
290+
291+ // --- audioSyncStream wrapper ---
292+ let mut out = Vec::with_capacity(LOAS_HEADER_LEN + body.len());
293+ let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF);
294+ out.push((hdr >> 16) as u8);
295+ out.push((hdr >> 8) as u8);
296+ out.push(hdr as u8);
297+ out.extend_from_slice(&body);
298+ out
299+}
300+
301+#[cfg(test)]
302+mod tests {
303+ use super::*;
304+
305+ fn cfg() -> AudioSpecificConfig {
306+ AudioSpecificConfig {
307+ object_type: 2,
308+ sample_rate: 44100,
309+ channels: 2,
310+ }
311+ }
312+
313+ /// Writer -> parser round-trip, the basic contract.
314+ #[test]
315+ fn loas_round_trips() {
316+ let au: Vec<u8> = (0..200u32).map(|i| (i * 7 + 3) as u8).collect();
317+ let frame = write_loas_frame(&cfg(), &au);
318+ assert!(is_loas(&frame), "writer must emit a valid syncword");
319+ let got = parse_loas_frame(&frame).expect("parse");
320+ assert_eq!(got.au, au, "payload must survive");
321+ assert_eq!(got.config.sample_rate, 44100);
322+ assert_eq!(got.config.channels, 2);
323+ assert_eq!(got.config.object_type, 2);
324+ assert_eq!(got.frame_length, frame.len());
325+ }
326+
327+ /// The 255-escape in PayloadLengthInfo must handle lengths either side of the
328+ /// boundary — an off-by-one there truncates or over-reads every large frame.
329+ #[test]
330+ fn payload_length_escape_is_exact() {
331+ for len in [0usize, 1, 254, 255, 256, 509, 510, 511, 1000] {
332+ let au: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
333+ let frame = write_loas_frame(&cfg(), &au);
334+ let got = parse_loas_frame(&frame).unwrap_or_else(|e| panic!("len {len}: {e}"));
335+ assert_eq!(got.au.len(), len, "length {len} mis-coded");
336+ assert_eq!(got.au, au, "length {len} payload corrupted");
337+ }
338+ }
339+
340+ /// A real stream sets `useSameStreamMux` after the first frame; a stateless
341+ /// parser fails on those, a `LatmReader` must not.
342+ #[test]
343+ fn reader_carries_config_across_frames() {
344+ let au = vec![0xAAu8; 40];
345+ let first = write_loas_frame(&cfg(), &au);
346+
347+ // Hand-build a second frame with useSameStreamMux = 1.
348+ let mut w = BitWriter::new();
349+ w.write_bool(true); // useSameStreamMux
350+ w.write(au.len() as u32, 8); // PayloadLengthInfo (< 255)
351+ for &b in &au {
352+ w.write(b as u32, 8);
353+ }
354+ let body = w.into_bytes();
355+ let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF);
356+ let mut second = vec![(hdr >> 16) as u8, (hdr >> 8) as u8, hdr as u8];
357+ second.extend_from_slice(&body);
358+
359+ let mut rd = LatmReader::new();
360+ let a = rd.parse(&first).expect("first frame");
361+ assert_eq!(a.au, au);
362+ let b = rd.parse(&second).expect("second frame must reuse the config");
363+ assert_eq!(b.au, au);
364+ assert_eq!(b.config.sample_rate, 44100);
365+
366+ // A fresh reader must REFUSE the config-less frame rather than guess.
367+ assert!(LatmReader::new().parse(&second).is_err());
368+ }
369+
370+ /// Sync detection and resynchronisation.
371+ #[test]
372+ fn finds_sync_after_garbage() {
373+ let au = vec![0x5Au8; 32];
374+ let frame = write_loas_frame(&cfg(), &au);
375+ let mut stream = vec![0x00, 0xFF, 0x12, 0x34];
376+ let offset = stream.len();
377+ stream.extend_from_slice(&frame);
378+ assert_eq!(find_sync(&stream), Some(offset));
379+ let got = parse_loas_frame(&stream[offset..]).unwrap();
380+ assert_eq!(got.au, au);
381+ }
382+
383+ /// A truncated frame must ask for more data, not mis-parse.
384+ #[test]
385+ fn truncated_frame_returns_again() {
386+ let au = vec![0x11u8; 300];
387+ let frame = write_loas_frame(&cfg(), &au);
388+ let cut = &frame[..frame.len() - 10];
389+ assert!(matches!(parse_loas_frame(cut), Err(Error::Again)));
390+ }
391+
392+ /// Unsupported mux shapes are refused with a clear error, never mis-decoded.
393+ #[test]
394+ fn unsupported_mux_shapes_are_refused() {
395+ // numLayer != 0
396+ let mut w = BitWriter::new();
397+ w.write_bool(false); // useSameStreamMux
398+ w.write_bool(false); // audioMuxVersion
399+ w.write_bool(true); // allStreamsSameTimeFraming
400+ w.write(0, 6); // numSubFrames
401+ w.write(0, 4); // numProgram
402+ w.write(1, 3); // numLayer = 1 <-- unsupported
403+ let body = w.into_bytes();
404+ let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF);
405+ let mut frame = vec![(hdr >> 16) as u8, (hdr >> 8) as u8, hdr as u8];
406+ frame.extend_from_slice(&body);
407+ assert!(parse_loas_frame(&frame).is_err());
408+ }
409+
410+ /// **End to end**: real AAC through LOAS and back out to PCM. The unit tests
411+ /// above prove the framing; this proves the framing carries a decodable
412+ /// stream, which is the only claim that matters for MPEG-TS carriage.
413+ #[test]
414+ fn real_aac_survives_loas_carriage() {
415+ use crate::{AacEncoder, AacEncoderConfig};
416+ let sr = 44100u32;
417+ let n = 10 * 1024;
418+ let pcm: Vec<f32> = (0..n * 2)
419+ .map(|i| {
420+ let t = (i / 2) as f32 / sr as f32;
421+ 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
422+ })
423+ .collect();
424+
425+ let mut enc = AacEncoder::new(AacEncoderConfig::default());
426+ enc.push_pcm(&pcm, 2, sr).unwrap();
427+ enc.finish();
428+
429+ let cfg = AudioSpecificConfig {
430+ object_type: 2,
431+ sample_rate: sr,
432+ channels: 2,
433+ };
434+
435+ // Encode -> LOAS
436+ let mut stream = Vec::new();
437+ let mut n_frames = 0usize;
438+ while let Ok(p) = enc.next_packet() {
439+ stream.extend_from_slice(&write_loas_frame(&cfg, &p.data));
440+ n_frames += 1;
441+ }
442+ assert!(n_frames > 5, "need several frames to exercise the reader");
443+
444+ // LOAS -> decode
445+ let mut rd = LatmReader::new();
446+ // The transport supplies the config out of band, exactly as an MPEG-TS
447+ // demuxer would hand it to the decoder.
448+ let mut dec = crate::AacDecoder::with_config(cfg);
449+ let mut pos = 0usize;
450+ let mut decoded = 0usize;
451+ let mut parsed = 0usize;
452+ while pos + LOAS_HEADER_LEN < stream.len() {
453+ let f = rd.parse(&stream[pos..]).expect("LOAS frame");
454+ assert_eq!(f.config, cfg, "config must survive the transport");
455+ let audio = dec.decode(&f.au, None).expect("AU must decode");
456+ decoded += audio.frames();
457+ pos += f.frame_length;
458+ parsed += 1;
459+ }
460+ assert_eq!(parsed, n_frames, "every frame must be recovered");
461+ assert!(decoded >= n, "decoded {decoded} of {n} samples");
462+ }
463+}
vendor/rusty_aac/src/lib.rsadded+413 -0
@@ -0,0 +1,413 @@
1+//! Pure-Rust **AAC-LC decoder + encoder**, no C and no FFI.
2+//!
3+//! Extracted from (and the engine of) the
4+//! [`remade_ffmpeg_rs`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)
5+//! project. The crate has **zero dependencies**.
6+//!
7+//! - **Decoder**: complete AAC-LC — long/short/transition windows with grouped
8+//! scalefactors, all spectral Huffman codebooks, M/S and intensity stereo,
9+//! PNS, TNS — verified against FFmpeg (bit-exact on deterministic features).
10+//! Entry point: [`AacDecoder`] (handles ADTS framing and raw MP4 access
11+//! units alike) or the lower-level [`decode::Decoder`].
12+//! - **Encoder**: psychoacoustic Bark-scale masking model, two-phase bitrate
13+//! rate loop, transient-driven block switching, per-SFB M/S stereo, and a
14+//! frame-parallel `encode_stream` (~450× realtime). Entry point:
15+//! [`AacEncoder`] with [`AacEncoderConfig`].
16+//! - **Framing & config**: [`AudioSpecificConfig`] (the MP4 `esds` payload)
17+//! and [`AdtsHeader`] (the `.aac` elementary-stream header) parsers plus
18+//! their serializers ([`write_audio_specific_config`], [`write_adts_header`],
19+//! [`audio_specific_config_bytes`]).
20+//!
21+//! The `simd` feature (default) enables runtime-detected AVX2 kernels;
22+//! `--no-default-features` gives a 100%-safe scalar build. `simd-avx512` adds
23+//! an opt-in AVX-512 tier.
24+
25+mod bits;
26+mod codebook;
27+pub mod decode;
28+mod dsp;
29+pub mod encode;
30+mod error;
31+mod huffman;
32+mod ics;
33+/// LATM/LOAS transport (ISO 14496-3 §1.7) — the MPEG-TS / broadcast carriage
34+/// format, alongside ADTS (`.aac`) and MP4 `esds`.
35+pub mod latm;
36+/// The quality lab (feature `lab`): deterministic corpus, the NMR metric, and the
37+/// bitrate-ladder runner. This is the verdict instrument for the Great Gate
38+/// campaign — see `docs/codec-aac-great-gate.md`.
39+#[cfg(feature = "lab")]
40+pub mod lab;
41+/// HE-AAC (SBR / Parametric Stereo) signalling and capability reporting — the
42+/// broadcast and low-bitrate-streaming configuration. See the module docs for
43+/// exactly which parts are implemented.
44+pub mod sbr;
45+mod swb;
46+mod tables;
47+
48+pub use bits::BitReader;
49+pub use encode::{
50+ audio_specific_config_bytes, write_adts_header, write_audio_specific_config, AacEncoder,
51+ AacEncoderConfig, EncodedPacket, WindowShape,
52+};
53+pub use error::{Error, Result};
54+
55+/// AAC sample-rate table, indexed by `samplingFrequencyIndex` (ISO 14496-3).
56+pub const SAMPLE_RATES: [u32; 13] = [
57+ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
58+];
59+
60+/// Map a 4-bit sampling-frequency index to a rate (0 for the reserved/escape
61+/// values 13-15, which require an explicit 24-bit rate).
62+pub fn sample_rate_for_index(idx: u8) -> u32 {
63+ SAMPLE_RATES.get(idx as usize).copied().unwrap_or(0)
64+}
65+
66+/// Map a sampling rate to its 4-bit index, or None if non-standard (the encoder
67+/// then uses the 0x0F + explicit-24-bit-rate escape).
68+pub fn sf_index_for_rate(rate: u32) -> Option<u8> {
69+ SAMPLE_RATES
70+ .iter()
71+ .position(|&r| r == rate)
72+ .map(|i| i as u8)
73+}
74+
75+// ---------------------------------------------------------------------------
76+// AudioSpecificConfig — the MP4 `esds` DecoderSpecificInfo (raw AAC config).
77+// ---------------------------------------------------------------------------
78+
79+/// Parsed `AudioSpecificConfig` (ISO 14496-3 §1.6.2.1).
80+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81+pub struct AudioSpecificConfig {
82+ /// Audio Object Type (2 = AAC-LC, the only one we target).
83+ pub object_type: u8,
84+ pub sample_rate: u32,
85+ /// Channel configuration (1 = mono, 2 = stereo, …).
86+ pub channels: u16,
87+}
88+
89+/// Parse an `AudioSpecificConfig` from its raw bytes (the `esds`/`stsd` config).
90+pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
91+ let mut r = BitReader::new(data);
92+ let object_type = read_object_type(&mut r)?;
93+ let sf_index = r.read_bits(4)? as u8;
94+ let sample_rate = if sf_index == 0x0F {
95+ r.read_bits(24)?
96+ } else {
97+ sample_rate_for_index(sf_index)
98+ };
99+ let channels = r.read_bits(4)? as u16;
100+ if sample_rate == 0 {
101+ return Err(Error::invalid("aac: invalid sampling frequency in config"));
102+ }
103+ Ok(AudioSpecificConfig {
104+ object_type,
105+ sample_rate,
106+ channels,
107+ })
108+}
109+
110+/// Read the (possibly escaped) 5-bit Audio Object Type.
111+fn read_object_type(r: &mut BitReader) -> Result<u8> {
112+ let ot = r.read_bits(5)? as u8;
113+ if ot == 31 {
114+ Ok((32 + r.read_bits(6)?) as u8)
115+ } else {
116+ Ok(ot)
117+ }
118+}
119+
120+// ---------------------------------------------------------------------------
121+// ADTS — the `.aac` elementary-stream frame header.
122+// ---------------------------------------------------------------------------
123+
124+/// A parsed ADTS frame header (ISO 14496-3 §1.A.2.2.1).
125+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126+pub struct AdtsHeader {
127+ /// Audio Object Type (profile + 1).
128+ pub object_type: u8,
129+ pub sample_rate: u32,
130+ pub channels: u16,
131+ /// Total frame length including this header.
132+ pub frame_length: usize,
133+ /// Header size in bytes (7 without CRC, 9 with).
134+ pub header_len: usize,
135+}
136+
137+/// True if `data` begins with an ADTS syncword (0xFFF, layer 00).
138+pub fn is_adts(data: &[u8]) -> bool {
139+ data.len() >= 2 && data[0] == 0xFF && (data[1] & 0xF6) == 0xF0
140+}
141+
142+/// Parse an ADTS header from the start of `data`.
143+pub fn parse_adts(data: &[u8]) -> Result<AdtsHeader> {
144+ if !is_adts(data) || data.len() < 7 {
145+ return Err(Error::invalid("aac: not an ADTS frame"));
146+ }
147+ let mut r = BitReader::new(data);
148+ r.skip(12)?; // syncword
149+ r.skip(1)?; // MPEG version
150+ r.skip(2)?; // layer (00)
151+ let protection_absent = r.read_bool()?;
152+ let profile = r.read_bits(2)? as u8; // object_type - 1
153+ let sf_index = r.read_bits(4)? as u8;
154+ r.skip(1)?; // private
155+ let channel_config = r.read_bits(3)? as u16;
156+ r.skip(4)?; // original/home/copyright id+start
157+ let frame_length = r.read_bits(13)? as usize;
158+ // remaining: buffer_fullness(11) + num_raw_data_blocks(2) — not needed here.
159+ let sample_rate = sample_rate_for_index(sf_index);
160+ if sample_rate == 0 || frame_length < 7 {
161+ return Err(Error::invalid("aac: invalid ADTS header"));
162+ }
163+ Ok(AdtsHeader {
164+ object_type: profile + 1,
165+ sample_rate,
166+ channels: channel_config,
167+ frame_length,
168+ header_len: if protection_absent { 7 } else { 9 },
169+ })
170+}
171+
172+// ---------------------------------------------------------------------------
173+// Decoded PCM — the decoder's native output.
174+// ---------------------------------------------------------------------------
175+
176+/// One decoded frame of PCM: interleaved `f32` samples in [-1, 1].
177+#[derive(Debug, Clone)]
178+pub struct DecodedAudio {
179+ pub sample_rate: u32,
180+ pub channels: u16,
181+ /// Interleaved samples (`samples.len() = frames × channels`).
182+ pub samples: Vec<f32>,
183+ /// The presentation timestamp handed to [`AacDecoder::decode`], if any.
184+ pub pts: Option<i64>,
185+}
186+
187+impl DecodedAudio {
188+ /// Number of PCM frames (samples per channel).
189+ pub fn frames(&self) -> usize {
190+ self.samples.len() / self.channels.max(1) as usize
191+ }
192+}
193+
194+// ---------------------------------------------------------------------------
195+// Decoder — stream-level: ADTS stripping + lazy core init.
196+// ---------------------------------------------------------------------------
197+
198+/// Stream-level AAC-LC decoder: accepts either ADTS frames (`.aac` elementary
199+/// streams — the config is read from the header) or bare raw access units
200+/// (MP4 — configure via [`AacDecoder::with_config`] from the `esds`
201+/// [`AudioSpecificConfig`]).
202+#[derive(Default)]
203+pub struct AacDecoder {
204+ config: Option<AudioSpecificConfig>,
205+ decoder: Option<decode::Decoder>,
206+ /// HE-AAC parameters, when built via [`AacDecoder::with_config_bytes`].
207+ sbr: Option<sbr::SbrConfig>,
208+}
209+
210+impl AacDecoder {
211+ /// A decoder that learns its parameters from the stream (ADTS headers).
212+ pub fn new() -> AacDecoder {
213+ AacDecoder::default()
214+ }
215+
216+ /// A decoder pre-configured from an out-of-band [`AudioSpecificConfig`]
217+ /// (the MP4 `esds` payload) — required for bare raw access units.
218+ pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
219+ AacDecoder {
220+ config: Some(cfg),
221+ decoder: None,
222+ sbr: None,
223+ }
224+ }
225+
226+ /// A decoder configured from the **raw** `AudioSpecificConfig` bytes.
227+ ///
228+ /// Prefer this over [`with_config`](Self::with_config) whenever the raw bytes
229+ /// are available (they always are — `esds`, `StreamMuxConfig`), because HE-AAC
230+ /// signalling lives in fields the plain [`AudioSpecificConfig`] does not
231+ /// carry. An HE-AAC stream configured through the plain path reports its
232+ /// **core** rate, and a player that believes it plays the audio at half
233+ /// speed.
234+ pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
235+ let sbr = sbr::parse_sbr_config(data)?;
236+ let mut cfg = parse_audio_specific_config(data)?;
237+ // The core decodes at the core rate whatever the config's first field
238+ // said; for hierarchical HE-AAC that field was the extension rate.
239+ if sbr.sbr_present {
240+ cfg.sample_rate = sbr.core_sample_rate;
241+ cfg.object_type = sbr.core_object_type;
242+ }
243+ Ok(AacDecoder {
244+ config: Some(cfg),
245+ decoder: None,
246+ sbr: Some(sbr),
247+ })
248+ }
249+
250+ /// HE-AAC parameters, when the decoder was built from raw config bytes.
251+ pub fn sbr_config(&self) -> Option<sbr::SbrConfig> {
252+ self.sbr
253+ }
254+
255+ /// How much of this stream can actually be reconstructed.
256+ ///
257+ /// [`SbrSupport::CoreOnly`](sbr::SbrSupport::CoreOnly) means the output is
258+ /// real audio, correct in rate and channels, but band-limited to the core's
259+ /// Nyquist because the SBR high band is not reconstructed.
260+ pub fn sbr_support(&self) -> sbr::SbrSupport {
261+ match self.sbr {
262+ Some(s) => s.support(),
263+ None => sbr::SbrSupport::NotPresent,
264+ }
265+ }
266+
267+ /// The stream's **output** sample rate.
268+ ///
269+ /// For HE-AAC this is twice the rate the `raw_data_block`s are coded at.
270+ /// Returns `None` until the configuration is known.
271+ pub fn output_sample_rate(&self) -> Option<u32> {
272+ match self.sbr {
273+ Some(s) if s.sbr_present => Some(s.output_sample_rate),
274+ _ => self.config.map(|c| c.sample_rate),
275+ }
276+ }
277+
278+ /// Lazily build the stateful decoder once rate/channels are known.
279+ fn ensure_decoder(&mut self) -> Result<&mut decode::Decoder> {
280+ if self.decoder.is_none() {
281+ let cfg = self
282+ .config
283+ .ok_or_else(|| Error::invalid("aac: stream parameters unknown"))?;
284+ self.decoder = Some(decode::Decoder::new(cfg.sample_rate));
285+ }
286+ Ok(self.decoder.as_mut().unwrap())
287+ }
288+
289+ /// Decode one packet (an ADTS frame or a bare raw access unit) into PCM.
290+ ///
291+ /// ADTS framing, if present, is stripped (and configures the decoder on
292+ /// first use). Returns [`Error::Again`] for an empty packet (nothing to
293+ /// decode — feed the next one).
294+ pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
295+ // Strip ADTS framing if present; MP4 delivers bare access units.
296+ let mut data = packet;
297+ if is_adts(data) {
298+ let header = parse_adts(data)?;
299+ if self.config.is_none() {
300+ self.config = Some(AudioSpecificConfig {
301+ object_type: header.object_type,
302+ sample_rate: header.sample_rate,
303+ channels: header.channels,
304+ });
305+ }
306+ data = data
307+ .get(header.header_len..header.frame_length.min(data.len()))
308+ .unwrap_or(&[]);
309+ }
310+ if data.is_empty() {
311+ return Err(Error::Again);
312+ }
313+ self.ensure_decoder()?.decode(data, pts)
314+ }
315+}
316+
317+#[cfg(test)]
318+mod tests {
319+ use super::*;
320+
321+ #[test]
322+ fn asc_stereo_44100_aac_lc() {
323+ // object_type=2 (00010), sf_index=4 (0100)=44100, channels=2 (0010).
324+ // 00010 0100 0010 → 0001 0010 0001 0000 = 0x12 0x10 (trailing pad).
325+ let cfg = parse_audio_specific_config(&[0x12, 0x10]).unwrap();
326+ assert_eq!(cfg.object_type, 2);
327+ assert_eq!(cfg.sample_rate, 44_100);
328+ assert_eq!(cfg.channels, 2);
329+ }
330+
331+ #[test]
332+ fn asc_mono_48000() {
333+ // object_type=2 (00010), sf_index=3 (0011)=48000, channels=1 (0001).
334+ // 00010 0011 0001 → 0001 0001 1000 1... = 0x11 0x88.
335+ let cfg = parse_audio_specific_config(&[0x11, 0x88]).unwrap();
336+ assert_eq!(cfg.sample_rate, 48_000);
337+ assert_eq!(cfg.channels, 1);
338+ }
339+
340+ #[test]
341+ fn adts_header_parses() {
342+ // 7-byte ADTS header (no CRC): sync 0xFFF, MPEG-4, layer 0,
343+ // protection_absent=1, profile 1 (AAC-LC), sf_index 4 (44100),
344+ // channel_config 2, frame_length 100. Layout verified bit-by-bit.
345+ let h = [0xFFu8, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC];
346+ let hdr = parse_adts(&h).unwrap();
347+ assert_eq!(hdr.object_type, 2); // profile 1 + 1
348+ assert_eq!(hdr.sample_rate, 44_100);
349+ assert_eq!(hdr.channels, 2);
350+ assert_eq!(hdr.frame_length, 100);
351+ assert_eq!(hdr.header_len, 7);
352+ }
353+
354+ #[test]
355+ fn is_adts_detects_syncword() {
356+ assert!(is_adts(&[0xFF, 0xF1, 0x00]));
357+ assert!(is_adts(&[0xFF, 0xF0, 0x00]));
358+ assert!(!is_adts(&[0xFF, 0x00]));
359+ assert!(!is_adts(&[0x00, 0xF1]));
360+ }
361+
362+ #[test]
363+ fn sample_rate_table() {
364+ assert_eq!(sample_rate_for_index(3), 48_000);
365+ assert_eq!(sample_rate_for_index(4), 44_100);
366+ assert_eq!(sample_rate_for_index(8), 16_000);
367+ assert_eq!(sample_rate_for_index(15), 0); // escape value
368+ }
369+
370+ /// The stream-level decoder learns its config from ADTS and decodes to
371+ /// interleaved PCM (encoder round-trip; the full-pipeline gates live in
372+ /// `encode`'s tests).
373+ #[test]
374+ fn adts_stream_decodes_via_stream_decoder() {
375+ let sr = 44100u32;
376+ let n = 4096usize;
377+ let pcm: Vec<f32> = (0..n)
378+ .map(|i| {
379+ ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32
380+ })
381+ .collect();
382+ let mut enc = AacEncoder::new(AacEncoderConfig::default());
383+ enc.push_pcm(&pcm, 1, sr).unwrap();
384+ enc.finish();
385+ let mut adts = Vec::new();
386+ while let Ok(p) = enc.next_packet() {
387+ let hdr = AdtsHeader {
388+ object_type: 2,
389+ sample_rate: sr,
390+ channels: 1,
391+ frame_length: 7 + p.data.len(),
392+ header_len: 7,
393+ };
394+ adts.extend_from_slice(&write_adts_header(&hdr));
395+ adts.extend_from_slice(&p.data);
396+ }
397+
398+ let mut dec = AacDecoder::new();
399+ let mut decoded = 0usize;
400+ let mut pos = 0usize;
401+ while pos + 7 <= adts.len() {
402+ let hdr = parse_adts(&adts[pos..]).unwrap();
403+ let out = dec
404+ .decode(&adts[pos..pos + hdr.frame_length], None)
405+ .unwrap();
406+ assert_eq!(out.sample_rate, sr);
407+ assert_eq!(out.channels, 1);
408+ decoded += out.frames();
409+ pos += hdr.frame_length;
410+ }
411+ assert!(decoded >= n, "decoded fewer samples than encoded");
412+ }
413+}
vendor/rusty_aac/src/sbr.rsadded+405 -0
@@ -0,0 +1,405 @@
1+//! **HE-AAC (SBR / PS)** — signalling, detection, and honest capability
2+//! reporting.
3+//!
4+//! HE-AAC v1 wraps an AAC-LC core with **SBR** (Spectral Band Replication): the
5+//! core codes the lower half of the spectrum at half the output rate, and SBR
6+//! reconstructs the top half from it plus a small parameter stream. HE-AAC v2
7+//! adds **PS** (Parametric Stereo), coding a mono core plus stereo parameters.
8+//!
9+//! This is what broadcast and low-bitrate streaming actually use, so a decoder
10+//! that mishandles it mishandles the majority of real AAC in the wild.
11+//!
12+//! # What is implemented here, and what is not
13+//!
14+//! **Implemented, exactly:** the signalling. Both forms — *explicit hierarchical*
15+//! (`audioObjectType` 5 or 29) and *explicit backward-compatible* (the `0x2B7`
16+//! sync extension after the `GASpecificConfig`) — plus detection of SBR payload
17+//! in the `fill_element`, and the **output sample rate**, which for HE-AAC is
18+//! twice the core rate.
19+//!
20+//! **NOT implemented:** the SBR reconstruction itself. See [`SbrSupport`]. The
21+//! blocker is not design effort — it is that the tool is defined by large
22+//! normative tables (the 640-tap QMF prototype filter, ISO/IEC 14496-3
23+//! Table 4.A.87, and the SBR envelope/noise Huffman codebooks). Those must be
24+//! transcribed from the specification or a reference implementation. Writing
25+//! *approximations* of them would produce a decoder that is subtly wrong
26+//! everywhere while appearing to work, which is strictly worse than not having
27+//! it — the same reason `decode` refuses `gain_control_data` rather than
28+//! guessing at it.
29+//!
30+//! # Why the signalling alone is worth having
31+//!
32+//! Without it an HE-AAC stream is not merely "missing its high band" — it is
33+//! **silently played at the wrong speed**. The config announces a 24 kHz core for
34+//! 48 kHz output; a decoder that reports 24 kHz hands the player half-rate audio.
35+//! With this module the core decodes correctly, the caller learns the true output
36+//! rate, and [`SbrSupport`] says plainly that the high band is absent instead of
37+//! pretending otherwise.
38+
39+use crate::bits::BitReader;
40+use crate::{Error, Result};
41+
42+/// `audioObjectType` values that name an SBR-bearing configuration.
43+pub const AOT_SBR: u8 = 5;
44+/// AAC-LC — the core object type SBR wraps.
45+pub const AOT_AAC_LC: u8 = 2;
46+/// HE-AAC v2 (SBR + Parametric Stereo).
47+pub const AOT_PS: u8 = 29;
48+/// ER-BSAC, the one object type that carries `extensionChannelConfiguration`.
49+const AOT_ER_BSAC: u8 = 22;
50+
51+/// `syncExtensionType` marking backward-compatible SBR signalling.
52+const SYNC_EXT_SBR: u32 = 0x2B7;
53+/// `syncExtensionType` marking backward-compatible PS signalling.
54+const SYNC_EXT_PS: u32 = 0x548;
55+
56+/// `extension_type` values inside a `fill_element` payload.
57+const EXT_SBR_DATA: u32 = 13;
58+const EXT_SBR_DATA_CRC: u32 = 14;
59+
60+/// How much of an SBR stream this build can actually reconstruct.
61+///
62+/// Returned rather than inferred so callers never have to guess, and so the
63+/// limitation is visible at the API surface instead of buried in a doc comment.
64+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65+pub enum SbrSupport {
66+ /// No SBR in this stream; plain AAC-LC decoding is complete and exact.
67+ NotPresent,
68+ /// SBR is present. The **core is decoded correctly** and the output sample
69+ /// rate is reported correctly, but the replicated high band is not
70+ /// reconstructed — the result is band-limited to the core's Nyquist.
71+ ///
72+ /// This is the standard "core-only" fallback, and it is audio rather than
73+ /// silence or an error. It is not conformant HE-AAC decoding.
74+ CoreOnly,
75+}
76+
77+/// HE-AAC parameters recovered from an `AudioSpecificConfig`.
78+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79+pub struct SbrConfig {
80+ /// SBR is signalled in the config.
81+ pub sbr_present: bool,
82+ /// Parametric Stereo is signalled (HE-AAC v2).
83+ pub ps_present: bool,
84+ /// The **core** AAC sample rate — what the `raw_data_block`s are coded at.
85+ pub core_sample_rate: u32,
86+ /// The **output** sample rate after SBR, normally `2 x core_sample_rate`.
87+ pub output_sample_rate: u32,
88+ /// The core object type beneath the extension (2 for HE-AAC over AAC-LC).
89+ pub core_object_type: u8,
90+}
91+
92+impl SbrConfig {
93+ /// What this build can do with the stream.
94+ pub fn support(&self) -> SbrSupport {
95+ if self.sbr_present {
96+ SbrSupport::CoreOnly
97+ } else {
98+ SbrSupport::NotPresent
99+ }
100+ }
101+}
102+
103+/// Read a (possibly escaped) 5-bit `audioObjectType`.
104+fn read_aot(r: &mut BitReader) -> Result<u8> {
105+ let ot = r.read_bits(5)? as u8;
106+ if ot == 31 {
107+ Ok((32 + r.read_bits(6)?) as u8)
108+ } else {
109+ Ok(ot)
110+ }
111+}
112+
113+/// Read a `samplingFrequencyIndex`, honouring the 0x0F escape.
114+fn read_sampling_frequency(r: &mut BitReader) -> Result<u32> {
115+ let idx = r.read_bits(4)? as u8;
116+ let rate = if idx == 0x0F {
117+ r.read_bits(24)?
118+ } else {
119+ crate::sample_rate_for_index(idx)
120+ };
121+ if rate == 0 {
122+ return Err(Error::invalid("sbr: reserved sampling frequency index"));
123+ }
124+ Ok(rate)
125+}
126+
127+/// Parse an `AudioSpecificConfig` for HE-AAC signalling.
128+///
129+/// Handles both forms the standard defines, because real streams use both:
130+///
131+/// * **Explicit hierarchical** — `audioObjectType` is 5 (SBR) or 29 (PS), and the
132+/// extension rate and true core object type follow immediately. A legacy AAC-LC
133+/// decoder cannot read these at all.
134+/// * **Explicit backward-compatible** — `audioObjectType` is 2 (AAC-LC), and a
135+/// `0x2B7` sync extension *after* the `GASpecificConfig` announces SBR. Legacy
136+/// decoders skip the extension and decode the core, which is precisely the
137+/// point.
138+///
139+/// A stream with neither yields `sbr_present = false`.
140+pub fn parse_sbr_config(data: &[u8]) -> Result<SbrConfig> {
141+ let mut r = BitReader::new(data);
142+ let mut aot = read_aot(&mut r)?;
143+ let core_rate_first = read_sampling_frequency(&mut r)?;
144+ let _channels = r.read_bits(4)?;
145+
146+ let mut cfg = SbrConfig {
147+ core_sample_rate: core_rate_first,
148+ output_sample_rate: core_rate_first,
149+ core_object_type: aot,
150+ ..Default::default()
151+ };
152+
153+ let hierarchical = aot == AOT_SBR || aot == AOT_PS;
154+ if hierarchical {
155+ cfg.sbr_present = true;
156+ cfg.ps_present = aot == AOT_PS;
157+ // In this form the rate read above is the EXTENSION (output) rate, and
158+ // the core rate follows the inner object type. Getting these the wrong
159+ // way round is the classic half-speed/double-speed HE-AAC bug.
160+ cfg.output_sample_rate = core_rate_first;
161+ aot = read_aot(&mut r)?;
162+ cfg.core_object_type = aot;
163+ if aot == AOT_ER_BSAC {
164+ let _ext_channels = r.read_bits(4)?;
165+ }
166+ // The core rate is not restated; for every real HE-AAC stream it is half
167+ // the extension rate.
168+ cfg.core_sample_rate = core_rate_first / 2;
169+ }
170+
171+ // GASpecificConfig (AAC-LC): three flags.
172+ if aot == AOT_AAC_LC {
173+ let frame_length_flag = r.read_bool()?;
174+ if frame_length_flag {
175+ return Err(Error::unsupported("sbr: 960-sample frames not supported"));
176+ }
177+ if r.read_bool()? {
178+ return Err(Error::unsupported("sbr: core-coder delay not supported"));
179+ }
180+ let _extension_flag = r.read_bool()?;
181+ }
182+
183+ // Backward-compatible signalling: only meaningful when the hierarchical form
184+ // was NOT used.
185+ if !hierarchical && r.bits_left() >= 16 {
186+ let sync = r.read_bits(11)?;
187+ if sync == SYNC_EXT_SBR {
188+ let ext_aot = read_aot(&mut r)?;
189+ if ext_aot == AOT_SBR {
190+ let sbr_present = r.read_bool()?;
191+ if sbr_present {
192+ cfg.sbr_present = true;
193+ cfg.output_sample_rate = read_sampling_frequency(&mut r)?;
194+ if r.bits_left() >= 12 {
195+ let sync2 = r.read_bits(11)?;
196+ if sync2 == SYNC_EXT_PS {
197+ cfg.ps_present = r.read_bool()?;
198+ }
199+ }
200+ }
201+ }
202+ }
203+ }
204+
205+ // A stream signalling SBR but no explicit output rate implies doubling.
206+ if cfg.sbr_present && cfg.output_sample_rate == cfg.core_sample_rate {
207+ cfg.output_sample_rate = cfg.core_sample_rate * 2;
208+ }
209+ Ok(cfg)
210+}
211+
212+/// Does this `fill_element` payload carry SBR data?
213+///
214+/// `payload` is the fill payload **after** the count field, and its first 4 bits
215+/// are the `extension_type`. Used for *implicit* SBR signalling, where nothing in
216+/// the config says SBR but the fill elements carry it anyway — a shape MPEG-TS
217+/// broadcast genuinely produces.
218+pub fn fil_payload_is_sbr(payload: &[u8]) -> bool {
219+ if payload.is_empty() {
220+ return false;
221+ }
222+ let ext = (payload[0] >> 4) as u32;
223+ ext == EXT_SBR_DATA || ext == EXT_SBR_DATA_CRC
224+}
225+
226+#[cfg(test)]
227+mod tests {
228+ use super::*;
229+ use crate::encode::BitWriter;
230+
231+ /// Plain AAC-LC: no SBR, rates equal.
232+ #[test]
233+ fn plain_aac_lc_has_no_sbr() {
234+ // AOT 2, sfIndex 4 (44100), 2 channels, GASpecificConfig zeros.
235+ let cfg = crate::audio_specific_config_bytes(44100, 2);
236+ let s = parse_sbr_config(&cfg).unwrap();
237+ assert!(!s.sbr_present);
238+ assert!(!s.ps_present);
239+ assert_eq!(s.core_sample_rate, 44100);
240+ assert_eq!(s.output_sample_rate, 44100);
241+ assert_eq!(s.support(), SbrSupport::NotPresent);
242+ }
243+
244+ /// **Explicit hierarchical HE-AAC v1.** AOT 5, extension rate 44100, core
245+ /// AOT 2 -> core runs at 22050. This is the case that silently plays at half
246+ /// speed if the two rates are swapped.
247+ #[test]
248+ fn explicit_hierarchical_he_aac_v1() {
249+ let mut w = BitWriter::new();
250+ w.write(AOT_SBR as u32, 5);
251+ w.write(4, 4); // extension sfIndex = 44100
252+ w.write(2, 4); // channels
253+ w.write(AOT_AAC_LC as u32, 5); // core object type
254+ w.write(0, 3); // GASpecificConfig
255+ let bytes = w.into_bytes();
256+
257+ let s = parse_sbr_config(&bytes).unwrap();
258+ assert!(s.sbr_present, "AOT 5 must signal SBR");
259+ assert!(!s.ps_present);
260+ assert_eq!(s.output_sample_rate, 44100, "extension rate is the OUTPUT rate");
261+ assert_eq!(s.core_sample_rate, 22050, "core runs at half");
262+ assert_eq!(s.core_object_type, AOT_AAC_LC);
263+ assert_eq!(s.support(), SbrSupport::CoreOnly);
264+ }
265+
266+ /// **Explicit hierarchical HE-AAC v2** — AOT 29 also implies PS.
267+ #[test]
268+ fn explicit_hierarchical_he_aac_v2() {
269+ let mut w = BitWriter::new();
270+ w.write(AOT_PS as u32, 5);
271+ w.write(3, 4); // 48000 output
272+ w.write(2, 4);
273+ w.write(AOT_AAC_LC as u32, 5);
274+ w.write(0, 3);
275+ let s = parse_sbr_config(&w.into_bytes()).unwrap();
276+ assert!(s.sbr_present && s.ps_present, "AOT 29 implies SBR + PS");
277+ assert_eq!(s.output_sample_rate, 48000);
278+ assert_eq!(s.core_sample_rate, 24000);
279+ }
280+
281+ /// **Explicit backward-compatible signalling** — the form legacy decoders can
282+ /// still read. AOT 2 up front, then the 0x2B7 sync extension.
283+ #[test]
284+ fn backward_compatible_signalling() {
285+ let mut w = BitWriter::new();
286+ w.write(AOT_AAC_LC as u32, 5);
287+ w.write(6, 4); // core sfIndex = 24000
288+ w.write(2, 4);
289+ w.write(0, 3); // GASpecificConfig
290+ w.write(SYNC_EXT_SBR, 11);
291+ w.write(AOT_SBR as u32, 5);
292+ w.write_bool(true); // sbrPresentFlag
293+ w.write(3, 4); // extension sfIndex = 48000
294+ let s = parse_sbr_config(&w.into_bytes()).unwrap();
295+ assert!(s.sbr_present);
296+ assert!(!s.ps_present);
297+ assert_eq!(s.core_sample_rate, 24000);
298+ assert_eq!(s.output_sample_rate, 48000);
299+ }
300+
301+ /// Backward-compatible PS signalling stacks a second sync extension.
302+ #[test]
303+ fn backward_compatible_ps_signalling() {
304+ let mut w = BitWriter::new();
305+ w.write(AOT_AAC_LC as u32, 5);
306+ w.write(6, 4); // 24000 core
307+ w.write(2, 4);
308+ w.write(0, 3);
309+ w.write(SYNC_EXT_SBR, 11);
310+ w.write(AOT_SBR as u32, 5);
311+ w.write_bool(true);
312+ w.write(3, 4); // 48000
313+ w.write(SYNC_EXT_PS, 11);
314+ w.write_bool(true); // psPresentFlag
315+ let s = parse_sbr_config(&w.into_bytes()).unwrap();
316+ assert!(s.sbr_present && s.ps_present);
317+ assert_eq!(s.output_sample_rate, 48000);
318+ }
319+
320+ /// SBR signalled without an explicit extension rate implies doubling.
321+ #[test]
322+ fn sbr_without_explicit_rate_doubles() {
323+ let mut w = BitWriter::new();
324+ w.write(AOT_AAC_LC as u32, 5);
325+ w.write(6, 4); // 24000
326+ w.write(1, 4);
327+ w.write(0, 3);
328+ w.write(SYNC_EXT_SBR, 11);
329+ w.write(AOT_SBR as u32, 5);
330+ w.write_bool(false); // sbrPresentFlag = 0
331+ let s = parse_sbr_config(&w.into_bytes()).unwrap();
332+ assert!(!s.sbr_present, "an explicit 0 must not turn SBR on");
333+ assert_eq!(s.output_sample_rate, 24000);
334+ }
335+
336+ /// Fill-element SBR payload detection, for implicit signalling.
337+ #[test]
338+ fn detects_sbr_fill_payload() {
339+ assert!(fil_payload_is_sbr(&[0xD0])); // EXT_SBR_DATA = 13
340+ assert!(fil_payload_is_sbr(&[0xE5])); // EXT_SBR_DATA_CRC = 14
341+ assert!(!fil_payload_is_sbr(&[0x10])); // EXT_FILL_DATA
342+ assert!(!fil_payload_is_sbr(&[0x00]));
343+ assert!(!fil_payload_is_sbr(&[]));
344+ }
345+
346+ /// **The integration that matters.** A decoder built from raw HE-AAC config
347+ /// bytes must decode the CORE correctly and report the DOUBLED output rate.
348+ /// Built from the plain `AudioSpecificConfig` path it reports the core rate,
349+ /// and a player believing that runs the audio at half speed — which is the
350+ /// bug this module exists to prevent.
351+ #[test]
352+ fn decoder_reports_he_aac_output_rate() {
353+ // Explicit hierarchical HE-AAC v1: 44100 output, 22050 core.
354+ let mut w = BitWriter::new();
355+ w.write(AOT_SBR as u32, 5);
356+ w.write(4, 4); // extension sfIndex = 44100
357+ w.write(1, 4); // mono
358+ w.write(AOT_AAC_LC as u32, 5);
359+ w.write(0, 3);
360+ let asc = w.into_bytes();
361+
362+ let dec = crate::AacDecoder::with_config_bytes(&asc).expect("config");
363+ assert_eq!(
364+ dec.output_sample_rate(),
365+ Some(44100),
366+ "HE-AAC must report the DOUBLED output rate"
367+ );
368+ assert_eq!(dec.sbr_support(), SbrSupport::CoreOnly);
369+ let s = dec.sbr_config().expect("sbr config");
370+ assert_eq!(s.core_sample_rate, 22050, "core decodes at half rate");
371+
372+ // Plain AAC-LC through the same path is unaffected.
373+ let plain = crate::audio_specific_config_bytes(48000, 2);
374+ let d2 = crate::AacDecoder::with_config_bytes(&plain).expect("config");
375+ assert_eq!(d2.output_sample_rate(), Some(48000));
376+ assert_eq!(d2.sbr_support(), SbrSupport::NotPresent);
377+ }
378+
379+ /// A real AAC-LC stream still round-trips through the new config path — the
380+ /// HE-AAC work must not disturb the overwhelmingly common case.
381+ #[test]
382+ fn plain_aac_still_decodes_through_the_new_path() {
383+ use crate::{AacEncoder, AacEncoderConfig};
384+ let sr = 44100u32;
385+ let n = 6 * 1024;
386+ let pcm: Vec<f32> = (0..n)
387+ .map(|i| {
388+ let t = i as f32 / sr as f32;
389+ 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
390+ })
391+ .collect();
392+ let mut enc = AacEncoder::new(AacEncoderConfig::default());
393+ enc.push_pcm(&pcm, 1, sr).unwrap();
394+ enc.finish();
395+
396+ let asc = crate::audio_specific_config_bytes(sr, 1);
397+ let mut dec = crate::AacDecoder::with_config_bytes(&asc).expect("config");
398+ let mut got = 0usize;
399+ while let Ok(p) = enc.next_packet() {
400+ got += dec.decode(&p.data, None).expect("decode").frames();
401+ }
402+ assert!(got >= n, "decoded {got} of {n}");
403+ assert_eq!(dec.sbr_support(), SbrSupport::NotPresent);
404+ }
405+}
vendor/rusty_aac/src/swb.rsadded+129 -0
@@ -0,0 +1,129 @@
1+//! Scalefactor-band (SWB) offset tables — ISO 14496-3 Annex 4.A.
2+//!
3+//! Each table lists the spectral-coefficient index where each scalefactor band
4+//! starts, ending with the transform's coefficient count (1024 for long
5+//! windows, 128 for one short window). `num_swb = table.len() - 1`. Tables are
6+//! shared across several sampling rates per the spec's grouping.
7+
8+#![allow(dead_code)]
9+
10+// ---- Long-window (1024) offsets ------------------------------------------
11+
12+const LONG_96: &[u16] = &[
13+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132,
14+ 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024,
15+];
16+
17+const LONG_64: &[u16] = &[
18+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124, 140,
19+ 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, 744, 784,
20+ 824, 864, 904, 944, 984, 1024,
21+];
22+
23+const LONG_48: &[u16] = &[
24+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160,
25+ 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704,
26+ 736, 768, 800, 832, 864, 896, 928, 1024,
27+];
28+
29+const LONG_32: &[u16] = &[
30+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160,
31+ 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704,
32+ 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
33+];
34+
35+const LONG_24: &[u16] = &[
36+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 136,
37+ 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, 600, 652,
38+ 704, 768, 832, 896, 960, 1024,
39+];
40+
41+const LONG_16: &[u16] = &[
42+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212,
43+ 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832,
44+ 896, 960, 1024,
45+];
46+
47+const LONG_8: &[u16] = &[
48+ 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, 268,
49+ 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
50+ 1024,
51+];
52+
53+// ---- Short-window (128) offsets ------------------------------------------
54+
55+const SHORT_96: &[u16] = &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128];
56+const SHORT_64: &[u16] = &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128];
57+const SHORT_48: &[u16] = &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128];
58+const SHORT_24: &[u16] = &[
59+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
60+];
61+const SHORT_16: &[u16] = &[
62+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
63+];
64+const SHORT_8: &[u16] = &[
65+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
66+];
67+
68+/// SWB offset table for a window type and sampling-frequency index. Returns the
69+/// full offset array (ending in 1024 long / 128 short); `num_swb = len - 1`.
70+pub fn swb_offsets(long: bool, fs_index: u8) -> &'static [u16] {
71+ if long {
72+ match fs_index {
73+ 0 | 1 => LONG_96,
74+ 2 => LONG_64,
75+ 3 | 4 => LONG_48,
76+ 5 => LONG_32,
77+ 6 | 7 => LONG_24,
78+ 8 | 9 | 10 => LONG_16,
79+ _ => LONG_8,
80+ }
81+ } else {
82+ match fs_index {
83+ 0 | 1 => SHORT_96,
84+ 2 => SHORT_64,
85+ 3 | 4 | 5 => SHORT_48,
86+ 6 | 7 => SHORT_24,
87+ 8 | 9 | 10 => SHORT_16,
88+ _ => SHORT_8,
89+ }
90+ }
91+}
92+
93+#[cfg(test)]
94+mod tests {
95+ use super::*;
96+
97+ fn check(table: &[u16], end: u16) {
98+ assert_eq!(table[0], 0, "must start at 0");
99+ assert_eq!(*table.last().unwrap(), end, "must end at {end}");
100+ assert!(
101+ table.windows(2).all(|w| w[1] > w[0]),
102+ "offsets must be strictly increasing"
103+ );
104+ }
105+
106+ #[test]
107+ fn all_long_tables_well_formed() {
108+ for fs in 0u8..=12 {
109+ check(swb_offsets(true, fs), 1024);
110+ }
111+ }
112+
113+ #[test]
114+ fn all_short_tables_well_formed() {
115+ for fs in 0u8..=12 {
116+ check(swb_offsets(false, fs), 128);
117+ }
118+ }
119+
120+ #[test]
121+ fn known_band_counts() {
122+ // num_swb = len - 1, against the spec's documented counts.
123+ assert_eq!(swb_offsets(true, 3).len() - 1, 49); // 48 kHz long
124+ assert_eq!(swb_offsets(true, 5).len() - 1, 51); // 32 kHz long
125+ assert_eq!(swb_offsets(true, 11).len() - 1, 40); // 8 kHz long
126+ assert_eq!(swb_offsets(false, 3).len() - 1, 14); // 48 kHz short
127+ assert_eq!(swb_offsets(false, 8).len() - 1, 15); // 16 kHz short
128+ }
129+}
vendor/rusty_aac/src/tables.rsadded+296 -0
@@ -0,0 +1,296 @@
1+//! AAC spectral + scalefactor Huffman codebook tables (ISO 14496-3 Tables
2+//! 4.A.2–4.A.13 and the scalefactor codebook).
3+//!
4+//! These are fixed standard data — the exact codeword/length pairs every AAC
5+//! decoder must use. They were transcribed from the ISO reference values and
6+//! each is checked in-tree (`codebooks_are_structurally_valid`) for entry
7+//! count, prefix-freedom, and Kraft sum, so a corrupted table fails the build's
8+//! tests rather than silently mis-decoding. All twelve are complete prefix
9+//! codes (Kraft = 1).
10+
11+#![allow(dead_code)]
12+
13+use crate::huffman::HuffBook;
14+
15+static CODES1: &[u32] = &[
16+ 0x7f8, 0x1f1, 0x7fd, 0x3f5, 0x068, 0x3f0, 0x7f7, 0x1ec, 0x7f5, 0x3f1, 0x072, 0x3f4, 0x074,
17+ 0x011, 0x076, 0x1eb, 0x06c, 0x3f6, 0x7fc, 0x1e1, 0x7f1, 0x1f0, 0x061, 0x1f6, 0x7f2, 0x1ea,
18+ 0x7fb, 0x1f2, 0x069, 0x1ed, 0x077, 0x017, 0x06f, 0x1e6, 0x064, 0x1e5, 0x067, 0x015, 0x062,
19+ 0x012, 0x000, 0x014, 0x065, 0x016, 0x06d, 0x1e9, 0x063, 0x1e4, 0x06b, 0x013, 0x071, 0x1e3,
20+ 0x070, 0x1f3, 0x7fe, 0x1e7, 0x7f3, 0x1ef, 0x060, 0x1ee, 0x7f0, 0x1e2, 0x7fa, 0x3f3, 0x06a,
21+ 0x1e8, 0x075, 0x010, 0x073, 0x1f4, 0x06e, 0x3f7, 0x7f6, 0x1e0, 0x7f9, 0x3f2, 0x066, 0x1f5,
22+ 0x7ff, 0x1f7, 0x7f4,
23+];
24+static BITS1: &[u8] = &[
25+ 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11,
26+ 9, 7, 9, 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9,
27+ 7, 9, 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11,
28+];
29+
30+static CODES2: &[u32] = &[
31+ 0x1f3, 0x06f, 0x1fd, 0x0eb, 0x023, 0x0ea, 0x1f7, 0x0e8, 0x1fa, 0x0f2, 0x02d, 0x070, 0x020,
32+ 0x006, 0x02b, 0x06e, 0x028, 0x0e9, 0x1f9, 0x066, 0x0f8, 0x0e7, 0x01b, 0x0f1, 0x1f4, 0x06b,
33+ 0x1f5, 0x0ec, 0x02a, 0x06c, 0x02c, 0x00a, 0x027, 0x067, 0x01a, 0x0f5, 0x024, 0x008, 0x01f,
34+ 0x009, 0x000, 0x007, 0x01d, 0x00b, 0x030, 0x0ef, 0x01c, 0x064, 0x01e, 0x00c, 0x029, 0x0f3,
35+ 0x02f, 0x0f0, 0x1fc, 0x071, 0x1f2, 0x0f4, 0x021, 0x0e6, 0x0f7, 0x068, 0x1f8, 0x0ee, 0x022,
36+ 0x065, 0x031, 0x002, 0x026, 0x0ed, 0x025, 0x06a, 0x1fb, 0x072, 0x1fe, 0x069, 0x02e, 0x0f6,
37+ 0x1ff, 0x06d, 0x1f6,
38+];
39+static BITS2: &[u8] = &[
40+ 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5,
41+ 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8,
42+ 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9,
43+];
44+
45+static CODES3: &[u32] = &[
46+ 0x0000, 0x0009, 0x00ef, 0x000b, 0x0019, 0x00f0, 0x01eb, 0x01e6, 0x03f2, 0x000a, 0x0035, 0x01ef,
47+ 0x0034, 0x0037, 0x01e9, 0x01ed, 0x01e7, 0x03f3, 0x01ee, 0x03ed, 0x1ffa, 0x01ec, 0x01f2, 0x07f9,
48+ 0x07f8, 0x03f8, 0x0ff8, 0x0008, 0x0038, 0x03f6, 0x0036, 0x0075, 0x03f1, 0x03eb, 0x03ec, 0x0ff4,
49+ 0x0018, 0x0076, 0x07f4, 0x0039, 0x0074, 0x03ef, 0x01f3, 0x01f4, 0x07f6, 0x01e8, 0x03ea, 0x1ffc,
50+ 0x00f2, 0x01f1, 0x0ffb, 0x03f5, 0x07f3, 0x0ffc, 0x00ee, 0x03f7, 0x7ffe, 0x01f0, 0x07f5, 0x7ffd,
51+ 0x1ffb, 0x3ffa, 0xffff, 0x00f1, 0x03f0, 0x3ffc, 0x01ea, 0x03ee, 0x3ffb, 0x0ff6, 0x0ffa, 0x7ffc,
52+ 0x07f2, 0x0ff5, 0xfffe, 0x03f4, 0x07f7, 0x7ffb, 0x0ff7, 0x0ff9, 0x7ffa,
53+];
54+static BITS3: &[u8] = &[
55+ 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6,
56+ 10, 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10,
57+ 15, 9, 11, 15, 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12,
58+ 15,
59+];
60+
61+static CODES4: &[u32] = &[
62+ 0x007, 0x016, 0x0f6, 0x018, 0x008, 0x0ef, 0x1ef, 0x0f3, 0x7f8, 0x019, 0x017, 0x0ed, 0x015,
63+ 0x001, 0x0e2, 0x0f0, 0x070, 0x3f0, 0x1ee, 0x0f1, 0x7fa, 0x0ee, 0x0e4, 0x3f2, 0x7f6, 0x3ef,
64+ 0x7fd, 0x005, 0x014, 0x0f2, 0x009, 0x004, 0x0e5, 0x0f4, 0x0e8, 0x3f4, 0x006, 0x002, 0x0e7,
65+ 0x003, 0x000, 0x06b, 0x0e3, 0x069, 0x1f3, 0x0eb, 0x0e6, 0x3f6, 0x06e, 0x06a, 0x1f4, 0x3ec,
66+ 0x1f0, 0x3f9, 0x0f5, 0x0ec, 0x7fb, 0x0ea, 0x06f, 0x3f7, 0x7f9, 0x3f3, 0xfff, 0x0e9, 0x06d,
67+ 0x3f8, 0x06c, 0x068, 0x1f5, 0x3ee, 0x1f2, 0x7f4, 0x7f7, 0x3f1, 0xffe, 0x3ed, 0x1f1, 0x7f5,
68+ 0x7fe, 0x3f5, 0x7fc,
69+];
70+static BITS4: &[u8] = &[
71+ 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5,
72+ 8, 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7,
73+ 10, 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11,
74+];
75+
76+static CODES5: &[u32] = &[
77+ 0x1fff, 0x0ff7, 0x07f4, 0x07e8, 0x03f1, 0x07ee, 0x07f9, 0x0ff8, 0x1ffd, 0x0ffd, 0x07f1, 0x03e8,
78+ 0x01e8, 0x00f0, 0x01ec, 0x03ee, 0x07f2, 0x0ffa, 0x0ff4, 0x03ef, 0x01f2, 0x00e8, 0x0070, 0x00ec,
79+ 0x01f0, 0x03ea, 0x07f3, 0x07eb, 0x01eb, 0x00ea, 0x001a, 0x0008, 0x0019, 0x00ee, 0x01ef, 0x07ed,
80+ 0x03f0, 0x00f2, 0x0073, 0x000b, 0x0000, 0x000a, 0x0071, 0x00f3, 0x07e9, 0x07ef, 0x01ee, 0x00ef,
81+ 0x0018, 0x0009, 0x001b, 0x00eb, 0x01e9, 0x07ec, 0x07f6, 0x03eb, 0x01f3, 0x00ed, 0x0072, 0x00e9,
82+ 0x01f1, 0x03ed, 0x07f7, 0x0ff6, 0x07f0, 0x03e9, 0x01ed, 0x00f1, 0x01ea, 0x03ec, 0x07f8, 0x0ff9,
83+ 0x1ffc, 0x0ffc, 0x0ff5, 0x07ea, 0x03f3, 0x03f2, 0x07f5, 0x0ffb, 0x1ffe,
84+];
85+static BITS5: &[u8] = &[
86+ 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10,
87+ 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11,
88+ 10, 9, 8, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13,
89+];
90+
91+static CODES6: &[u32] = &[
92+ 0x7fe, 0x3fd, 0x1f1, 0x1eb, 0x1f4, 0x1ea, 0x1f0, 0x3fc, 0x7fd, 0x3f6, 0x1e5, 0x0ea, 0x06c,
93+ 0x071, 0x068, 0x0f0, 0x1e6, 0x3f7, 0x1f3, 0x0ef, 0x032, 0x027, 0x028, 0x026, 0x031, 0x0eb,
94+ 0x1f7, 0x1e8, 0x06f, 0x02e, 0x008, 0x004, 0x006, 0x029, 0x06b, 0x1ee, 0x1ef, 0x072, 0x02d,
95+ 0x002, 0x000, 0x003, 0x02f, 0x073, 0x1fa, 0x1e7, 0x06e, 0x02b, 0x007, 0x001, 0x005, 0x02c,
96+ 0x06d, 0x1ec, 0x1f9, 0x0ee, 0x030, 0x024, 0x02a, 0x025, 0x033, 0x0ec, 0x1f2, 0x3f8, 0x1e4,
97+ 0x0ed, 0x06a, 0x070, 0x069, 0x074, 0x0f1, 0x3fa, 0x7ff, 0x3f9, 0x1f6, 0x1ed, 0x1f8, 0x1e9,
98+ 0x1f5, 0x3fb, 0x7fc,
99+];
100+static BITS6: &[u8] = &[
101+ 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6,
102+ 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8,
103+ 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11,
104+];
105+
106+static CODES7: &[u32] = &[
107+ 0x000, 0x005, 0x037, 0x074, 0x0f2, 0x1eb, 0x3ed, 0x7f7, 0x004, 0x00c, 0x035, 0x071, 0x0ec,
108+ 0x0ee, 0x1ee, 0x1f5, 0x036, 0x034, 0x072, 0x0ea, 0x0f1, 0x1e9, 0x1f3, 0x3f5, 0x073, 0x070,
109+ 0x0eb, 0x0f0, 0x1f1, 0x1f0, 0x3ec, 0x3fa, 0x0f3, 0x0ed, 0x1e8, 0x1ef, 0x3ef, 0x3f1, 0x3f9,
110+ 0x7fb, 0x1ed, 0x0ef, 0x1ea, 0x1f2, 0x3f3, 0x3f8, 0x7f9, 0x7fc, 0x3ee, 0x1ec, 0x1f4, 0x3f4,
111+ 0x3f7, 0x7f8, 0xffd, 0xffe, 0x7f6, 0x3f0, 0x3f2, 0x3f6, 0x7fa, 0x7fd, 0xffc, 0xfff,
112+];
113+static BITS7: &[u8] = &[
114+ 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9,
115+ 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12,
116+ 11, 10, 10, 10, 11, 11, 12, 12,
117+];
118+
119+static CODES8: &[u32] = &[
120+ 0x00e, 0x005, 0x010, 0x030, 0x06f, 0x0f1, 0x1fa, 0x3fe, 0x003, 0x000, 0x004, 0x012, 0x02c,
121+ 0x06a, 0x075, 0x0f8, 0x00f, 0x002, 0x006, 0x014, 0x02e, 0x069, 0x072, 0x0f5, 0x02f, 0x011,
122+ 0x013, 0x02a, 0x032, 0x06c, 0x0ec, 0x0fa, 0x071, 0x02b, 0x02d, 0x031, 0x06d, 0x070, 0x0f2,
123+ 0x1f9, 0x0ef, 0x068, 0x033, 0x06b, 0x06e, 0x0ee, 0x0f9, 0x3fc, 0x1f8, 0x074, 0x073, 0x0ed,
124+ 0x0f0, 0x0f6, 0x1f6, 0x1fd, 0x3fd, 0x0f3, 0x0f4, 0x0f7, 0x1f7, 0x1fb, 0x1fc, 0x3ff,
125+];
126+static BITS8: &[u8] = &[
127+ 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8,
128+ 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9,
129+ 9, 10,
130+];
131+
132+static CODES9: &[u32] = &[
133+ 0x0000, 0x0005, 0x0037, 0x00e7, 0x01de, 0x03ce, 0x03d9, 0x07c8, 0x07cd, 0x0fc8, 0x0fdd, 0x1fe4,
134+ 0x1fec, 0x0004, 0x000c, 0x0035, 0x0072, 0x00ea, 0x00ed, 0x01e2, 0x03d1, 0x03d3, 0x03e0, 0x07d8,
135+ 0x0fcf, 0x0fd5, 0x0036, 0x0034, 0x0071, 0x00e8, 0x00ec, 0x01e1, 0x03cf, 0x03dd, 0x03db, 0x07d0,
136+ 0x0fc7, 0x0fd4, 0x0fe4, 0x00e6, 0x0070, 0x00e9, 0x01dd, 0x01e3, 0x03d2, 0x03dc, 0x07cc, 0x07ca,
137+ 0x07de, 0x0fd8, 0x0fea, 0x1fdb, 0x01df, 0x00eb, 0x01dc, 0x01e6, 0x03d5, 0x03de, 0x07cb, 0x07dd,
138+ 0x07dc, 0x0fcd, 0x0fe2, 0x0fe7, 0x1fe1, 0x03d0, 0x01e0, 0x01e4, 0x03d6, 0x07c5, 0x07d1, 0x07db,
139+ 0x0fd2, 0x07e0, 0x0fd9, 0x0feb, 0x1fe3, 0x1fe9, 0x07c4, 0x01e5, 0x03d7, 0x07c6, 0x07cf, 0x07da,
140+ 0x0fcb, 0x0fda, 0x0fe3, 0x0fe9, 0x1fe6, 0x1ff3, 0x1ff7, 0x07d3, 0x03d8, 0x03e1, 0x07d4, 0x07d9,
141+ 0x0fd3, 0x0fde, 0x1fdd, 0x1fd9, 0x1fe2, 0x1fea, 0x1ff1, 0x1ff6, 0x07d2, 0x03d4, 0x03da, 0x07c7,
142+ 0x07d7, 0x07e2, 0x0fce, 0x0fdb, 0x1fd8, 0x1fee, 0x3ff0, 0x1ff4, 0x3ff2, 0x07e1, 0x03df, 0x07c9,
143+ 0x07d6, 0x0fca, 0x0fd0, 0x0fe5, 0x0fe6, 0x1feb, 0x1fef, 0x3ff3, 0x3ff4, 0x3ff5, 0x0fe0, 0x07ce,
144+ 0x07d5, 0x0fc6, 0x0fd1, 0x0fe1, 0x1fe0, 0x1fe8, 0x1ff0, 0x3ff1, 0x3ff8, 0x3ff6, 0x7ffc, 0x0fe8,
145+ 0x07df, 0x0fc9, 0x0fd7, 0x0fdc, 0x1fdc, 0x1fdf, 0x1fed, 0x1ff5, 0x3ff9, 0x3ffb, 0x7ffd, 0x7ffe,
146+ 0x1fe7, 0x0fcc, 0x0fd6, 0x0fdf, 0x1fde, 0x1fda, 0x1fe5, 0x1ff2, 0x3ffa, 0x3ff7, 0x3ffc, 0x3ffd,
147+ 0x7fff,
148+];
149+static BITS9: &[u8] = &[
150+ 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6,
151+ 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8,
152+ 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11,
153+ 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13,
154+ 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13,
155+ 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, 13,
156+ 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
157+];
158+
159+static CODES10: &[u32] = &[
160+ 0x022, 0x008, 0x01d, 0x026, 0x05f, 0x0d3, 0x1cf, 0x3d0, 0x3d7, 0x3ed, 0x7f0, 0x7f6, 0xffd,
161+ 0x007, 0x000, 0x001, 0x009, 0x020, 0x054, 0x060, 0x0d5, 0x0dc, 0x1d4, 0x3cd, 0x3de, 0x7e7,
162+ 0x01c, 0x002, 0x006, 0x00c, 0x01e, 0x028, 0x05b, 0x0cd, 0x0d9, 0x1ce, 0x1dc, 0x3d9, 0x3f1,
163+ 0x025, 0x00b, 0x00a, 0x00d, 0x024, 0x057, 0x061, 0x0cc, 0x0dd, 0x1cc, 0x1de, 0x3d3, 0x3e7,
164+ 0x05d, 0x021, 0x01f, 0x023, 0x027, 0x059, 0x064, 0x0d8, 0x0df, 0x1d2, 0x1e2, 0x3dd, 0x3ee,
165+ 0x0d1, 0x055, 0x029, 0x056, 0x058, 0x062, 0x0ce, 0x0e0, 0x0e2, 0x1da, 0x3d4, 0x3e3, 0x7eb,
166+ 0x1c9, 0x05e, 0x05a, 0x05c, 0x063, 0x0ca, 0x0da, 0x1c7, 0x1ca, 0x1e0, 0x3db, 0x3e8, 0x7ec,
167+ 0x1e3, 0x0d2, 0x0cb, 0x0d0, 0x0d7, 0x0db, 0x1c6, 0x1d5, 0x1d8, 0x3ca, 0x3da, 0x7ea, 0x7f1,
168+ 0x1e1, 0x0d4, 0x0cf, 0x0d6, 0x0de, 0x0e1, 0x1d0, 0x1d6, 0x3d1, 0x3d5, 0x3f2, 0x7ee, 0x7fb,
169+ 0x3e9, 0x1cd, 0x1c8, 0x1cb, 0x1d1, 0x1d7, 0x1df, 0x3cf, 0x3e0, 0x3ef, 0x7e6, 0x7f8, 0xffa,
170+ 0x3eb, 0x1dd, 0x1d3, 0x1d9, 0x1db, 0x3d2, 0x3cc, 0x3dc, 0x3ea, 0x7ed, 0x7f3, 0x7f9, 0xff9,
171+ 0x7f2, 0x3ce, 0x1e4, 0x3cb, 0x3d8, 0x3d6, 0x3e2, 0x3e5, 0x7e8, 0x7f4, 0x7f5, 0x7f7, 0xffb,
172+ 0x7fa, 0x3ec, 0x3df, 0x3e1, 0x3e4, 0x3e6, 0x3f0, 0x7e9, 0x7ef, 0xff8, 0xffe, 0xffc, 0xfff,
173+];
174+static BITS10: &[u8] = &[
175+ 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5,
176+ 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7,
177+ 8, 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10,
178+ 10, 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11,
179+ 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12,
180+ 11, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12,
181+ 12, 12,
182+];
183+
184+static CODES11: &[u32] = &[
185+ 0x000, 0x006, 0x019, 0x03d, 0x09c, 0x0c6, 0x1a7, 0x390, 0x3c2, 0x3df, 0x7e6, 0x7f3, 0xffb,
186+ 0x7ec, 0xffa, 0xffe, 0x38e, 0x005, 0x001, 0x008, 0x014, 0x037, 0x042, 0x092, 0x0af, 0x191,
187+ 0x1a5, 0x1b5, 0x39e, 0x3c0, 0x3a2, 0x3cd, 0x7d6, 0x0ae, 0x017, 0x007, 0x009, 0x018, 0x039,
188+ 0x040, 0x08e, 0x0a3, 0x0b8, 0x199, 0x1ac, 0x1c1, 0x3b1, 0x396, 0x3be, 0x3ca, 0x09d, 0x03c,
189+ 0x015, 0x016, 0x01a, 0x03b, 0x044, 0x091, 0x0a5, 0x0be, 0x196, 0x1ae, 0x1b9, 0x3a1, 0x391,
190+ 0x3a5, 0x3d5, 0x094, 0x09a, 0x036, 0x038, 0x03a, 0x041, 0x08c, 0x09b, 0x0b0, 0x0c3, 0x19e,
191+ 0x1ab, 0x1bc, 0x39f, 0x38f, 0x3a9, 0x3cf, 0x093, 0x0bf, 0x03e, 0x03f, 0x043, 0x045, 0x09e,
192+ 0x0a7, 0x0b9, 0x194, 0x1a2, 0x1ba, 0x1c3, 0x3a6, 0x3a7, 0x3bb, 0x3d4, 0x09f, 0x1a0, 0x08f,
193+ 0x08d, 0x090, 0x098, 0x0a6, 0x0b6, 0x0c4, 0x19f, 0x1af, 0x1bf, 0x399, 0x3bf, 0x3b4, 0x3c9,
194+ 0x3e7, 0x0a8, 0x1b6, 0x0ab, 0x0a4, 0x0aa, 0x0b2, 0x0c2, 0x0c5, 0x198, 0x1a4, 0x1b8, 0x38c,
195+ 0x3a4, 0x3c4, 0x3c6, 0x3dd, 0x3e8, 0x0ad, 0x3af, 0x192, 0x0bd, 0x0bc, 0x18e, 0x197, 0x19a,
196+ 0x1a3, 0x1b1, 0x38d, 0x398, 0x3b7, 0x3d3, 0x3d1, 0x3db, 0x7dd, 0x0b4, 0x3de, 0x1a9, 0x19b,
197+ 0x19c, 0x1a1, 0x1aa, 0x1ad, 0x1b3, 0x38b, 0x3b2, 0x3b8, 0x3ce, 0x3e1, 0x3e0, 0x7d2, 0x7e5,
198+ 0x0b7, 0x7e3, 0x1bb, 0x1a8, 0x1a6, 0x1b0, 0x1b2, 0x1b7, 0x39b, 0x39a, 0x3ba, 0x3b5, 0x3d6,
199+ 0x7d7, 0x3e4, 0x7d8, 0x7ea, 0x0ba, 0x7e8, 0x3a0, 0x1bd, 0x1b4, 0x38a, 0x1c4, 0x392, 0x3aa,
200+ 0x3b0, 0x3bc, 0x3d7, 0x7d4, 0x7dc, 0x7db, 0x7d5, 0x7f0, 0x0c1, 0x7fb, 0x3c8, 0x3a3, 0x395,
201+ 0x39d, 0x3ac, 0x3ae, 0x3c5, 0x3d8, 0x3e2, 0x3e6, 0x7e4, 0x7e7, 0x7e0, 0x7e9, 0x7f7, 0x190,
202+ 0x7f2, 0x393, 0x1be, 0x1c0, 0x394, 0x397, 0x3ad, 0x3c3, 0x3c1, 0x3d2, 0x7da, 0x7d9, 0x7df,
203+ 0x7eb, 0x7f4, 0x7fa, 0x195, 0x7f8, 0x3bd, 0x39c, 0x3ab, 0x3a8, 0x3b3, 0x3b9, 0x3d0, 0x3e3,
204+ 0x3e5, 0x7e2, 0x7de, 0x7ed, 0x7f1, 0x7f9, 0x7fc, 0x193, 0xffd, 0x3dc, 0x3b6, 0x3c7, 0x3cc,
205+ 0x3cb, 0x3d9, 0x3da, 0x7d3, 0x7e1, 0x7ee, 0x7ef, 0x7f5, 0x7f6, 0xffc, 0xfff, 0x19d, 0x1c2,
206+ 0x0b5, 0x0a1, 0x096, 0x097, 0x095, 0x099, 0x0a0, 0x0a2, 0x0ac, 0x0a9, 0x0b1, 0x0b3, 0x0bb,
207+ 0x0c0, 0x18f, 0x004,
208+];
209+static BITS11: &[u8] = &[
210+ 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9,
211+ 10, 10, 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7,
212+ 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8,
213+ 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10,
214+ 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9,
215+ 9, 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11,
216+ 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10,
217+ 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11,
218+ 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, 10, 10, 10, 10,
219+ 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11,
220+ 11, 12, 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5,
221+];
222+
223+static SF_CODES: &[u32] = &[
224+ 0x3ffe8, 0x3ffe6, 0x3ffe7, 0x3ffe5, 0x7fff5, 0x7fff1, 0x7ffed, 0x7fff6, 0x7ffee, 0x7ffef,
225+ 0x7fff0, 0x7fffc, 0x7fffd, 0x7ffff, 0x7fffe, 0x7fff7, 0x7fff8, 0x7fffb, 0x7fff9, 0x3ffe4,
226+ 0x7fffa, 0x3ffe3, 0x1ffef, 0x1fff0, 0x0fff5, 0x1ffee, 0x0fff2, 0x0fff3, 0x0fff4, 0x0fff1,
227+ 0x07ff6, 0x07ff7, 0x03ff9, 0x03ff5, 0x03ff7, 0x03ff3, 0x03ff6, 0x03ff2, 0x01ff7, 0x01ff5,
228+ 0x00ff9, 0x00ff7, 0x00ff6, 0x007f9, 0x00ff4, 0x007f8, 0x003f9, 0x003f7, 0x003f5, 0x001f8,
229+ 0x001f7, 0x000fa, 0x000f8, 0x000f6, 0x00079, 0x0003a, 0x00038, 0x0001a, 0x0000b, 0x00004,
230+ 0x00000, 0x0000a, 0x0000c, 0x0001b, 0x00039, 0x0003b, 0x00078, 0x0007a, 0x000f7, 0x000f9,
231+ 0x001f6, 0x001f9, 0x003f4, 0x003f6, 0x003f8, 0x007f5, 0x007f4, 0x007f6, 0x007f7, 0x00ff5,
232+ 0x00ff8, 0x01ff4, 0x01ff6, 0x01ff8, 0x03ff8, 0x03ff4, 0x0fff0, 0x07ff4, 0x0fff6, 0x07ff5,
233+ 0x3ffe2, 0x7ffd9, 0x7ffda, 0x7ffdb, 0x7ffdc, 0x7ffdd, 0x7ffde, 0x7ffd8, 0x7ffd2, 0x7ffd3,
234+ 0x7ffd4, 0x7ffd5, 0x7ffd6, 0x7fff2, 0x7ffdf, 0x7ffe7, 0x7ffe8, 0x7ffe9, 0x7ffea, 0x7ffeb,
235+ 0x7ffe6, 0x7ffe0, 0x7ffe1, 0x7ffe2, 0x7ffe3, 0x7ffe4, 0x7ffe5, 0x7ffd7, 0x7ffec, 0x7fff4,
236+ 0x7fff3,
237+];
238+static SF_BITS: &[u8] = &[
239+ 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17,
240+ 16, 17, 16, 16, 16, 16, 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10,
241+ 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11,
242+ 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
243+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
244+];
245+
246+/// Spectral Huffman codebooks indexed by codebook number 0..=11. Index 0 is the
247+/// ZERO codebook (never decoded), represented by an empty book.
248+pub static SPECTRAL_BOOKS: [HuffBook; 12] = [
249+ HuffBook::new(&[], &[]),
250+ HuffBook::new(CODES1, BITS1),
251+ HuffBook::new(CODES2, BITS2),
252+ HuffBook::new(CODES3, BITS3),
253+ HuffBook::new(CODES4, BITS4),
254+ HuffBook::new(CODES5, BITS5),
255+ HuffBook::new(CODES6, BITS6),
256+ HuffBook::new(CODES7, BITS7),
257+ HuffBook::new(CODES8, BITS8),
258+ HuffBook::new(CODES9, BITS9),
259+ HuffBook::new(CODES10, BITS10),
260+ HuffBook::new(CODES11, BITS11),
261+];
262+
263+/// The scalefactor codebook (differential scalefactor Huffman).
264+pub static SCALEFACTOR_BOOK: HuffBook = HuffBook::new(SF_CODES, SF_BITS);
265+
266+/// Spectral codebook for codebook number `cb` (1..=11).
267+pub fn spectral_book(cb: u8) -> &'static HuffBook {
268+ &SPECTRAL_BOOKS[cb as usize]
269+}
270+
271+#[cfg(test)]
272+mod tests {
273+ use super::*;
274+
275+ #[test]
276+ fn codebooks_are_structurally_valid() {
277+ // Expected entry counts per spectral codebook (dim and value range).
278+ let expected = [81, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
279+ for (i, &count) in expected.iter().enumerate() {
280+ let book = &SPECTRAL_BOOKS[i + 1];
281+ assert_eq!(book.count(), count, "cb{} count", i + 1);
282+ assert!(book.is_prefix_free(), "cb{} prefix-free", i + 1);
283+ // The 11 spectral books are complete codes.
284+ assert!(
285+ (book.kraft_sum() - 1.0).abs() < 1e-9,
286+ "cb{} kraft = {}",
287+ i + 1,
288+ book.kraft_sum()
289+ );
290+ }
291+ // Scalefactor book: 121 entries, prefix-free, complete code.
292+ assert_eq!(SCALEFACTOR_BOOK.count(), 121);
293+ assert!(SCALEFACTOR_BOOK.is_prefix_free());
294+ assert!((SCALEFACTOR_BOOK.kraft_sum() - 1.0).abs() < 1e-9);
295+ }
296+}