forge
Explore
Log in

Don't you dare go Hollow

A Matroska film opens, its 10-bit picture and its 5.1 sound alike

Browse files at this commit

b083a3b27b507f5c9e86b4827251061cca6f02e3Ahmet Kaan GümüşParent: 88fbed0
  • feat
    • a Matroska film opens, its 10-bit picture and its 5.1 sound alike
Show full message
✨ feat(import): a Matroska film opens, its 10-bit picture and its 5.1 sound alike

mkv HEVC demux (Main/Main10), a P010 pool in the hardware path read back to
I420, mkv audio through symphonia's Matroska reader with rusty_aac decoding
what symphonia's own AAC refuses (anything wider than stereo), and a BS.775
fold of 5.1 down to the stereo the output device takes.

vendor/rusty_aac is 0.5.0 with one local patch: its decoder's IMDCT caches the
cosine matrix instead of calling cos() per term, 11x faster and the difference
between playable and not.

31 changed files +10002 -148

Cargo.lockmodified+18 -0
@@ -1638,6 +1638,7 @@ dependencies = [
1638 "oxideav-ac3",1638 "oxideav-ac3",
1639 "oxideav-core",1639 "oxideav-core",
1640 "rav1e",1640 "rav1e",
1641+ "rusty_aac",
1641 "rusty_h264",1642 "rusty_h264",
1642 "symphonia",1643 "symphonia",
1643 "symphonia-codec-aac",1644 "symphonia-codec-aac",
@@ -4880,6 +4881,10 @@ version = "1.0.23"
4880 source = "registry+https://github.com/rust-lang/crates.io-index"4881 source = "registry+https://github.com/rust-lang/crates.io-index"
4881 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"4882 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
4882 4883
4884+[[package]]
4885+name = "rusty_aac"
4886+version = "0.5.0"
4887+
4883 [[package]]4888 [[package]]
4884 name = "rusty_h264"4889 name = "rusty_h264"
4885 version = "0.8.0"4890 version = "0.8.0"
@@ -5600,6 +5605,7 @@ dependencies = [
5600 "symphonia-codec-vorbis",5605 "symphonia-codec-vorbis",
5601 "symphonia-core",5606 "symphonia-core",
5602 "symphonia-format-isomp4",5607 "symphonia-format-isomp4",
5608+ "symphonia-format-mkv",
5603 "symphonia-format-ogg",5609 "symphonia-format-ogg",
5604 "symphonia-format-riff",5610 "symphonia-format-riff",
5605 "symphonia-metadata",5611 "symphonia-metadata",
@@ -5709,6 +5715,18 @@ dependencies = [
5709 "symphonia-metadata",5715 "symphonia-metadata",
5710 ]5716 ]
5711 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+
5712 [[package]]5730 [[package]]
5713 name = "symphonia-format-ogg"5731 name = "symphonia-format-ogg"
5714 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/main.rsmodified+1 -1
@@ -5905,7 +5905,7 @@ const FORMATS: [(Option<Format>, &str, &str); 9] = [
5905 (Some(Format::Flac), "FLAC", "lossless — audio only"),5905 (Some(Format::Flac), "FLAC", "lossless — audio only"),
5906 (None, "MP3", "encoder is LGPL — licence decision pending"),5906 (None, "MP3", "encoder is LGPL — licence decision pending"),
5907 (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),5907 (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),
5908- (None, "AAC", "no pure-Rust AAC encoder"),5908+ (None, "AAC", "encoder exists (rusty_aac) but is not wired here yet"),
5909 (5909 (
5910 None,5910 None,
5911 "HEVC",5911 "HEVC",
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+10 -1
@@ -28,7 +28,9 @@ symphonia-codec-aac = "0.6"
28 # The umbrella crate for the standalone audio files: one dependency instead of28 # The umbrella crate for the standalone audio files: one dependency instead of
29 # seven, and its `default::get_probe`/`get_codecs` are the registries this would29 # seven, and its `default::get_probe`/`get_codecs` are the registries this would
30 # otherwise hand-build. Explicit feature list rather than the default one -- no30 # otherwise hand-build. Explicit feature list rather than the default one -- no
31-# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits.31+# ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus
32+# `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of
33+# a Matroska video file is read, the picture having its own demuxer here.
32 # There is no opus/ac3/dts feature at any symphonia version, which is why those34 # There is no opus/ac3/dts feature at any symphonia version, which is why those
33 # are refused rather than promised.35 # are refused rather than promised.
34 symphonia = { version = "0.6", default-features = false, features = [36 symphonia = { version = "0.6", default-features = false, features = [
@@ -38,12 +40,19 @@ symphonia = { version = "0.6", default-features = false, features = [
38 "id3v1",40 "id3v1",
39 "id3v2",41 "id3v2",
40 "isomp4",42 "isomp4",
43+ "mkv",
41 "mp3",44 "mp3",
42 "ogg",45 "ogg",
43 "pcm",46 "pcm",
44 "vorbis",47 "vorbis",
45 "wav",48 "wav",
46 ] }49 ] }
50+# The AAC decoder symphonia is not: its own refuses anything wider than stereo
51+# outright (`aac/mod.rs:93`, "aac: aac too complex"), and a 5.1 film soundtrack
52+# in an mkv is exactly that. Pure Rust with no dependencies of its own, from the
53+# same family as `rusty_h264`, and it hands 5.1 back already reordered into
54+# FL, FR, FC, LFE, BL, BR -- which is the order the downmix here folds.
55+rusty_aac = "0.5"
47 oxideav-ac3 = "=0.0.10"56 oxideav-ac3 = "=0.0.10"
48 oxideav-core = "0.1.34"57 oxideav-core = "0.1.34"
49 # The software AV1 encoder, and the only new name in this list that was already58 # The software AV1 encoder, and the only new name in this list that was already
crates/engine/src/audio.rsmodified+189 -28
@@ -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
@@ -490,14 +492,15 @@ impl AudioSession {
490 /// -- nothing to tell the user there. Header only, and only worth calling492 /// -- nothing to tell the user there. Header only, and only worth calling
491 /// once the open has already returned no audio.493 /// once the open has already returned no audio.
492 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {494 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
493- // Matroska: the demuxer reads its picture and nothing else yet, so a495+ // Matroska: AAC is read out of one ([`Track::open`]) and everything
494- // file that has sound is told so by name rather than playing silent496+ // 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 all497+ // version -- is named rather than left playing silent with no reason
496- // returns `None` here like any other silent file.498+ // given. A Matroska file with no audio track at all returns `None` here
499+ // like any other silent file.
497 if crate::demux::is_matroska(path.as_ref()) {500 if crate::demux::is_matroska(path.as_ref()) {
498 return Ok(501 return Ok(
499 crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {502 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")503+ format!("the {codec} track of this Matroska file cannot be decoded (AAC only)")
501 }),504 }),
502 );505 );
503 }506 }
@@ -546,11 +549,22 @@ impl AudioSession {
546 /// and an ALAC `.m4a` only half is.549 /// and an ALAC `.m4a` only half is.
547 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {550 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
548 let path = path.as_ref();551 let path = path.as_ref();
549- // A Matroska file's audio tracks are not readable here yet ([`Track`]),552+ // 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 as553+ // reader's default track ([`SymTrack::open`]) -- so it lists like a
551- // the silent source it currently is.554+ // standalone audio file rather than like an mp4, and one with no
555+ // readable track at all lists as the silent source it is.
552 if crate::demux::is_matroska(path) {556 if crate::demux::is_matroska(path) {
553- return Ok(Vec::new());557+ let Ok(track) = SymTrack::open(path) else {
558+ return Ok(Vec::new());
559+ };
560+ return Ok(vec![StreamInfo {
561+ index: 0,
562+ codec: track.codec.into(),
563+ channels: track.channels,
564+ sample_rate: track.sample_rate,
565+ lang: None,
566+ decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),
567+ }]);
554 }568 }
555 if crate::is_audio(path) {569 if crate::is_audio(path) {
556 let track = SymTrack::open(path)?;570 let track = SymTrack::open(path)?;
@@ -648,7 +662,8 @@ impl AudioSession {
648 /// windows [`open_segments`](Self::open_segments) decodes — copied out662 /// windows [`open_segments`](Self::open_segments) decodes — copied out
649 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go663 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
650 /// straight into an mp4 writer, which is the only way to keep audio in an664 /// straight into an mp4 writer, which is the only way to keep audio in an
651- /// export at all (no pure-Rust AAC encoder exists).665+ /// export at all (nothing here *encodes* AAC: the vendored `rusty_aac` has
666+ /// an encoder, but no export path is wired to it).
652 ///667 ///
653 /// Cut points do not land on 1024-sample boundaries, so each segment is668 /// Cut points do not land on 1024-sample boundaries, so each segment is
654 /// rounded to whole packets against an error carried across the joins (see669 /// rounded to whole packets against an error carried across the joins (see
@@ -834,6 +849,24 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
834 match Track::open(path, stream)? {849 match Track::open(path, stream)? {
835 None => Ok(None),850 None => Ok(None),
836 Some(Track::Aac(track)) => Ok(Some(track)),851 Some(Track::Aac(track)) => Ok(Some(track)),
852+ // A Matroska source gets its own words: its packets *are* AAC, so
853+ // "export needs AAC audio today" would read as a contradiction. What
854+ // they are not is packets of an mp4 sample table, which is what the
855+ // copy walks -- and refusing beats writing a film with no sound in it.
856+ //
857+ // ponytail: the ceiling is the copy path being written against the mp4
858+ // reader, not anything about the bytes. Upgrade path is the same one
859+ // every other refusal here names -- an AAC encoder, or a `copy_segments`
860+ // that walks a Matroska track -- and either would let this through.
861+ Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
862+ "{}'s sound is AAC inside a Matroska file, which an mp4 export cannot copy: \
863+ it copies packets out of an mp4's own sample table. Export WAV or FLAC for \
864+ the sound, or AV1 for the picture alone",
865+ path.file_name()
866+ .unwrap_or(path.as_os_str())
867+ .to_string_lossy(),
868+ )
869+ .into()),
837 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),870 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
838 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`871 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
839 // sample table can hold, and there is no AAC encoder here to turn it872 // sample table can hold, and there is no AAC encoder here to turn it
@@ -878,11 +911,20 @@ impl Track {
878 /// has exactly one, so any `stream` above 0 there is a promise the file911 /// has exactly one, so any `stream` above 0 there is a promise the file
879 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.912 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
880 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {913 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
881- // A Matroska file's sound is not wired to either reader yet: its picture914+ // A Matroska file goes straight to symphonia, whose `mkv` reader is the
882- // is what this slice delivers, and the source counts as a silent one --915+ // one thing here that reads its packets -- neither mp4 reader can open
883- // which `AudioSession::unsupported` puts into words for the user.916+ // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia
917+ // has no such decoder at any version) leaves the source the silent one
918+ // it always was, which `AudioSession::unsupported` puts into words,
919+ // rather than failing the import of a file whose picture is fine.
884 if crate::demux::is_matroska(path) {920 if crate::demux::is_matroska(path) {
885- return Ok(None);921+ if stream > 0 {
922+ return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
923+ }
924+ return Ok(SymTrack::open(path)
925+ .ok()
926+ .filter(|t| t.decoder().is_ok())
927+ .map(Self::Sym));
886 }928 }
887 let audio_file = crate::is_audio(path);929 let audio_file = crate::is_audio(path);
888 // Ahead of the AAC reader, because that one answers "not AAC" for a930 // Ahead of the AAC reader, because that one answers "not AAC" for a
@@ -995,7 +1037,12 @@ struct SymTrack {
995 reader: Box<dyn FormatReader>,1037 reader: Box<dyn FormatReader>,
996 track_id: u32,1038 track_id: u32,
997 sample_rate: u32,1039 sample_rate: u32,
1040+ /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,
1041+ /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's
1042+ /// decoder folds its own.
998 channels: u16,1043 channels: u16,
1044+ /// What the decoder emits, which is what the fold reads.
1045+ source_channels: u16,
999 /// Frames per channel of audible audio, `None` when the header does not say.1046 /// Frames per channel of audible audio, `None` when the header does not say.
1000 total_samples: Option<u64>,1047 total_samples: Option<u64>,
1001 /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the1048 /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the
@@ -1050,7 +1097,11 @@ impl SymTrack {
1050 reader,1097 reader,
1051 track_id,1098 track_id,
1052 sample_rate,1099 sample_rate,
1053- channels,1100+ // 5.1 arrives as a stereo source, whatever it was stored as; every
1101+ // other layout is passed through and refused above stereo by
1102+ // [`Track::channels`], where it always was.
1103+ channels: if channels == 6 { 2 } else { channels },
1104+ source_channels: channels,
1054 total_samples: num_frames,1105 total_samples: num_frames,
1055 priming: u64::from(delay.unwrap_or(0)),1106 priming: u64::from(delay.unwrap_or(0)),
1056 time_base,1107 time_base,
@@ -1061,9 +1112,28 @@ impl SymTrack {
1061 1112
1062 /// A fresh decoder: seeking mid-stream leaves state that belongs to the1113 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
1063 /// packets we skipped, exactly as on the AAC path.1114 /// packets we skipped, exactly as on the AAC path.
1064- fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> {1115+ ///
1065- Ok(symphonia::default::get_codecs()1116+ /// Which decoder is not the caller's business, and it is not always
1066- .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?)1117+ /// symphonia's: its AAC decoder refuses anything wider than stereo outright
1118+ /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track
1119+ /// of a film in an mkv, so that one goes to `rusty_aac` instead.
1120+ fn decoder(&self) -> crate::Result<SymDecoder> {
1121+ let fold = self.source_channels != self.channels;
1122+ if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 {
1123+ let asc = self
1124+ .params
1125+ .extra_data
1126+ .as_deref()
1127+ .ok_or("a multichannel AAC track with no AudioSpecificConfig")?;
1128+ let decoder = rusty_aac::AacDecoder::with_config_bytes(asc)
1129+ .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?;
1130+ return Ok(SymDecoder::Aac(Box::new(decoder), fold));
1131+ }
1132+ Ok(SymDecoder::Sym(
1133+ symphonia::default::get_codecs()
1134+ .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
1135+ fold,
1136+ ))
1067 }1137 }
1068 1138
1069 /// `secs` on this source's audible timeline into media samples (priming1139 /// `secs` on this source's audible timeline into media samples (priming
@@ -1079,6 +1149,65 @@ impl SymTrack {
1079 }1149 }
1080 }1150 }
1081 1151
1152+/// One packet in, interleaved f32 out — whichever library did the decoding, and
1153+/// already folded to the layout [`SymTrack::channels`] promised. The flag is
1154+/// that fold: `true` for a 5.1 track, and there is nothing else it can be.
1155+enum SymDecoder {
1156+ Sym(Box<dyn AudioDecoder>, bool),
1157+ /// Boxed because the decoder carries its own IMDCT tables and this enum is
1158+ /// moved into the worker.
1159+ Aac(Box<rusty_aac::AacDecoder>, bool),
1160+}
1161+
1162+impl SymDecoder {
1163+ fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
1164+ match self {
1165+ Self::Sym(decoder, fold) => {
1166+ decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
1167+ fold_5_1(out, *fold);
1168+ }
1169+ Self::Aac(decoder, fold) => {
1170+ let pcm = decoder
1171+ .decode(&packet.data, None)
1172+ .map_err(|e| format!("AAC decode failed: {e}"))?;
1173+ *out = pcm.samples;
1174+ fold_5_1(out, *fold);
1175+ }
1176+ }
1177+ Ok(())
1178+ }
1179+}
1180+
1181+/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of
1182+/// each side join that side at -3 dB, and the LFE is dropped -- it carries no
1183+/// programme a stereo pair could put anywhere. Both outputs are divided by the
1184+/// sum of their own coefficients, so a source at full scale cannot come out
1185+/// clipped; that is what every player does by default.
1186+///
1187+/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders
1188+/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls,
1189+/// Rs, LFE element order into it: `decode.rs:779`).
1190+///
1191+/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands
1192+/// out, which does not normalise and can overload -- so a film plays quieter
1193+/// here than in a player beside it. It is the loudness the AC-3 5.1 path already
1194+/// has (measured within 1.3 dB), so the two agree; the upgrade path is a
1195+/// limiter on the output, at which point the coefficients can go back to 1.0.
1196+fn fold_5_1(samples: &mut Vec<f32>, fold: bool) {
1197+ if !fold {
1198+ return;
1199+ }
1200+ const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2;
1201+ const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE);
1202+ for frame in 0..samples.len() / 6 {
1203+ let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6])
1204+ .expect("six samples of a 5.1 frame");
1205+ samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM;
1206+ samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM;
1207+ }
1208+ samples.truncate(samples.len() / 6 * 2);
1209+}
1210+
1082 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read1211 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read
1083 /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder1212 /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder
1084 /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and1213 /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and
@@ -2085,14 +2214,10 @@ fn run_sym(
2085 if pos >= seg.media_end {2214 if pos >= seg.media_end {
2086 return true; // segment done, on to the next one2215 return true; // segment done, on to the next one
2087 }2216 }
2088- let buf = match decoder.decode(&packet) {2217+ if let Err(e) = decoder.decode(&packet, &mut interleaved) {
2089- Ok(buf) => buf,2218+ eprintln!("audio decode error at sample {pos}: {e}");
2090- Err(e) => {2219+ return true;
2091- eprintln!("audio decode error at sample {pos}: {e}");2220+ }
2092- return true;
2093- }
2094- };
2095- buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
2096 let next = pos + (interleaved.len() / channels) as u64;2221 let next = pos + (interleaved.len() / channels) as u64;
2097 // Reborrowed per packet: the filter memory has to carry across the2222 // Reborrowed per packet: the filter memory has to carry across the
2098 // packet boundary, so this is one `EqState` for the whole segment.2223 // packet boundary, so this is one `EqState` for the whole segment.
@@ -2114,7 +2239,43 @@ fn run_sym(
2114 2239
2115 #[cfg(test)]2240 #[cfg(test)]
2116 mod tests {2241 mod tests {
2117- use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run};2242+ use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run};
2243+
2244+ /// The 5.1 fold: each side keeps its own front channel, takes the centre
2245+ /// and its own surround at -3 dB, drops the LFE, and comes out unable to
2246+ /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR.
2247+ #[test]
2248+ fn five_one_folds_to_stereo_without_clipping() {
2249+ // One frame per channel at full scale, one channel at a time.
2250+ for (channel, (left, right)) in [
2251+ (0, (1.0, 0.0)), // FL
2252+ (1, (0.0, 1.0)), // FR
2253+ (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC
2254+ (3, (0.0, 0.0)), // LFE, dropped
2255+ (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL
2256+ (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR
2257+ ] {
2258+ let mut frame = vec![0.0f32; 6];
2259+ frame[channel] = 1.0;
2260+ fold_5_1(&mut frame, true);
2261+ let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);
2262+ assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame");
2263+ assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2264+ assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2265+ }
2266+ // Every channel at once is what a normalised fold exists for.
2267+ let mut loud = vec![1.0f32; 12];
2268+ fold_5_1(&mut loud, true);
2269+ assert_eq!(loud.len(), 4);
2270+ assert!(
2271+ loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
2272+ "full scale in, full scale out, never past it: {loud:?}"
2273+ );
2274+ // A track that is not 5.1 is handed over untouched.
2275+ let mut stereo = vec![0.5f32, -0.5];
2276+ fold_5_1(&mut stereo, false);
2277+ assert_eq!(stereo, [0.5, -0.5]);
2278+ }
2118 2279
2119 /// A real AAC track: one stts entry, N packets of 1024.2280 /// A real AAC track: one stts entry, N packets of 1024.
2120 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {2281 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+7 -5
@@ -3,7 +3,7 @@
3 //!3 //!
4 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it4 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
5 //! is impossible — while audio is copied packet for packet, because there is no5 //! is impossible — while audio is copied packet for packet, because there is no
6-//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such6+//! AAC encoder wired here to re-encode with. The audio-only formats have no such
7 //! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so7 //! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so
8 //! those are *decoded* out of the timeline instead of copied. The worker owns8 //! those are *decoded* out of the timeline instead of copied. The worker owns
9 //! everything: the caller gets an [`ExportHandle`] and polls it from its render9 //! everything: the caller gets an [`ExportHandle`] and polls it from its render
@@ -73,10 +73,12 @@ pub enum Format {
73 #[default]73 #[default]
74 Mp4,74 Mp4,
75 /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound75 /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound
76- /// this project can write: there is no AAC or Opus encoder here, and an AAC76+ /// this project can *write*: there is no AAC or Opus encoder here, and the
77- /// track copied in would be one *this engine's own reader* leaves silent77+ /// copy path walks an mp4 sample table, which a Matroska file has none of.
78- /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV178+ /// (Reading one's AAC is a different question and the answer is yes --
79- /// export is a WAV or FLAC beside it, which a front-end says up front.79+ /// `audio::Track::open` does it through symphonia's mkv reader.) The sound
80+ /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up
81+ /// front.
80 Av1,82 Av1,
81 /// The audio lane alone, 16-bit PCM.83 /// The audio lane alone, 16-bit PCM.
82 Wav,84 Wav,
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+}
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+}