forge
Explore
Log in

Don't you dare go Hollow

lane-stackbox: box the by-value fields in ec-opus, ec-ac3 and ec-vp9, and gate each crate on a measured bound

Browse files at this commit

958901bdf3effbf4d3a35ec6cc10aec8f338736eAhmet Kaan GümüşParent: cd17c30
Same class as ec-av1's stack sweep (d202b8b4): a large struct returned BY VALUE from a public
constructor is a stack cost the CALLER pays. The inventory from that lane named these; this lane re-measured
each one, boxed the dominant fields, proved no output changed, and added a per-crate gate.

  ec-opus::Encoder    87,024 -> 4,072  (21.4x)   silk_nb/mb/wb, silk_stereo_nb/mb/wb, silk_buf
  ec-opus::Decoder     7,576 -> 1,280  (5.9x)    silk (it was already at 92.5% of budget)
  ec-ac3::Ac3Decoder  20,024 -> 3,160  (6.3x)    Core::exps/bap/coeffs/delay
  ec-vp9::Decoder     10,944 ->   768  (14.3x)   frame_ctxs: Box<[FrameContext; 4]>, ctx: Box<FrameContext>

API COMPATIBILITY: no public field type changed in any of the three crates -- ec-opus::Encoder/Decoder
and ec-vp9::Decoder have private fields, ec-ac3::decode::Core is pub(crate) and Core itself is
crate-private, and every public method signature (Encoder::new, Decoder::new, Ac3Decoder::new,
Ac3Decoder::with_options, vp9::Decoder::new) is untouched. The only observable change is a few extra
heap allocations AT CONSTRUCTION, not on the per-frame path.

NO OUTPUT CHANGE, per crate, before vs after: ec-opus lib 36/0 -> 42/0 (the +6 are the new gates) and
conformance 28/0/16 -> 28/0/16 unchanged (its closed-loop range-state-exact gate against the
RFC-vector-verified decoder); ec-ac3 lib 36/0 -> 43/0 and both matrices 8/0 and 6/0 unchanged; ec-vp9
lib 10/0 -> 16/0 and ALL eight bit-exactness integration families unchanged (keyframe 3, inter_pixels 3,
hbd 1, subsampling 3, odd_dimensions 2, scaledref 3, intraonly 1). Main re-ran the three crates' lib
suites on the branch: 42/0, 16/0, 43/0.

DELIBERATELY LEFT INLINE: ec-opus::Encoder::analysis (2,168) + celt (1,592) -- together already under
budget, so a Box per field buys no bound and costs a per-frame indirection on a hot path. ec-vp9::Picture's
public fields are 96 B of Vec handles, not a stack cost. A measurement, not a shrug.

Gate modules: crates/{ec-opus,ec-ac3,ec-vp9}/src/stack_budget.rs, same shape as ec-av1's (inventory
printer, bound asserted by name, a real small-thread capability arm, non-vacuity control).

PRE-EXISTING REDS CARRIED, not caused here: ec-ac3
encode_matrix::real_fixtures_round_trip_through_our_decoder_and_the_oracle and ec-vp9
keyframe_exact::lossless_64_matches_ffmpeg both fail NotFound on a missing fixture (the same
fixture-root shape the fixture-library verifier complains about); and ec-vp9 generates 5 warnings
(unused read_partition, TM_PRED, partition_probs, x_mis, y_mis) which are present on main too.
crates/ec-ac3/src/decode.rsmodified+15 -10
@@ -43,9 +43,14 @@ pub(crate) struct Core {
4343 pub(crate) nfchans: usize,
4444 pub(crate) lfeon: bool,
4545 /// Decoded exponents per channel, valid up to that channel's `endmant`.
46- pub(crate) exps: [[u8; COEFFS]; CHANNELS],
46+ ///
47+ /// Boxed, with `bap`, `coeffs` and `delay`, because the four are 16896 of
48+ /// `Core`'s 19728 bytes and `Core` sits inline in the `Ac3Decoder` that
49+ /// `Ac3Decoder::new` hands a caller BY VALUE. Indexing and `&mut self.f[ch]`
50+ /// read through the box unchanged. `Stack`: crate::stack_budget.
51+ pub(crate) exps: Box<[[u8; COEFFS]; CHANNELS]>,
4752 /// Bit allocation pointers per channel.
48- pub(crate) bap: [[u8; COEFFS]; CHANNELS],
53+ pub(crate) bap: Box<[[u8; COEFFS]; CHANNELS]>,
4954 /// Exponent strategy of the current block per channel.
5055 pub(crate) expstr: [Strategy; CHANNELS],
5156 pub(crate) endmant: [usize; CHANNELS],
@@ -83,8 +88,8 @@ pub(crate) struct Core {
8388 /// Dynamic range gain for program 1 and, in 1+1 mode, program 2.
8489 pub(crate) dynrng: [f32; 2],
8590 // Output.
86- pub(crate) coeffs: [[f32; COEFFS]; CHANNELS],
87- pub(crate) delay: [[f32; COEFFS]; MAX_FBW + 1],
91+ pub(crate) coeffs: Box<[[f32; COEFFS]; CHANNELS]>,
92+ pub(crate) delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>,
8893 pub(crate) imdct: Imdct,
8994 pub(crate) dither: Dither,
9095 /// Fraction of the `dynrng` compression to apply (§7.7.1).
@@ -135,8 +140,8 @@ impl Core {
135140 acmod: Acmod::Stereo,
136141 nfchans: 2,
137142 lfeon: false,
138- exps: [[0; COEFFS]; CHANNELS],
139- bap: [[0; COEFFS]; CHANNELS],
143+ exps: Box::new([[0; COEFFS]; CHANNELS]),
144+ bap: Box::new([[0; COEFFS]; CHANNELS]),
140145 expstr: [Strategy::Reuse; CHANNELS],
141146 endmant: [0; CHANNELS],
142147 strtmant: [0; CHANNELS],
@@ -163,8 +168,8 @@ impl Core {
163168 blksw: [false; MAX_FBW],
164169 dithflag: [true; MAX_FBW],
165170 dynrng: [1.0; 2],
166- coeffs: [[0.0; COEFFS]; CHANNELS],
167- delay: [[0.0; COEFFS]; MAX_FBW + 1],
171+ coeffs: Box::new([[0.0; COEFFS]; CHANNELS]),
172+ delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1]),
168173 imdct: Imdct::new(),
169174 dither: Dither::default(),
170175 drc_scale: 1.0,
@@ -194,12 +199,12 @@ impl Core {
194199
195200 /// Drop everything a seek invalidates.
196201 pub(crate) fn reset(&mut self) {
197- for d in &mut self.delay {
202+ for d in self.delay.iter_mut() {
198203 d.fill(0.0);
199204 }
200205 self.cplinu = false;
201206 self.dynrng = [1.0; 2];
202- self.exps = [[0; COEFFS]; CHANNELS];
207+ self.exps = Box::new([[0; COEFFS]; CHANNELS]);
203208 }
204209
205210 /// Adopt a frame header: channel configuration for the blocks that follow.
crates/ec-ac3/src/lib.rsmodified+2 -1
@@ -62,6 +62,7 @@ pub mod bsi;
6262 pub mod eac3;
6363 pub mod exps;
6464 pub mod mantissa;
65+mod stack_budget;
6566 pub mod syncinfo;
6667 pub mod tables;
6768 pub mod transform;
@@ -72,8 +73,8 @@ pub mod encode;
7273
7374 pub use decode::Syntax;
7475 pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
75-pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig};
7676 pub use ec_core::Error;
77+pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig};
7778
7879 /// Samples per channel one audio block produces.
7980 pub use transform::BLOCK_SAMPLES;
crates/ec-ac3/src/stack_budget.rsadded+981 -0
@@ -0,0 +1,981 @@
1+#![cfg(test)]
2+//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3+//!
4+//! # The class
5+//!
6+//! A large struct returned BY VALUE from a public constructor is a stack cost,
7+//! not a heap cost, and the cost is paid by the CALLER. The constructors here
8+//! nest -- `Ac3Decoder::new` -> `Ac3Decoder::with_options` -> `Core::new` for
9+//! the decoder -- and in an unoptimized build each level materialises its whole
10+//! return slot before the inner call returns. So one value's `size_of` is the
11+//! MULTIPLIER, and the chain length is the other factor.
12+//!
13+//! That is not hypothetical. `Ac3Decoder` was **20,024** bytes by value -- its
14+//! inline `decode::Core` carried four per-channel coefficient planes
15+//! (`exps`, `bap`, `coeffs`, `delay`) that are **16,896** of `Core`'s 19,728
16+//! bytes -- and every `Ac3Decoder::new()` / `Ac3Decoder::with_options()` call
17+//! made the caller pay all of it on its own stack. `.cargo/config.toml`
18+//! carries `RUST_MIN_STACK = 67108864`, which HIDES the class from this
19+//! workspace's own runs -- a band-aid a library consumer does not get. Boxing
20+//! those four fields took `Core` to **2,864** and `Ac3Decoder` to **3,160**;
21+//! [`the_crate_private_core_stays_behind_a_box`] is the pin that keeps them
22+//! there.
23+//!
24+//! # Why this module exists when that boxing already exists
25+//!
26+//! The boxing fixed ONE type. The class was not swept: nothing stopped the
27+//! next 18 KB inline plane from landing in `Core`, and nothing said which types
28+//! had been checked. This module is the sweep:
29+//!
30+//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
31+//! that a public `fn` can return by value, with a measured `size_of` floor
32+//! recorded as of this commit.
33+//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
34+//! the table cannot rot into a list of stale small numbers.
35+//! 2. [`STACK_BUDGET`] is the bound, and
36+//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
37+//! every row, so a regression reds naming the type that caused it.
38+//! 3. [`the_crate_private_core_stays_behind_a_box`] pins the four `Box` field
39+//! spellings, with a negative control, so the fix is not silently reverted.
40+//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
41+//! capability arm: it really constructs the heavy types on a deliberately
42+//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
43+//! costing margin.
44+//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
45+//! teeth against NEW types: a source scan re-derives the set of by-value
46+//! public returns from the crate source, so a lane that adds a 40 KB struct
47+//! to a `pub fn` return reds here until it is measured and listed.
48+//! [`the_inventory_scan_is_not_vacuous`] is its control, and
49+//! [`every_by_value_module_is_scanned`] keeps the scan's file list derived
50+//! from `lib.rs` rather than curated.
51+//!
52+//! # The bound, and why this number
53+//!
54+//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by
55+//! measurement, and both sides are asserted in
56+//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently.
57+//!
58+//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a
59+//! caller can be made to owe*: the size of one by-value return, multiplied by
60+//! how many constructor levels hold a copy of it at once. Three inputs:
61+//!
62+//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
63+//! Measured, not assumed, by
64+//! [`test_threads_get_the_stack_they_are_given`] reading
65+//! `/proc/self/task/<tid>/maps`. That is libtest's default test thread and
66+//! also what `std::thread::Builder::new()` gives a caller who does not ask
67+//! for a size. A library consumer gets no `.cargo/config.toml`.
68+//! 2. **The deepest PUBLIC by-value chain is 2** ([`DEEPEST_PUBLIC_CHAIN`]):
69+//! `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options`
70+//! (decoder.rs:122), which calls `Core::new()` (decode.rs:136) as a third,
71+//! crate-private level carrying a 2,864-byte `Core`. The encoder's
72+//! `Ac3Encoder::new` is a single level -- it builds the struct inline in
73+//! its `Ok(..)` and does not nest -- and `Ac3Decoder::decode_frame`'s
74+//! `Result<AudioFrame>` is a single level too. The test asserts
75+//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return
76+//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest
77+//! for the decode, which is the thing that actually needs it.
78+//! 3. **The budget applies only to types a `pub fn` returns.** The
79+//! crate-private 2,864-byte `Core` is measured and listed but is NOT
80+//! bounded, because no caller can reach it by value -- every field that
81+//! holds one of its 16,896-byte planes is a `Box`, which
82+//! [`the_crate_private_core_stays_behind_a_box`] pins by source. Bounding
83+//! it would calibrate the number to something unreachable.
84+//!
85+//! **Where the number sits.** At 8 KiB with the worst public return at 3,160
86+//! bytes ([`Ac3Decoder`]), the worst a caller owes is `2 x 3160 = 6,320` bytes
87+//! -- **0.30%** of a 2 MiB thread -- and the budget itself is 2.59x above the
88+//! incumbent. `Ac3Decoder` is also the row closest to the budget, at **38.6%**
89+//! of it: **5,032 bytes of margin**, the least of any row here.
90+//! [`Ac3Encoder`] is second, at 34.0% and 5,408 bytes of margin. Both
91+//! directions have room, which is the point: a bound the largest type sits
92+//! just under is a bound the next lane will quietly raise.
93+//!
94+//! **What it catches.** A pre-fix `Ac3Decoder` (20,024 B) is **2.44x over**
95+//! budget. The pre-fix `Core` (19,728 B) behind it is **2.41x over** the same
96+//! number -- that is the ratio the layout fix removed, not one this gate
97+//! enforces, because no `pub fn` returns `Core`; the pin on its four `Box`
98+//! fields is what keeps it there. Both the historical defect and the
99+//! near-miss red by a factor, not by a hair.
100+//!
101+//! **What it does not claim.** `size_of` is layout, not stack depth, and the
102+//! gap between the two is the nesting multiplier plus every frame a call owns
103+//! for its own work. `Ac3Encoder::new` is the clearest case: its 2,784-byte
104+//! return is nowhere near the budget, yet building it needs ~80 KiB of thread
105+//! in a debug build, because it materialises a `[0.0f32; 512]` window, an
106+//! `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep. So this module
107+//! does not trust the arithmetic:
108+//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs both
109+//! heavy types for real on a real thread, and its measured threshold is the
110+//! number that settles it.
111+
112+use crate::decoder::{Ac3Decoder, Options};
113+use crate::encode::Ac3Encoder;
114+
115+/// The per-type ceiling for a type a CALLER can be made to hold by value, in
116+/// bytes. See the module docs for the derivation; it is two-sided, and both
117+/// sides are measured.
118+pub(crate) const STACK_BUDGET: usize = 8192;
119+
120+/// The deepest PUBLIC by-value constructor chain in this crate, counted from
121+/// the source:
122+///
123+/// * `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options`
124+/// (decoder.rs:122): TWO public levels, both returning a 3,160-byte
125+/// `Ac3Decoder` by value. `with_options` calls `Core::new()`
126+/// (decode.rs:136), a third level, but that one is `pub(crate)` and carries
127+/// a 2,864-byte `Core`, so it is not a public return.
128+/// * `Ac3Encoder::new` (encode.rs:254): ONE level. It builds the struct
129+/// inline in its `Ok(Ac3Encoder { .. })` (encode.rs:306) and never calls
130+/// another constructor that returns it by value.
131+/// * `Ac3Decoder::decode_frame` (decoder.rs:156) -> `Result<AudioFrame>`:
132+/// ONE level, 96 bytes. It does not nest.
133+///
134+/// The budget is checked against two, the worst of the three.
135+#[cfg(test)]
136+const DEEPEST_PUBLIC_CHAIN: usize = 2;
137+
138+/// Every public type in this crate a public `fn` can return BY VALUE, with the
139+/// `size_of` measured at the commit that wrote this table. `None` means "not
140+/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
141+///
142+/// The third column names the return path, so a reader can see why a type is
143+/// here rather than a coincidence of the type system.
144+pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
145+ // -- decoder.rs: the headline row -------------------------------------
146+ (
147+ "Ac3Decoder",
148+ Some(3160),
149+ true,
150+ "Ac3Decoder::new / with_options -> Ac3Decoder, nesting two deep. Was \
151+ 20024 bytes with decode::Core's four coefficient planes inline, i.e. \
152+ 2.44x over the 8192-byte budget",
153+ ),
154+ // -- encode.rs: the second-closest row to the budget -------------------
155+ (
156+ "Ac3Encoder",
157+ Some(2784),
158+ true,
159+ "Ac3Encoder::new -> Result<Ac3Encoder>, one level, no nesting. \
160+ 34.0% of the budget, 5408 bytes of margin; Ac3Decoder above is the \
161+ closest row at 38.6%",
162+ ),
163+ (
164+ "EncoderConfig",
165+ Some(12),
166+ true,
167+ "consumed by value by Ac3Encoder::new, which copies it into the \
168+ encoder it returns",
169+ ),
170+ (
171+ "EncodeStats",
172+ Some(72),
173+ true,
174+ "Ac3Encoder::stats -> EncodeStats, by value out of the encoder's field",
175+ ),
176+ // -- decoder.rs: the header/option surface ---------------------------
177+ (
178+ "Options",
179+ Some(8),
180+ true,
181+ "Ac3Decoder::with_options(Options) takes it by value and keeps it",
182+ ),
183+ (
184+ "FrameInfo",
185+ Some(48),
186+ true,
187+ "built by value in Ac3Decoder's private info_from; handed back as \
188+ Option<&FrameInfo>, a BORROW, so the row is about the move the \
189+ decoder makes internally",
190+ ),
191+ (
192+ "Downmix",
193+ Some(1),
194+ true,
195+ "Options::downmix, a field of the by-value Options above",
196+ ),
197+ (
198+ "AudioFrame",
199+ Some(96),
200+ true,
201+ "Ac3Decoder::decode_frame -> Result<AudioFrame>, one level, no \
202+ nesting. From ec_core, not this crate, but it is a public return of \
203+ this crate and the sweep finds it by name",
204+ ),
205+ // -- decode.rs -------------------------------------------------------
206+ (
207+ "Syntax",
208+ Some(1),
209+ true,
210+ "re-exported from decode; a field of FrameInfo and of Ac3Decoder::Core",
211+ ),
212+ // -- the header parsers ----------------------------------------------
213+ (
214+ "Bsi",
215+ Some(56),
216+ true,
217+ "bsi::parse / bsi::parse_from -> Result<Bsi>, one level each",
218+ ),
219+ ("Acmod", Some(1), true, "bsi::Acmod::from_code -> Acmod"),
220+ (
221+ "SyncInfo",
222+ Some(24),
223+ true,
224+ "syncinfo::parse / syncinfo::parse_from -> Result<SyncInfo>",
225+ ),
226+ (
227+ "Eac3Bsi",
228+ Some(96),
229+ true,
230+ "eac3::bsi::parse / eac3::bsi::parse_from -> Result<Eac3Bsi>",
231+ ),
232+ (
233+ "StreamType",
234+ Some(1),
235+ true,
236+ "a field of the by-value Eac3Bsi above; eac3::StreamType::Dependent \
237+ is the first-substream refusal",
238+ ),
239+ // -- transform.rs / mantissa.rs / exps.rs ----------------------------
240+ (
241+ "Imdct",
242+ Some(472),
243+ true,
244+ "transform::Imdct::new -> Imdct, one level. Held inline in both Core \
245+ and Ac3Encoder, the largest type in the crate that is NOT a public \
246+ return",
247+ ),
248+ (
249+ "Mantissas",
250+ Some(56),
251+ true,
252+ "mantissa::Mantissas::new -> Mantissas, one level",
253+ ),
254+ (
255+ "Strategy",
256+ Some(1),
257+ true,
258+ "exps::Strategy::from_code -> Strategy; a field of Core's inline \
259+ [Strategy; CHANNELS]",
260+ ),
261+ // -- bitalloc.rs -----------------------------------------------------
262+ (
263+ "BitAllocParams",
264+ Some(5),
265+ true,
266+ "bitalloc::BitAllocParams::default, copied into Core's inline copy",
267+ ),
268+ (
269+ "DeltaBa",
270+ Some(32),
271+ true,
272+ "bitalloc::DeltaBa, built by value per block",
273+ ),
274+ (
275+ "Allocation",
276+ Some(56),
277+ true,
278+ "bitalloc::Allocation<'_>, built by value and passed to \
279+ bitalloc::compute by reference; the move copies the struct, not the \
280+ borrowed slices",
281+ ),
282+ (
283+ "Channel",
284+ Some(12),
285+ true,
286+ "bitalloc::Channel, moved out of the per-block channel table",
287+ ),
288+ // -- crate-private: never a public return, and every one of its four
289+ // -- large planes is behind a Box now. The budget does not apply; the
290+ // -- pin that does is `the_crate_private_core_stays_behind_a_box`.
291+ (
292+ "Core",
293+ Some(2864),
294+ false,
295+ "decode::Core::new -> Core, pub(crate), held inline in Ac3Decoder. \
296+ Was 19728 bytes with exps/bap/coeffs/delay inline; those four are \
297+ 16896 of them and are boxed now",
298+ ),
299+];
300+
301+/// The live `size_of` for every inventoried type, keyed BY NAME.
302+///
303+/// Keyed rather than positional on purpose: `Bsi`, `Mantissas` and
304+/// `Allocation` are all 56 bytes, and `Eac3Bsi` and `AudioFrame` are both 96,
305+/// so a row inserted into [`BY_VALUE_TYPES`] without a matching insert here
306+/// would zip cleanly and assert the wrong type's size against the wrong
307+/// recorded one. A name key makes that mistake loud instead.
308+#[cfg(test)]
309+fn measured_by_name() -> Vec<(&'static str, usize)> {
310+ vec![
311+ ("Ac3Decoder", std::mem::size_of::<Ac3Decoder>()),
312+ ("Ac3Encoder", std::mem::size_of::<Ac3Encoder>()),
313+ (
314+ "EncoderConfig",
315+ std::mem::size_of::<crate::encode::EncoderConfig>(),
316+ ),
317+ (
318+ "EncodeStats",
319+ std::mem::size_of::<crate::encode::EncodeStats>(),
320+ ),
321+ ("Options", std::mem::size_of::<Options>()),
322+ (
323+ "FrameInfo",
324+ std::mem::size_of::<crate::decoder::FrameInfo>(),
325+ ),
326+ ("Downmix", std::mem::size_of::<crate::decoder::Downmix>()),
327+ ("AudioFrame", std::mem::size_of::<ec_core::AudioFrame>()),
328+ ("Syntax", std::mem::size_of::<crate::decode::Syntax>()),
329+ ("Bsi", std::mem::size_of::<crate::bsi::Bsi>()),
330+ ("Acmod", std::mem::size_of::<crate::bsi::Acmod>()),
331+ ("SyncInfo", std::mem::size_of::<crate::syncinfo::SyncInfo>()),
332+ ("Eac3Bsi", std::mem::size_of::<crate::eac3::Eac3Bsi>()),
333+ ("StreamType", std::mem::size_of::<crate::eac3::StreamType>()),
334+ ("Imdct", std::mem::size_of::<crate::transform::Imdct>()),
335+ (
336+ "Mantissas",
337+ std::mem::size_of::<crate::mantissa::Mantissas>(),
338+ ),
339+ ("Strategy", std::mem::size_of::<crate::exps::Strategy>()),
340+ (
341+ "BitAllocParams",
342+ std::mem::size_of::<crate::bitalloc::BitAllocParams>(),
343+ ),
344+ ("DeltaBa", std::mem::size_of::<crate::bitalloc::DeltaBa>()),
345+ (
346+ "Allocation",
347+ std::mem::size_of::<crate::bitalloc::Allocation<'static>>(),
348+ ),
349+ ("Channel", std::mem::size_of::<crate::bitalloc::Channel>()),
350+ ("Core", std::mem::size_of::<crate::decode::Core>()),
351+ ]
352+}
353+
354+/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
355+/// constructs on.
356+///
357+/// 1 MiB: half of what an unconfigured caller gives this crate, and far above
358+/// what the deepest measured chain needs in a debug build. The threshold was
359+/// swept in an unoptimized build and is reproducible with
360+/// `EC_AC3_TIGHT_STACK_BYTES`.
361+const TIGHT_STACK: usize = 1024 * 1024;
362+
363+#[cfg(test)]
364+mod tests {
365+ use super::{
366+ BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
367+ };
368+ use crate::decoder::{Ac3Decoder, Downmix, Options};
369+ use crate::encode::{Ac3Encoder, EncoderConfig};
370+
371+ /// Return types that are not a by-value copy of anything the caller has to
372+ /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
373+ /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
374+ /// which the inventory rows already cover, so it is exempt from the scan
375+ /// and not from the table.
376+ const THIN: &[&str] = &[
377+ "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
378+ "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
379+ "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
380+ ];
381+
382+ /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
383+ /// returns a pointer, a `Vec`, a primitive, or nothing.
384+ ///
385+ /// One function, shared by the sweep and its control, so the control
386+ /// cannot pass while the sweep's copy of the logic rotted.
387+ fn by_value_return_name(line: &str) -> Option<String> {
388+ let trimmed = line.trim_start();
389+ if !trimmed.starts_with("pub fn ") {
390+ return None;
391+ }
392+ let arrow = line.find("->")?;
393+ let rest = &line[arrow + 2..];
394+ let end = rest.find('{').unwrap_or(rest.len());
395+ let ret = rest[..end].trim();
396+ if ret.is_empty() {
397+ return None;
398+ }
399+ // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
400+ // not a shape this crate uses, and flagging one as uninventoried is
401+ // the safe direction to be wrong in.
402+ let inner = {
403+ let t = ret
404+ .strip_prefix("Result<")
405+ .or_else(|| ret.strip_prefix("Option<"))
406+ .unwrap_or(ret);
407+ t.split('>').next().unwrap_or(t)
408+ };
409+ // Drop the error type and any lifetime or generic argument:
410+ // `Result<Bsi, Error>`, `Allocation<'a>` and `AudioFrame` are all the
411+ // bare name for this purpose. Splitting on the comma is load-bearing:
412+ // the first version of this matcher cut only at `>` and so read
413+ // `Result<Bsi, Error>` as the name "Bsi, Error". `ec_av1`'s control
414+ // caught exactly that, which is why the control is not optional.
415+ let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
416+ if name.is_empty() || THIN.contains(&name) {
417+ return None;
418+ }
419+ // A generic parameter, not a concrete type.
420+ if !name.chars().next().is_some_and(char::is_uppercase) {
421+ return None;
422+ }
423+ Some(name.to_string())
424+ }
425+
426+ /// The source files the by-value scan reads. Every module that can expose
427+ /// a `pub fn` returning a named type; a new module added to `lib.rs` needs
428+ /// adding here, and
429+ /// [`every_by_value_module_is_scanned`] is what keeps that honest.
430+ const FILES: &[(&str, &str)] = &[
431+ ("aht.rs", include_str!("aht.rs")),
432+ ("aht_tables.rs", include_str!("aht_tables.rs")),
433+ ("bitalloc.rs", include_str!("bitalloc.rs")),
434+ ("bsi.rs", include_str!("bsi.rs")),
435+ ("decode.rs", include_str!("decode.rs")),
436+ ("decoder.rs", include_str!("decoder.rs")),
437+ ("eac3.rs", include_str!("eac3.rs")),
438+ ("encode.rs", include_str!("encode.rs")),
439+ ("exps.rs", include_str!("exps.rs")),
440+ ("lib.rs", include_str!("lib.rs")),
441+ ("mantissa.rs", include_str!("mantissa.rs")),
442+ ("stack_budget.rs", include_str!("stack_budget.rs")),
443+ ("syncinfo.rs", include_str!("syncinfo.rs")),
444+ ("tables.rs", include_str!("tables.rs")),
445+ ("transform.rs", include_str!("transform.rs")),
446+ ];
447+
448+ /// Every module `lib.rs` declares, so the scan's file list cannot silently
449+ /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
450+ /// that the scan never reads is exactly the hole this class would come
451+ /// back through, so the list is derived, not curated.
452+ #[test]
453+ fn every_by_value_module_is_scanned() {
454+ let lib = include_str!("lib.rs");
455+ let mut declared: Vec<&str> = Vec::new();
456+ for line in lib.lines() {
457+ let t = line.trim();
458+ let rest = t
459+ .strip_prefix("pub mod ")
460+ .or_else(|| t.strip_prefix("mod "))
461+ .unwrap_or("");
462+ if rest.is_empty() {
463+ continue;
464+ }
465+ let name = rest.split([';', ' ']).next().unwrap_or("");
466+ if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
467+ declared.push(name);
468+ }
469+ }
470+ assert!(
471+ declared.len() > 10,
472+ "only {} module declarations parsed out of lib.rs, so the \
473+ derived file list is broken rather than small",
474+ declared.len()
475+ );
476+ let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
477+ let mut missing: Vec<String> = declared
478+ .iter()
479+ .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
480+ .map(|d| (*d).to_string())
481+ .collect();
482+ missing.sort();
483+ assert!(
484+ missing.is_empty(),
485+ "lib.rs declares modules the by-value scan never reads: {:?}. Add \
486+ them to FILES, or the sweep cannot see a new by-value return that \
487+ lands in one of them.",
488+ missing
489+ );
490+ }
491+
492+ /// The inventory, printed as a sorted table, and checked against the
493+ /// types' real sizes.
494+ ///
495+ /// The print is the instrument: one command
496+ /// (`cargo test -p ec-ac3 --lib -- stack_budget -- --nocapture`)
497+ /// reproduces the whole table, biggest first, so "what is the largest
498+ /// by-value type in this crate" has an answer that is a measurement
499+ /// rather than a grep.
500+ ///
501+ /// The check reds on ANY change with both numbers. That is deliberate: a
502+ /// by-value type that grew raises the question of whether it should have
503+ /// been boxed instead, and auto-accepting the new number would answer
504+ /// that question by default.
505+ #[test]
506+ fn the_measured_inventory_is_accurate() {
507+ let live = measured_by_name();
508+ assert_eq!(
509+ BY_VALUE_TYPES.len(),
510+ live.len(),
511+ "the inventory names {} types but {} are measured; every row needs \
512+ a measured size or the sweep is a list of hopes",
513+ BY_VALUE_TYPES.len(),
514+ live.len()
515+ );
516+ let mut rows: Vec<(&str, usize)> = live.clone();
517+ rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
518+ eprintln!(
519+ "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
520+ rows.len(),
521+ STACK_BUDGET / 1024
522+ );
523+ eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE");
524+ for (name, size) in &rows {
525+ eprintln!(
526+ "{size:>8} {:>6.1}% {name}",
527+ *size as f64 * 100.0 / STACK_BUDGET as f64
528+ );
529+ }
530+ for (name, recorded, _public, _path) in BY_VALUE_TYPES {
531+ let recorded = recorded.expect("every inventory row carries a measured size");
532+ let actual = live
533+ .iter()
534+ .find(|(n, _)| n == name)
535+ .map(|(_, size)| *size)
536+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
537+ assert_eq!(
538+ recorded, actual,
539+ "{name} is {actual} bytes, the inventory records {recorded}; \
540+ update the table deliberately -- a by-value type that changed \
541+ is a stack cost every caller of its constructor now pays"
542+ );
543+ }
544+ }
545+
546+ /// The bound, asserted BY NAME. A regression in any inventoried type reds
547+ /// here naming the type, not "some type is too big".
548+ #[test]
549+ fn every_by_value_type_fits_the_stack_budget() {
550+ let live = measured_by_name();
551+ let mut checked = 0usize;
552+ for (name, _, public, path) in BY_VALUE_TYPES {
553+ if !public {
554+ continue;
555+ }
556+ checked += 1;
557+ let size = live
558+ .iter()
559+ .find(|(n, _)| n == name)
560+ .map(|(_, size)| *size)
561+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
562+ assert!(
563+ size <= STACK_BUDGET,
564+ "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
565+ stack budget ({:.2}x). It is returned by value from {path}, so \
566+ every caller pays it on its own stack, and the constructors \
567+ nest -- one value's size is the multiplier, not the cost. \
568+ Box the large field (this crate did exactly that for \
569+ Ac3Decoder's inline decode::Core) or hand back a reference.",
570+ size as f64 / STACK_BUDGET as f64
571+ );
572+ }
573+ assert!(
574+ checked >= 10,
575+ "only {checked} rows were bound-checked; the budget must apply to \
576+ every type a caller can be made to hold by value"
577+ );
578+ // The other half of the derivation, asserted so it cannot rot: the
579+ // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
580+ let worst = live
581+ .iter()
582+ .filter(|(n, _)| {
583+ BY_VALUE_TYPES
584+ .iter()
585+ .any(|(row, _, public, _)| row == n && *public)
586+ })
587+ .map(|(_, size)| *size)
588+ .max()
589+ .expect("at least one public row");
590+ assert!(
591+ DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
592+ "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
593+ public by-value return ({worst} B) is {} B, over an eighth of the \
594+ 2101248-byte stack an unconfigured caller hands this crate; \
595+ re-derive STACK_BUDGET",
596+ DEEPEST_PUBLIC_CHAIN * worst
597+ );
598+ }
599+
600+ /// The crate-private decode state stays BEHIND A BOX.
601+ ///
602+ /// The budget does not apply to `Core` because no `pub fn` returns it, so
603+ /// bounding it would calibrate the number to something no caller can
604+ /// reach. What keeps its 16,896 bytes of coefficient planes off every
605+ /// caller's stack is that the four fields holding them are `Box`es, and
606+ /// THIS is the pin for that -- a source scan over the four declarations
607+ /// plus the four `Box::new`s in `Core::new`.
608+ ///
609+ /// It earned its place during the layout fix: `exps`, `bap` and `delay`
610+ /// are `[[T; COEFFS]; CHANNELS]`-shaped planes at 1,792 / 1,792 / 6,144
611+ /// bytes and `coeffs` is 7,168 -- 16,896 of a 19,728-byte `Core` -- and
612+ /// `Core` sits inline in the `Ac3Decoder` that `Ac3Decoder::new` hands a
613+ /// caller BY VALUE. Unboxing any of the four puts the stack cost straight
614+ /// back.
615+ #[test]
616+ fn the_crate_private_core_stays_behind_a_box() {
617+ const PINS: &[(&str, &str)] = &[
618+ (
619+ "decode.rs::Core::exps",
620+ "exps: Box<[[u8; COEFFS]; CHANNELS]>",
621+ ),
622+ ("decode.rs::Core::bap", "bap: Box<[[u8; COEFFS]; CHANNELS]>"),
623+ (
624+ "decode.rs::Core::coeffs",
625+ "coeffs: Box<[[f32; COEFFS]; CHANNELS]>",
626+ ),
627+ (
628+ "decode.rs::Core::delay",
629+ "delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>",
630+ ),
631+ (
632+ "decode.rs::Core::new::exps",
633+ "exps: Box::new([[0; COEFFS]; CHANNELS])",
634+ ),
635+ (
636+ "decode.rs::Core::new::bap",
637+ "bap: Box::new([[0; COEFFS]; CHANNELS])",
638+ ),
639+ (
640+ "decode.rs::Core::new::coeffs",
641+ "coeffs: Box::new([[0.0; COEFFS]; CHANNELS])",
642+ ),
643+ (
644+ "decode.rs::Core::new::delay",
645+ "delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1])",
646+ ),
647+ ];
648+ const UNBOXED: &[(&str, &str)] = &[
649+ ("decode.rs::Core::exps", "exps: [[u8; COEFFS]; CHANNELS],"),
650+ ("decode.rs::Core::bap", "bap: [[u8; COEFFS]; CHANNELS],"),
651+ (
652+ "decode.rs::Core::coeffs",
653+ "coeffs: [[f32; COEFFS]; CHANNELS],",
654+ ),
655+ (
656+ "decode.rs::Core::delay",
657+ "delay: [[f32; COEFFS]; MAX_FBW + 1],",
658+ ),
659+ ];
660+ let decode = include_str!("decode.rs");
661+ for (where_, spelling) in PINS {
662+ assert!(
663+ decode.contains(spelling),
664+ "{where_} is no longer declared `{spelling}`. An inline \
665+ coefficient plane there puts its 16896 bytes back inside \
666+ decode::Core, which sits inline in the Ac3Decoder that \
667+ Ac3Decoder::new returns BY VALUE -- that is how Ac3Decoder was \
668+ 20024 bytes, 2.44x over the by-value budget.",
669+ );
670+ }
671+ // And the negative control: the unboxed spellings must be ABSENT, or
672+ // the scan above would be matching a doc comment or a dead branch
673+ // rather than the live declaration.
674+ for (where_, unboxed) in UNBOXED {
675+ assert!(
676+ !decode.contains(unboxed),
677+ "{where_} is declared `{unboxed}`, unboxed. The box pin above \
678+ is not matching the live declaration, or the plane is inline \
679+ again and every Ac3Decoder::new caller pays 16896 bytes.",
680+ );
681+ }
682+ }
683+
684+ /// CAPABILITY: really construct the heavy types on a tight stack, so a
685+ /// regression ABORTS THE PROCESS instead of costing invisible margin.
686+ ///
687+ /// Arm 1 is the two-deep `Ac3Decoder` constructor nest -- the crate's
688+ /// largest by-value return, and the type this lane's layout fix took from
689+ /// 20,024 to 3,160 bytes. Arm 2 is `Ac3Encoder::new`, the second-closest
690+ /// row to the budget at 34.0% of it.
691+ ///
692+ /// Both arms assert a REAL property of what came back, not merely that the
693+ /// thread survived: a fresh `Ac3Decoder` has no `frame_info()` before any
694+ /// syncframe, and one built with explicit options hands those exact options
695+ /// back through `options_mut()`. A constructor that quietly dropped its
696+ /// argument would red here rather than pass on a stack measurement alone.
697+ ///
698+ /// Measured stack need, **debug** build, one process per point so a
699+ /// stack-overflow abort cannot truncate the sweep:
700+ ///
701+ /// | `EC_AC3_TIGHT_STACK_BYTES` | result |
702+ /// |---|---|
703+ /// | 1048576 (1 MiB) | **ok** |
704+ /// | 524288 | **ok** |
705+ /// | 262144 | **ok** |
706+ /// | 131072 | **ok** |
707+ /// | 98304 | **ok** |
708+ /// | 86016 | **ok** |
709+ /// | 81920 | **ok** |
710+ /// | 77824 | overflow |
711+ /// | 65536 | overflow |
712+ /// | 32768 | overflow |
713+ /// | 24576 | overflow |
714+ ///
715+ /// The deepest measured need is therefore between 77,824 and 81,920
716+ /// bytes, and the gate sits at 1 MiB -- **12.8x** that, and half of what an
717+ /// unconfigured caller hands this crate. The ~80 KiB is dominated by
718+ /// `Ac3Encoder::new`'s own working frames (a 512-float window, an
719+ /// `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep), not by the
720+ /// by-value return slots this module bounds; that is exactly the residual
721+ /// `size_of` cannot predict, and why the arm constructs rather than
722+ /// computing.
723+ ///
724+ /// `EC_AC3_TIGHT_STACK_BYTES` overrides the size, which is how the
725+ /// threshold is swept.
726+ #[test]
727+ fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
728+ let stack: usize = std::env::var("EC_AC3_TIGHT_STACK_BYTES")
729+ .ok()
730+ .and_then(|v| v.parse().ok())
731+ .unwrap_or(TIGHT_STACK);
732+ let config = EncoderConfig {
733+ sample_rate: 48_000,
734+ channels: 2,
735+ bitrate_kbps: 192,
736+ };
737+ let handle = std::thread::Builder::new()
738+ .stack_size(stack)
739+ .spawn(move || {
740+ // Arm 1: the two-deep `Ac3Decoder` constructor nest, the
741+ // crate's largest by-value return.
742+ let mut plain = Ac3Decoder::new();
743+ let fresh_has_no_frame_info = plain.frame_info().is_none();
744+ let plain_options = *plain.options_mut();
745+ // A decoder built with explicit options must keep exactly
746+ // those options, including a non-default downmix.
747+ let mut configured = Ac3Decoder::with_options(Options {
748+ drc_scale: 0.25,
749+ downmix: Downmix::Stereo,
750+ dither: false,
751+ });
752+ let kept = *configured.options_mut();
753+ drop(plain);
754+ drop(configured);
755+ // Arm 2: `Ac3Encoder::new`, the second-closest row to the budget.
756+ let encoder = Ac3Encoder::new(config).expect("Ac3Encoder::new");
757+ let delay = encoder.encoder_delay();
758+ let stats = encoder.stats();
759+ (fresh_has_no_frame_info, plain_options, kept, delay, stats)
760+ })
761+ .expect("spawn tight-stack thread");
762+ let (fresh_has_no_frame_info, plain_options, kept, delay, stats) =
763+ handle.join().unwrap_or_else(|_| {
764+ panic!(
765+ "a by-value constructor overflowed a {stack}-byte stack; the \
766+ old 20024-byte Ac3Decoder is what that costs"
767+ )
768+ });
769+ assert!(
770+ fresh_has_no_frame_info,
771+ "a freshly constructed Ac3Decoder already reported a frame_info(); \
772+ decode_frame is the only thing that may set one"
773+ );
774+ assert_eq!(
775+ plain_options,
776+ Options::default(),
777+ "Ac3Decoder::new did not give back the default Options"
778+ );
779+ assert_eq!(
780+ kept,
781+ Options {
782+ drc_scale: 0.25,
783+ downmix: Downmix::Stereo,
784+ dither: false,
785+ },
786+ "Ac3Decoder::with_options did not keep the options it was handed"
787+ );
788+ assert!(
789+ delay > 0,
790+ "Ac3Encoder::encoder_delay reported no priming samples"
791+ );
792+ assert_eq!(
793+ stats,
794+ crate::encode::EncodeStats::default(),
795+ "a fresh Ac3Encoder reported non-zero coding stats"
796+ );
797+ eprintln!(
798+ "TIGHTSTACK {stack} bytes: Ac3Decoder={} Ac3Encoder={} bytes, both \
799+ constructors returned and both options paths round-tripped",
800+ std::mem::size_of::<Ac3Decoder>(),
801+ std::mem::size_of::<Ac3Encoder>(),
802+ );
803+ }
804+
805+ /// The sweep's teeth against a NEW by-value return: re-derive the set from
806+ /// the crate source and require every name to be inventoried.
807+ ///
808+ /// Without this the inventory is a list of what someone remembered to
809+ /// measure, and a lane that adds `pub fn make() -> HugeThing` where
810+ /// `HugeThing` is 200 KB of inline tables passes every other test here.
811+ #[test]
812+ fn every_by_value_public_return_is_in_the_inventory() {
813+ let mut found: Vec<(String, String)> = Vec::new();
814+ for (file, src) in FILES {
815+ for (n, line) in src.lines().enumerate() {
816+ if let Some(name) = by_value_return_name(line) {
817+ found.push((name, format!("{file}:{}", n + 1)));
818+ }
819+ }
820+ }
821+ found.sort();
822+ found.dedup();
823+ assert!(
824+ found.len() > 5,
825+ "the by-value return scan found {} names across {} files, which is \
826+ too few to be a real sweep -- the matcher, not the crate, is broken",
827+ found.len(),
828+ FILES.len()
829+ );
830+ eprintln!("BY-VALUE PUBLIC RETURNS FOUND: {found:?}");
831+
832+ let mut missing = Vec::new();
833+ for (name, site) in &found {
834+ if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
835+ missing.push(format!("{name} ({site})"));
836+ }
837+ }
838+ assert!(
839+ missing.is_empty(),
840+ "these types are returned BY VALUE from a public fn and are not in \
841+ the inventory: {}. Either they are thin enough not to be a stack \
842+ cost -- say so by adding a row with its measured size -- or they \
843+ are the next instance of the class this module exists for.",
844+ missing.join(", ")
845+ );
846+ }
847+
848+ /// The control for the scan above, on synthetic text rather than by
849+ /// trusting the live tree to happen to contain a case.
850+ ///
851+ /// If the matcher silently stopped recognising a shape, the sweep would
852+ /// pass everything and this would still be asserting nothing. So: every
853+ /// by-value spelling the crate uses must yield its type name, and every
854+ /// pointer/Vec/primitive/`Self` spelling must yield nothing.
855+ #[test]
856+ fn the_inventory_scan_is_not_vacuous() {
857+ for synthetic in [
858+ "pub fn zz_a() -> ZzNotInventoried { todo!() }",
859+ "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
860+ "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
861+ "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
862+ "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
863+ ] {
864+ let name = by_value_return_name(synthetic)
865+ .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
866+ assert_eq!(
867+ name, "ZzNotInventoried",
868+ "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
869+ cannot see a new by-value return and its green is vacuous"
870+ );
871+ assert!(
872+ !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
873+ "the synthetic control name is in the inventory, so the control \
874+ proves nothing"
875+ );
876+ }
877+ for thin in [
878+ "pub fn zz_t() -> Box<Decoder> { todo!() }",
879+ "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
880+ "pub fn zz_v() -> Option<&Path> { todo!() }",
881+ "pub fn zz_w() -> usize { todo!() }",
882+ "pub fn zz_x() -> Self { todo!() }",
883+ "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
884+ "pub fn zz_z() { todo!() }",
885+ "fn zz_private() -> ZzNotInventoried { todo!() }",
886+ ] {
887+ assert_eq!(
888+ by_value_return_name(thin),
889+ None,
890+ "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
891+ above already cover, or not a `pub fn` -- the matcher must not \
892+ read it as an uninventoried by-value return"
893+ );
894+ }
895+ }
896+
897+ /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
898+ ///
899+ /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
900+ /// adjacent VMAs that share protections, and a merged region is
901+ /// indistinguishable from a single one in the maps file. A lower bound is
902+ /// what the budget's reasoning needs: the claim is "no caller gets less
903+ /// than 2 MiB", and `size >= 2 MiB` is exactly that, whether the region is
904+ /// one mapping or three.
905+ fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize)> {
906+ let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
907+ for line in maps.lines() {
908+ let (range, _) = line.split_once(' ')?;
909+ let (lo, hi) = range.split_once('-')?;
910+ let (lo, hi) = (
911+ usize::from_str_radix(lo, 16).ok()?,
912+ usize::from_str_radix(hi, 16).ok()?,
913+ );
914+ if addr >= lo && addr < hi {
915+ return Some((lo, hi));
916+ }
917+ }
918+ None
919+ }
920+
921+ /// What a thread's stack ACTUALLY is, read from
922+ /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
923+ ///
924+ /// The number the budget's reasoning rests on, measured two ways:
925+ ///
926+ /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
927+ /// the control that says the parse finds stacks at all, and the shape
928+ /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
929+ /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
930+ /// `std::thread::spawn` gets, and what libtest gives a test thread when
931+ /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
932+ ///
933+ /// Both are floors, because [`stack_region`] can only report a lower bound.
934+ /// That is the right direction: the budget's claim is that no caller gets
935+ /// LESS than 2 MiB, and a floor is what proves it.
936+ #[test]
937+ fn test_threads_get_the_stack_they_are_given() {
938+ const EXPLICIT: usize = 1024 * 1024;
939+ let handle = std::thread::Builder::new()
940+ .stack_size(EXPLICIT)
941+ .spawn(|| {
942+ let tid = std::process::id();
943+ let marker = 0u8;
944+ let here = &marker as *const u8 as usize;
945+ let (lo, hi) =
946+ stack_region(tid, here).expect("this thread's own stack is in its maps");
947+ (tid, lo, hi)
948+ })
949+ .expect("spawn");
950+ let (_tid, lo, hi) = handle.join().expect("the probe thread returned");
951+ let size = hi - lo;
952+ assert!(
953+ size >= EXPLICIT,
954+ "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
955+ stack mapping; the runtime gave it less than it was promised, so \
956+ the maps parse is finding the wrong region"
957+ );
958+ assert!(
959+ size <= 512 * 1024 * 1024,
960+ "the mapping holding an explicitly-1-MiB thread's frame is {size} \
961+ bytes, which is not a stack -- the maps parse found the wrong region"
962+ );
963+
964+ let tid = std::process::id();
965+ let marker = 0u8;
966+ let here = &marker as *const u8 as usize;
967+ let (lo, hi) = stack_region(tid, here).expect("this test thread's stack is in its maps");
968+ let size = hi - lo;
969+ assert!(
970+ size >= 2 * 1024 * 1024,
971+ "a default test thread's stack measured {size} bytes, under the \
972+ 2 MiB floor the by-value budget is derived from; the smallest \
973+ stack a caller can hand this crate just got smaller and the bound \
974+ needs re-deriving"
975+ );
976+ eprintln!(
977+ "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
978+ (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
979+ );
980+ }
981+}
crates/ec-opus/src/encoder.rsmodified+84 -34
@@ -99,15 +99,28 @@ pub struct Encoder {
9999 mode: Option<Mode>,
100100 /// Lazily created on first use so the mode can flip between packets
101101 /// without paying for the unused layer's state.
102- silk_nb: Option<SilkEncoder>,
103- silk_mb: Option<SilkEncoder>,
104- silk_wb: Option<SilkEncoder>,
105- silk_stereo_nb: Option<SilkStereoEncoder>,
106- silk_stereo_mb: Option<SilkStereoEncoder>,
107- silk_stereo_wb: Option<SilkStereoEncoder>,
102+ ///
103+ /// The six slots are behind `Box` because of what they cost the CALLER.
104+ /// A `SilkStereoEncoder` is 19744 bytes and a `SilkEncoder` 6648, so six
105+ /// inline slots put 79176 bytes on the stack of every `Encoder` that a
106+ /// `pub fn` hands back by value -- 10.6x the crate's by-value stack
107+ /// budget, on a type `Encoder::new` returns and a caller constructs
108+ /// inside its own frame. Only one of the six is ever alive at a time
109+ /// (the mode decides), so the heap pays for one and the stack pays for
110+ /// six pointers. `Stack`: crate::stack_budget.
111+ silk_nb: Option<Box<SilkEncoder>>,
112+ silk_mb: Option<Box<SilkEncoder>>,
113+ silk_wb: Option<Box<SilkEncoder>>,
114+ silk_stereo_nb: Option<Box<SilkStereoEncoder>>,
115+ silk_stereo_mb: Option<Box<SilkStereoEncoder>>,
116+ silk_stereo_wb: Option<Box<SilkStereoEncoder>>,
108117 /// Scratch space for the SILK packet payload, sized once so the steady-state
109118 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
110- silk_buf: [u8; MAX_SILK_PACKET_BYTES],
119+ ///
120+ /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is
121+ /// 4088 bytes, and an inline array that size is a third of the whole
122+ /// budget on the `Encoder` that a caller holds by value.
123+ silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>,
111124 /// Hybrid: the last `Encoder::hybrid_silk_delay_48k` samples of SILK-layer input.
112125 silk_delay: Vec<f32>,
113126 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
@@ -188,7 +201,7 @@ impl Encoder {
188201 silk_stereo_nb: None,
189202 silk_stereo_mb: None,
190203 silk_stereo_wb: None,
191- silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
204+ silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]),
192205 silk_delay: Vec::new(),
193206 silk_stuff: Vec::new(),
194207 align_input: false,
@@ -263,7 +276,12 @@ impl Encoder {
263276 /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus
264277 /// libopus's `delay_compensation` when the alignment is on.
265278 fn celt_look_ahead_48k(&self) -> usize {
266- CELT_OVERLAP_48K + if self.align_input { CELT_DELAY_COMP_48K } else { 0 }
279+ CELT_OVERLAP_48K
280+ + if self.align_input {
281+ CELT_DELAY_COMP_48K
282+ } else {
283+ 0
284+ }
267285 }
268286
269287 /// How far the hybrid path delays the SILK layer's input so its output
@@ -412,7 +430,9 @@ impl Encoder {
412430 if !self.auto_silk(equiv, ve) {
413431 return None;
414432 }
415- let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
433+ let bw = self
434+ .bandwidth
435+ .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
416436 // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms):
417437 // cap at Wide so a high equiv rate does not fall through to
418438 // an impossible CELT 40/60 ms packet.
@@ -458,7 +478,9 @@ impl Encoder {
458478 if self.mode.is_none() && !self.auto_silk(equiv, ve) {
459479 return None;
460480 }
461- let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
481+ let bw = self
482+ .bandwidth
483+ .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
462484 match bw {
463485 Bandwidth::SuperWide | Bandwidth::Full => Some(bw),
464486 // A forced Hybrid with a narrow/medium/wide bandwidth still codes
@@ -564,13 +586,13 @@ impl Encoder {
564586 let enc = match fs_khz {
565587 8 => self
566588 .silk_stereo_nb
567- .get_or_insert_with(|| SilkStereoEncoder::new(false)),
589+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(false))),
568590 12 => self
569591 .silk_stereo_mb
570- .get_or_insert_with(SilkStereoEncoder::new_mediumband),
592+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new_mediumband())),
571593 _ => self
572594 .silk_stereo_wb
573- .get_or_insert_with(|| SilkStereoEncoder::new(true)),
595+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))),
574596 };
575597 enc.set_bitrate(self.bitrate);
576598 for i in 0..frame_count {
@@ -589,7 +611,7 @@ impl Encoder {
589611 self.silk_buf[pos] = 0x80 | frame_count as u8;
590612 pos += 1;
591613 for &len in &lens[..frame_count - 1] {
592- Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?;
614+ Self::write_frame_len(&mut self.silk_buf[..], &mut pos, len - 1)?;
593615 }
594616 for i in 0..frame_count {
595617 let len = lens[i] - 1;
@@ -636,31 +658,38 @@ impl Encoder {
636658 let enc = match fs_khz {
637659 8 => self
638660 .silk_stereo_nb
639- .get_or_insert_with(|| SilkStereoEncoder::new(false)),
661+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(false))),
640662 12 => self
641663 .silk_stereo_mb
642- .get_or_insert_with(SilkStereoEncoder::new_mediumband),
664+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new_mediumband())),
643665 _ => self
644666 .silk_stereo_wb
645- .get_or_insert_with(|| SilkStereoEncoder::new(true)),
667+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))),
646668 };
647669 enc.set_bitrate(self.bitrate);
648670 let n =
649- enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
671+ enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?;
650672 self.final_range = enc.final_range();
651673 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
652674 }
653675 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
654676 let enc = match fs_khz {
655- 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),
656- 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband),
657- _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)),
677+ 8 => self
678+ .silk_nb
679+ .get_or_insert_with(|| Box::new(SilkEncoder::new(false))),
680+ 12 => self
681+ .silk_mb
682+ .get_or_insert_with(|| Box::new(SilkEncoder::new_mediumband())),
683+ _ => self
684+ .silk_wb
685+ .get_or_insert_with(|| Box::new(SilkEncoder::new(true))),
658686 };
659687 // Keep SILK's own reservoir-based rate control tracking the
660688 // Encoder's current target on every frame — cheap (an Option<u32>
661689 // store) and catches set_bitrate calls made between frames.
662690 enc.set_bitrate(self.bitrate);
663- let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
691+ let n =
692+ enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?;
664693 self.final_range = enc.final_range();
665694 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
666695 }
@@ -698,9 +727,9 @@ impl Encoder {
698727 ));
699728 }
700729 };
701- let bandwidth = self
702- .bandwidth
703- .unwrap_or_else(|| self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est()));
730+ let bandwidth = self.bandwidth.unwrap_or_else(|| {
731+ self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est())
732+ });
704733 let bw_idx: u8 = match bandwidth {
705734 Bandwidth::Narrow => 0,
706735 // CELT has no mediumband configuration; the next one up covers it.
@@ -857,7 +886,12 @@ impl Encoder {
857886 /// not ported — every VoIP frame still gets this DC reject.
858887 /// Ships off with the alignment knob: `dc_reject` alone (without the
859888 /// input delay) has never been measured on the library gate.
860- fn dc_reject<'a>(&mut self, pcm: &'a [f32], frame_size: usize, out: &'a mut Vec<f32>) -> &'a [f32] {
889+ fn dc_reject<'a>(
890+ &mut self,
891+ pcm: &'a [f32],
892+ frame_size: usize,
893+ out: &'a mut Vec<f32>,
894+ ) -> &'a [f32] {
861895 if !self.align_input {
862896 return pcm;
863897 }
@@ -1001,11 +1035,13 @@ impl Encoder {
10011035 if self.channels == 2 {
10021036 let silk = self
10031037 .silk_stereo_wb
1004- .get_or_insert_with(|| SilkStereoEncoder::new(true));
1038+ .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true)));
10051039 silk.set_bitrate(silk_rate);
10061040 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
10071041 } else {
1008- let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
1042+ let silk = self
1043+ .silk_wb
1044+ .get_or_insert_with(|| Box::new(SilkEncoder::new(true)));
10091045 silk.set_bitrate(silk_rate);
10101046 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
10111047 }
@@ -1066,9 +1102,15 @@ impl Encoder {
10661102 (b.saturating_sub(1).clamp(2, cap), 0)
10671103 };
10681104 self.range.reset(budget);
1069- let n =
1070- self.celt
1071- .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate, &self.info)?;
1105+ let n = self.celt.encode(
1106+ &mut self.range,
1107+ pcm,
1108+ frame_size,
1109+ 0,
1110+ end,
1111+ vbr_rate,
1112+ &self.info,
1113+ )?;
10721114 self.final_range = self.range.range();
10731115 Ok(n)
10741116 }
@@ -1146,7 +1188,11 @@ mod tests {
11461188 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
11471189 e.set_bitrate(8000);
11481190 assert_eq!(e.look_ahead(480), 58, "10ms NB SILK");
1149- assert_eq!(e.look_ahead(240), CELT_OVERLAP_48K, "5ms frame falls back to CELT");
1191+ assert_eq!(
1192+ e.look_ahead(240),
1193+ CELT_OVERLAP_48K,
1194+ "5ms frame falls back to CELT"
1195+ );
11501196 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
11511197
11521198 // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap).
@@ -1154,7 +1200,11 @@ mod tests {
11541200 assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid FB");
11551201
11561202 e.set_bitrate(32000);
1157- assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid, CELT's delay");
1203+ assert_eq!(
1204+ e.look_ahead(960),
1205+ CELT_OVERLAP_48K,
1206+ "20ms hybrid, CELT's delay"
1207+ );
11581208
11591209 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
11601210 e.set_bitrate(8000);
crates/ec-opus/src/lib.rsmodified+8 -3
@@ -73,16 +73,17 @@ pub mod range;
7373 pub mod silk;
7474 pub(crate) mod silk_enc;
7575 pub mod silk_enc_write;
76+mod stack_budget;
7677
7778 pub use celt::CeltDecoder;
7879 pub use celt_enc::CeltFrameDiag;
7980 pub use encoder::{Application, Encoder};
80-pub use silk_enc_write::SilkFrameDiag;
8181 pub use multistream::MultistreamDecoder;
8282 pub use multistream_enc::MultistreamEncoder;
8383 pub use packet::{Bandwidth, Mode, Packet, Toc};
8484 pub use range::{RangeDecoder, RangeEncoder};
8585 pub use silk::{SilkDecIndices, SilkDecoder};
86+pub use silk_enc_write::SilkFrameDiag;
8687 pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder};
8788
8889 use ec_core::{Error, Result};
@@ -99,7 +100,11 @@ pub struct Decoder {
99100 channels: usize,
100101 downsample: usize,
101102 celt: CeltDecoder,
102- silk: SilkDecoder,
103+ /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder`
104+ /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
105+ /// decoder's largest field and its only large one; `celt` is 1168.
106+ /// `Stack`: crate::stack_budget.
107+ silk: Box<SilkDecoder>,
103108 /// The CELT overlap window, reused for redundancy cross-fades.
104109 celt_window: Vec<f32>,
105110 /// Per-frame scratch, allocated once: the SILK layer's output and the
@@ -154,7 +159,7 @@ impl Decoder {
154159 channels,
155160 downsample,
156161 celt: CeltDecoder::new(channels, downsample),
157- silk: SilkDecoder::new(sample_rate, channels),
162+ silk: Box::new(SilkDecoder::new(sample_rate, channels)),
158163 celt_window: celt::overlap_window(),
159164 silk_pcm: vec![0; 5760 * channels],
160165 redundant: vec![0.0; 240 * channels],
crates/ec-opus/src/stack_budget.rsadded+934 -0
@@ -0,0 +1,934 @@
1+#![cfg(test)]
2+//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3+//!
4+//! # The class
5+//!
6+//! A large struct returned BY VALUE from a public constructor is a stack cost,
7+//! not a heap cost, and the cost is paid by the CALLER. `Encoder` is the
8+//! workspace's largest live instance of this class: it was **87,024 bytes** by
9+//! value -- ten and a half times the budget below -- because six
10+//! `Option<SilkEncoder>` / `Option<SilkStereoEncoder>` slots (6,648 and 19,744
11+//! bytes each, 79,176 together) and a 3,831-byte SILK packet scratch buffer
12+//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type
13+//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the
14+//! budget, with a 6,304-byte `SilkDecoder` inline.
15+//!
16+//! Both are boxed now (82,952 bytes moved off the stack onto the heap: six
17+//! `Box`ed SILK encoders, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and
18+//! `Decoder::silk: Box<SilkDecoder>`), and this module is what stops the
19+//! numbers from walking back.
20+//!
21+//! # Why this module exists
22+//!
23+//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public
24+//! `fn` can return or take by value, with a measured `size_of` recorded as
25+//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size
26+//! moves, so the table cannot rot into a list of stale small numbers.
27+//! 2. [`STACK_BUDGET`] is the bound, and
28+//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
29+//! every budgeted row, so a regression reds naming the type that caused it.
30+//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the eight
31+//! `Box` spellings that moved the 87 KB off the stack, with a negative
32+//! control so the scan cannot be matching a doc comment.
33+//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
34+//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on
35+//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather
36+//! than quietly costing margin. Red/green in milliseconds.
37+//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
38+//! teeth against NEW types: a source scan re-derives the set of by-value
39+//! public returns from the crate source, so a lane that adds a 40 KB struct
40+//! to a `pub fn` return reds here until it is measured and listed.
41+//! [`the_inventory_scan_is_not_vacuous`] is its control, and
42+//! [`every_by_value_module_is_scanned`] keeps the scan's file list from
43+//! falling behind a new `mod` in `lib.rs`.
44+//!
45+//! # The bound, and why this number
46+//!
47+//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical
48+//! sweep uses, and it is bounded from BOTH sides by measurement:
49+//!
50+//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's
51+//! default test thread, and what `std::thread::Builder::new()` gives a
52+//! caller who does not ask for a size. This workspace's
53+//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides
54+//! the problem from its own runs; a library consumer gets no
55+//! `.cargo/config.toml` and no such cover.
56+//! * **The deepest PUBLIC by-value chain is 2**
57+//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` ->
58+//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both
59+//! handing back a `MultistreamDecoder` by value, so both frames hold a
60+//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new`
61+//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner
62+//! constructor of its own type, they build the struct literal inline -- so
63+//! the worst live set of by-value return slots is two frames, and the test
64+//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`.
65+//! * **The budget applies to types a public `fn` returns by value.** The
66+//! `Box`ed payloads are listed with `public: false` and measured, but not
67+//! budgeted, because the budget's job is to bound what a CALLER can be made
68+//! to own and none of them is reachable that way any more -- every field
69+//! that holds one is a `Box`, which
70+//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source.
71+//!
72+//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,072
73+//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4072 = 8,144` bytes --
74+//! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the
75+//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the
76+//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect
77+//! and the near-miss both red by a factor rather than by a hair.
78+//!
79+//! **What it does not claim.** `size_of` is layout, not stack depth: the
80+//! measured stack/size ratio on a by-value constructor here is several times
81+//! over, because the constructor's own frames add on top of the return slot.
82+//! That residual is why
83+//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for
84+//! real instead of trusting the arithmetic.
85+
86+use crate::Decoder;
87+use crate::encoder::Encoder;
88+
89+/// The per-type ceiling for a type a CALLER can be made to hold by value, in
90+/// bytes. See the module docs for the derivation; it is two-sided, and both
91+/// sides are measured.
92+pub(crate) const STACK_BUDGET: usize = 8192;
93+
94+/// The deepest PUBLIC by-value constructor chain in this crate, counted from
95+/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder::
96+/// try_with_rate` is two, both returning the same type by value so both frames
97+/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and
98+/// `Decoder::new` are one level each -- neither delegates to an inner
99+/// constructor of its own type. The budget is checked against two, the worse
100+/// of the chains.
101+const DEEPEST_PUBLIC_CHAIN: usize = 2;
102+
103+/// Every type in this crate a public `fn` can hand back BY VALUE (or take by
104+/// value in a public signature), with the `size_of` measured at the commit
105+/// that wrote this table. `None` means "not yet measured", which
106+/// [`the_measured_inventory_is_accurate`] rejects.
107+///
108+/// The third column names the return path, so a reader can see why a type is
109+/// here rather than a coincidence of the type system. `false` in that column
110+/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only
111+/// through a pointer now, and the pin that keeps it that way is
112+/// [`the_crate_private_silk_encoders_stay_behind_a_box`].
113+pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
114+ // -- lib.rs -----------------------------------------------------------
115+ (
116+ "Decoder",
117+ Some(1280),
118+ true,
119+ "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \
120+ because a 6304-byte SilkDecoder sat inline; that field is now a Box",
121+ ),
122+ // -- encoder.rs -------------------------------------------------------
123+ (
124+ "Encoder",
125+ Some(4072),
126+ true,
127+ "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \
128+ inline Option<SilkEncoder>/Option<SilkStereoEncoder> slots (79176 \
129+ together) and an inline 3831-byte silk_buf",
130+ ),
131+ (
132+ "Application",
133+ Some(1),
134+ true,
135+ "Encoder::new(.., application: Application) takes it by value and \
136+ stores it inline in every Encoder",
137+ ),
138+ // -- celt.rs ----------------------------------------------------------
139+ (
140+ "CeltDecoder",
141+ Some(1168),
142+ true,
143+ "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \
144+ value into Decoder::celt",
145+ ),
146+ // -- celt_enc.rs ------------------------------------------------------
147+ (
148+ "CeltEncoder",
149+ Some(1592),
150+ false,
151+ "celt_enc::CeltEncoder::new -> Self. `pub`, and stored inline in \
152+ Encoder::celt, but 1592 is 19% of budget and it is the second \
153+ largest field of a type that is itself budgeted; the crate-private \
154+ 19744 SilkStereoEncoder is the one this module had to pin",
155+ ),
156+ (
157+ "CeltFrameDiag",
158+ Some(424),
159+ true,
160+ "celt_enc::last_diag(&self) -> &CeltFrameDiag hands back a \
161+ reference; the row is here because Encoder::last_celt_diag and \
162+ Decoder::last_celt_diag name it in their signatures",
163+ ),
164+ // -- multistream.rs / multistream_enc.rs ------------------------------
165+ (
166+ "MultistreamDecoder",
167+ Some(96),
168+ true,
169+ "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \
170+ public by-value chain: with_rate -> try_with_rate -> Result<..>",
171+ ),
172+ (
173+ "MultistreamEncoder",
174+ Some(88),
175+ true,
176+ "MultistreamEncoder::surround_5_1 -> Result<MultistreamEncoder>",
177+ ),
178+ // -- packet.rs --------------------------------------------------------
179+ (
180+ "Packet",
181+ Some(40),
182+ true,
183+ "Packet::parse -> Result<Packet<'a>>",
184+ ),
185+ ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"),
186+ (
187+ "Mode",
188+ Some(1),
189+ true,
190+ "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode",
191+ ),
192+ (
193+ "Bandwidth",
194+ Some(1),
195+ true,
196+ "Toc::bandwidth(self) -> Bandwidth; also stored inline in \
197+ Encoder::bandwidth",
198+ ),
199+ // -- range.rs ---------------------------------------------------------
200+ (
201+ "RangeEncoder",
202+ Some(80),
203+ true,
204+ "RangeEncoder::new() -> Self; stored inline in Encoder::range",
205+ ),
206+ (
207+ "RangeDecoder",
208+ Some(56),
209+ true,
210+ "RangeDecoder::new(buf) -> RangeDecoder<'a>",
211+ ),
212+ (
213+ "EncSnapshot",
214+ Some(48),
215+ true,
216+ "RangeEncoder::snapshot(&self) -> EncSnapshot",
217+ ),
218+ // -- silk.rs ----------------------------------------------------------
219+ (
220+ "SilkDecoder",
221+ Some(6304),
222+ true,
223+ "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \
224+ root, so 6304 bytes is a caller's by-value cost TODAY even though \
225+ Decoder::new moves it straight into a Box. At 77% of the budget it \
226+ is the LARGEST budgeted row in the table, and the one that says how \
227+ little headroom the budget would have left if it had stayed inline",
228+ ),
229+ (
230+ "SilkDecIndices",
231+ Some(104),
232+ true,
233+ "SilkDecoder::last_indices(&self) -> SilkDecIndices",
234+ ),
235+ // -- silk_enc_write.rs ------------------------------------------------
236+ (
237+ "SilkEncoder",
238+ Some(6648),
239+ false,
240+ "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \
241+ crate root, and returned by value -- but every field that holds one \
242+ is an Option<Box<..>>, so no CALLER can be made to own it",
243+ ),
244+ (
245+ "SilkStereoEncoder",
246+ Some(19744),
247+ false,
248+ "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \
249+ type in the crate at 2.41x the budget, and the reason three of the \
250+ six Encoder slots are boxed rather than one",
251+ ),
252+ (
253+ "SilkFrameDiag",
254+ Some(56),
255+ true,
256+ "SilkEncoder::last_diag(&self) -> &SilkFrameDiag hands back a \
257+ reference",
258+ ),
259+ // -- analysis.rs (crate-private) --------------------------------------
260+ (
261+ "TonalityAnalysis",
262+ Some(2168),
263+ false,
264+ "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \
265+ INLINE in Encoder::analysis. 2168 is inside the budget and the field \
266+ is reached only through an Encoder that is itself budgeted, so it is \
267+ measured here rather than pinned behind a Box",
268+ ),
269+ (
270+ "AnalysisInfo",
271+ Some(60),
272+ false,
273+ "analysis::AnalysisInfo::default() -> Self, stored inline in \
274+ Encoder::info",
275+ ),
276+];
277+
278+/// The live `size_of` for every inventoried type, keyed BY NAME.
279+///
280+/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and
281+/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`]
282+/// without a matching insert here would zip cleanly and assert the wrong
283+/// type's size against the wrong recorded one. A name key makes that mistake
284+/// loud instead.
285+fn measured_by_name() -> Vec<(&'static str, usize)> {
286+ vec![
287+ ("Decoder", std::mem::size_of::<Decoder>()),
288+ ("Encoder", std::mem::size_of::<Encoder>()),
289+ (
290+ "Application",
291+ std::mem::size_of::<crate::encoder::Application>(),
292+ ),
293+ (
294+ "CeltDecoder",
295+ std::mem::size_of::<crate::celt::CeltDecoder>(),
296+ ),
297+ (
298+ "CeltEncoder",
299+ std::mem::size_of::<crate::celt_enc::CeltEncoder>(),
300+ ),
301+ (
302+ "CeltFrameDiag",
303+ std::mem::size_of::<crate::celt_enc::CeltFrameDiag>(),
304+ ),
305+ (
306+ "MultistreamDecoder",
307+ std::mem::size_of::<crate::multistream::MultistreamDecoder>(),
308+ ),
309+ (
310+ "MultistreamEncoder",
311+ std::mem::size_of::<crate::multistream_enc::MultistreamEncoder>(),
312+ ),
313+ (
314+ "Packet",
315+ std::mem::size_of::<crate::packet::Packet<'static>>(),
316+ ),
317+ ("Toc", std::mem::size_of::<crate::packet::Toc>()),
318+ ("Mode", std::mem::size_of::<crate::packet::Mode>()),
319+ ("Bandwidth", std::mem::size_of::<crate::packet::Bandwidth>()),
320+ (
321+ "RangeEncoder",
322+ std::mem::size_of::<crate::range::RangeEncoder>(),
323+ ),
324+ (
325+ "RangeDecoder",
326+ std::mem::size_of::<crate::range::RangeDecoder<'static>>(),
327+ ),
328+ (
329+ "EncSnapshot",
330+ std::mem::size_of::<crate::range::EncSnapshot>(),
331+ ),
332+ (
333+ "SilkDecoder",
334+ std::mem::size_of::<crate::silk::SilkDecoder>(),
335+ ),
336+ (
337+ "SilkDecIndices",
338+ std::mem::size_of::<crate::silk::SilkDecIndices>(),
339+ ),
340+ (
341+ "SilkEncoder",
342+ std::mem::size_of::<crate::silk_enc_write::SilkEncoder>(),
343+ ),
344+ (
345+ "SilkStereoEncoder",
346+ std::mem::size_of::<crate::silk_enc_write::SilkStereoEncoder>(),
347+ ),
348+ (
349+ "SilkFrameDiag",
350+ std::mem::size_of::<crate::silk_enc_write::SilkFrameDiag>(),
351+ ),
352+ (
353+ "TonalityAnalysis",
354+ std::mem::size_of::<crate::analysis::TonalityAnalysis>(),
355+ ),
356+ (
357+ "AnalysisInfo",
358+ std::mem::size_of::<crate::analysis::AnalysisInfo>(),
359+ ),
360+ ]
361+}
362+
363+/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
364+/// constructs on.
365+///
366+/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and
367+/// **5.3x** the deepest need measured in a debug build on the current layout
368+/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting
369+/// **2.1x below** the pre-fix layout's own threshold, which completes at
370+/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability
371+/// arm rather than a formality: at 256 KiB the layout this crate used to
372+/// ship ABORTS THE PROCESS. The sweep is reproducible with
373+/// `EC_OPUS_TIGHT_STACK_BYTES`.
374+const TIGHT_STACK: usize = 256 * 1024;
375+
376+#[cfg(test)]
377+mod tests {
378+ use super::{
379+ BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
380+ };
381+ use crate::Decoder;
382+ use crate::encoder::Encoder;
383+
384+ /// Return types that are not a by-value copy of anything the caller has to
385+ /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
386+ /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
387+ /// which the inventory rows already cover, so it is exempt from the scan
388+ /// and not from the table.
389+ const THIN: &[&str] = &[
390+ "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
391+ "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
392+ "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
393+ ];
394+
395+ /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
396+ /// returns a pointer, a `Vec`, a primitive, or nothing.
397+ ///
398+ /// One function, shared by the sweep and its control, so the control
399+ /// cannot pass while the sweep's copy of the logic rotted.
400+ fn by_value_return_name(line: &str) -> Option<String> {
401+ let trimmed = line.trim_start();
402+ if !trimmed.starts_with("pub fn ") {
403+ return None;
404+ }
405+ let arrow = line.find("->")?;
406+ let rest = &line[arrow + 2..];
407+ let end = rest.find('{').unwrap_or(rest.len());
408+ let ret = rest[..end].trim();
409+ if ret.is_empty() {
410+ return None;
411+ }
412+ // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
413+ // not a shape this crate uses, and flagging one as uninventoried is
414+ // the safe direction to be wrong in.
415+ let inner = {
416+ let t = ret
417+ .strip_prefix("Result<")
418+ .or_else(|| ret.strip_prefix("Option<"))
419+ .unwrap_or(ret);
420+ t.split('>').next().unwrap_or(t)
421+ };
422+ // Drop the error type and any lifetime or generic argument:
423+ // `Result<Decoder, Error>`, `RangeDecoder<'a>` and `Packet<'a>` are
424+ // all the bare name for this purpose. Splitting on the comma is
425+ // load-bearing: a matcher that cut only at `>` would read
426+ // `Result<Decoder, Error>` as the name "Decoder, Error".
427+ // `the_inventory_scan_is_not_vacuous` covers exactly that, which is
428+ // why the control is not optional.
429+ let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
430+ if name.is_empty() || THIN.contains(&name) {
431+ return None;
432+ }
433+ // A generic parameter, not a concrete type.
434+ if !name.chars().next().is_some_and(char::is_uppercase) {
435+ return None;
436+ }
437+ Some(name.to_string())
438+ }
439+
440+ /// The source files the by-value scan reads. Every module `lib.rs`
441+ /// declares, plus `lib.rs` itself (which is where `Decoder` and
442+ /// `Encoder::new`'s crate-root sibling live) and this module.
443+ const FILES: &[(&str, &str)] = &[
444+ ("analysis.rs", include_str!("analysis.rs")),
445+ ("celt.rs", include_str!("celt.rs")),
446+ ("celt_enc.rs", include_str!("celt_enc.rs")),
447+ ("encoder.rs", include_str!("encoder.rs")),
448+ ("lib.rs", include_str!("lib.rs")),
449+ ("multistream.rs", include_str!("multistream.rs")),
450+ ("multistream_enc.rs", include_str!("multistream_enc.rs")),
451+ ("ogg.rs", include_str!("ogg.rs")),
452+ ("packet.rs", include_str!("packet.rs")),
453+ ("range.rs", include_str!("range.rs")),
454+ ("silk.rs", include_str!("silk.rs")),
455+ ("silk_enc.rs", include_str!("silk_enc.rs")),
456+ ("silk_enc_write.rs", include_str!("silk_enc_write.rs")),
457+ ("stack_budget.rs", include_str!("stack_budget.rs")),
458+ ];
459+
460+ /// Every module `lib.rs` declares, so the scan's file list cannot silently
461+ /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
462+ /// that the scan never reads is exactly the hole this class would come
463+ /// back through, so the list is derived, not curated.
464+ ///
465+ /// `pub(crate) mod foo;` is a module too, and ec-opus has two of them
466+ /// (`analysis`, `silk_enc`), so the derivation strips the visibility
467+ /// parenthesised form as well as the bare `pub`.
468+ #[test]
469+ fn every_by_value_module_is_scanned() {
470+ let lib = include_str!("lib.rs");
471+ let mut declared: Vec<&str> = Vec::new();
472+ for line in lib.lines() {
473+ let t = line.trim();
474+ let after_pub = if let Some(rest) = t.strip_prefix("pub(") {
475+ // `pub(crate) mod foo;` / `pub(super) mod foo;`
476+ rest.split_once(')')
477+ .map(|(_, after)| after.trim_start())
478+ .unwrap_or("")
479+ } else {
480+ t.strip_prefix("pub ").unwrap_or(t)
481+ };
482+ let Some(rest) = after_pub.strip_prefix("mod ") else {
483+ continue;
484+ };
485+ let name = rest.split([';', ' ']).next().unwrap_or("");
486+ if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
487+ declared.push(name);
488+ }
489+ }
490+ assert!(
491+ declared.len() > 8,
492+ "only {} module declarations parsed out of lib.rs, so the \
493+ derived file list is broken rather than small",
494+ declared.len()
495+ );
496+ let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
497+ let mut missing: Vec<String> = declared
498+ .iter()
499+ .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
500+ .map(|d| (*d).to_string())
501+ .collect();
502+ missing.sort();
503+ assert!(
504+ missing.is_empty(),
505+ "lib.rs declares modules the by-value scan never reads: {:?}. Add \
506+ them to FILES, or the sweep cannot see a new by-value return that \
507+ lands in one of them.",
508+ missing
509+ );
510+ }
511+
512+ /// The inventory, printed as a sorted table, and checked against the
513+ /// types' real sizes.
514+ ///
515+ /// The print is the instrument: one command reproduces the whole table,
516+ /// biggest first, so "what is the largest by-value type in this crate"
517+ /// has an answer that is a measurement rather than a grep.
518+ ///
519+ /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the
520+ /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps
521+ /// every test binary in `scripts/memguard-runner.sh`, which buffers a
522+ /// green run's stdout and prints nothing. The table appears on a failing
523+ /// run, or by invoking the built binary directly
524+ /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`).
525+ ///
526+ /// The check reds on ANY change with both numbers. That is deliberate: a
527+ /// by-value type that grew raises the question of whether it should have
528+ /// been boxed instead, and auto-accepting the new number would answer
529+ /// that question by default.
530+ #[test]
531+ fn the_measured_inventory_is_accurate() {
532+ let live = measured_by_name();
533+ assert_eq!(
534+ BY_VALUE_TYPES.len(),
535+ live.len(),
536+ "the inventory names {} types but {} are measured; every row needs \
537+ a measured size or the sweep is a list of hopes",
538+ BY_VALUE_TYPES.len(),
539+ live.len()
540+ );
541+ let mut rows: Vec<(&str, usize)> = live.clone();
542+ rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
543+ eprintln!(
544+ "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
545+ rows.len(),
546+ STACK_BUDGET / 1024
547+ );
548+ eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE");
549+ for (name, size) in &rows {
550+ eprintln!(
551+ "{size:>8} {:>6.1}% {name}",
552+ *size as f64 * 100.0 / STACK_BUDGET as f64
553+ );
554+ }
555+ for (name, recorded, _public, _path) in BY_VALUE_TYPES {
556+ let recorded = recorded.expect("every inventory row carries a measured size");
557+ let actual = live
558+ .iter()
559+ .find(|(n, _)| n == name)
560+ .map(|(_, size)| *size)
561+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
562+ assert_eq!(
563+ recorded, actual,
564+ "{name} is {actual} bytes, the inventory records {recorded}; \
565+ update the table deliberately -- a by-value type that changed \
566+ is a stack cost every caller of its constructor now pays"
567+ );
568+ }
569+ }
570+
571+ /// The bound, asserted BY NAME. A regression in any inventoried type reds
572+ /// here naming the type, not "some type is too big".
573+ #[test]
574+ fn every_by_value_type_fits_the_stack_budget() {
575+ let live = measured_by_name();
576+ let mut checked = 0usize;
577+ for (name, _, public, path) in BY_VALUE_TYPES {
578+ if !public {
579+ continue;
580+ }
581+ checked += 1;
582+ let size = live
583+ .iter()
584+ .find(|(n, _)| n == name)
585+ .map(|(_, size)| *size)
586+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
587+ assert!(
588+ size <= STACK_BUDGET,
589+ "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
590+ stack budget ({:.2}x). It is returned by value from {path}, so \
591+ every caller pays it on its own stack, and the constructors \
592+ nest -- one value's size is the multiplier, not the cost. \
593+ Box the large field: Encoder's six SILK slots and silk_buf, \
594+ and Decoder::silk, are Boxed for exactly this reason and \
595+ took Encoder from 87024 bytes to this one.",
596+ size as f64 / STACK_BUDGET as f64
597+ );
598+ }
599+ assert!(
600+ checked >= 10,
601+ "only {checked} rows were bound-checked; the budget must apply to \
602+ every type a caller can be made to hold by value"
603+ );
604+ // The other half of the derivation, asserted so it cannot rot: the
605+ // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
606+ let worst = live
607+ .iter()
608+ .filter(|(n, _)| {
609+ BY_VALUE_TYPES
610+ .iter()
611+ .any(|(row, _, public, _)| row == n && *public)
612+ })
613+ .map(|(_, size)| *size)
614+ .max()
615+ .expect("at least one public row");
616+ assert!(
617+ DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
618+ "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
619+ public by-value return ({worst} B) is {} B, over an eighth of the \
620+ 2 MiB stack an unconfigured caller hands this crate; re-derive \
621+ STACK_BUDGET",
622+ DEEPEST_PUBLIC_CHAIN * worst
623+ );
624+ }
625+
626+ /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX.
627+ ///
628+ /// The budget does not apply to `SilkEncoder` (6,648 B),
629+ /// `SilkStereoEncoder` (19,744 B) or the 3,831-byte `silk_buf`, because
630+ /// every field holding one is a `Box` and no caller can reach them by
631+ /// value any more. What keeps them off the stack is those exact `Box`
632+ /// spellings, and THIS is the pin for that -- a source scan over the
633+ /// declarations, with a negative control so it cannot be matching a doc
634+ /// comment.
635+ ///
636+ /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from
637+ /// 4,072 to **7,896** bytes and reds this pin naming
638+ /// `encoder.rs::Encoder::silk_buf` and
639+ /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing any
640+ /// of the six SILK slots is far larger -- `Encoder` was 87,024 bytes
641+ /// before the boxing, 10.62x the budget.
642+ #[test]
643+ fn the_crate_private_silk_encoders_stay_behind_a_box() {
644+ const PINS: &[(&str, &str, &str)] = &[
645+ (
646+ "encoder.rs",
647+ "Encoder::silk_nb",
648+ "silk_nb: Option<Box<SilkEncoder>>",
649+ ),
650+ (
651+ "encoder.rs",
652+ "Encoder::silk_mb",
653+ "silk_mb: Option<Box<SilkEncoder>>",
654+ ),
655+ (
656+ "encoder.rs",
657+ "Encoder::silk_wb",
658+ "silk_wb: Option<Box<SilkEncoder>>",
659+ ),
660+ (
661+ "encoder.rs",
662+ "Encoder::silk_stereo_nb",
663+ "silk_stereo_nb: Option<Box<SilkStereoEncoder>>",
664+ ),
665+ (
666+ "encoder.rs",
667+ "Encoder::silk_stereo_mb",
668+ "silk_stereo_mb: Option<Box<SilkStereoEncoder>>",
669+ ),
670+ (
671+ "encoder.rs",
672+ "Encoder::silk_stereo_wb",
673+ "silk_stereo_wb: Option<Box<SilkStereoEncoder>>",
674+ ),
675+ (
676+ "encoder.rs",
677+ "Encoder::silk_buf",
678+ "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>",
679+ ),
680+ ("lib.rs", "Decoder::silk", "silk: Box<SilkDecoder>"),
681+ ];
682+ const SCANNED: &[(&str, &str)] = &[
683+ ("encoder.rs", include_str!("encoder.rs")),
684+ ("lib.rs", include_str!("lib.rs")),
685+ ];
686+ for (file, field, spelling) in PINS {
687+ let src = SCANNED
688+ .iter()
689+ .find(|(name, _)| name == file)
690+ .map(|(_, src)| *src)
691+ .unwrap_or_else(|| panic!("no source pinned for {file}"));
692+ let where_ = format!("{file}::{field}");
693+ assert!(
694+ src.contains(spelling),
695+ "{where_} is no longer declared `{spelling}`. An inline SILK \
696+ encoder or scratch buffer there puts {field}'s bytes back on \
697+ every caller's stack -- that is how Encoder was 87024 bytes \
698+ and Decoder 7576 before the boxing, 10.62x the by-value budget \
699+ on the type Encoder::new hands back by value."
700+ );
701+ }
702+ // And the negative control: the UNBOXED spellings must be ABSENT, or
703+ // the scan above could be matching a doc comment instead of the live
704+ // declaration. The unboxed forms are what this lane removed, so their
705+ // absence is the proof the pin is reading the code.
706+ const UNBOXED: &[(&str, &str, &str)] = &[
707+ (
708+ "encoder.rs",
709+ "Encoder::silk_nb",
710+ "silk_nb: Option<SilkEncoder>,",
711+ ),
712+ (
713+ "encoder.rs",
714+ "Encoder::silk_stereo_wb",
715+ "silk_stereo_wb: Option<SilkStereoEncoder>,",
716+ ),
717+ (
718+ "encoder.rs",
719+ "Encoder::silk_buf",
720+ "silk_buf: [u8; MAX_SILK_PACKET_BYTES],",
721+ ),
722+ ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"),
723+ ];
724+ for (file, field, spelling) in UNBOXED {
725+ let src = SCANNED
726+ .iter()
727+ .find(|(name, _)| name == file)
728+ .map(|(_, src)| *src)
729+ .unwrap_or_else(|| panic!("no source pinned for {file}"));
730+ assert!(
731+ !src.contains(spelling),
732+ "{} is declared unboxed as `{spelling}`. The box pin is \
733+ matching a spelling that is not the live declaration, and \
734+ {field}'s bytes are back on every caller's stack.",
735+ format!("{file}::{field}")
736+ );
737+ }
738+ }
739+
740+ /// CAPABILITY: really construct the heavy types on a tight stack, so a
741+ /// regression ABORTS THE PROCESS instead of costing invisible margin.
742+ ///
743+ /// Both arms are the crate's by-value constructors: `Encoder::new`, the
744+ /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real
745+ /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the
746+ /// decoder is proved live on this thread rather than merely constructed.
747+ ///
748+ /// Measured stack need, **debug** build, one process per point so a
749+ /// SIGABRT cannot truncate the sweep:
750+ ///
751+ /// | stack | pre-fix layout (inline SILK slots) | current layout |
752+ /// |---|---|---|
753+ /// | 32768 | overflow | **overflow** |
754+ /// | 49152 | overflow | **ok** |
755+ /// | 131072 | overflow | ok |
756+ /// | 262144 (**the gate**) | **overflow** | **ok** |
757+ /// | 524288 | **overflow** | ok |
758+ /// | 557056 | ok | ok |
759+ /// | 786432 | ok | ok |
760+ /// | 1048576 | ok | ok |
761+ ///
762+ /// The gate sits at 256 KiB, **5.3x** the measured need of the current
763+ /// layout and **2.1x** below the pre-fix layout's own threshold. Note
764+ /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB,
765+ /// so a gate set at 1 MiB would have been a formality -- a test that
766+ /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES`
767+ /// overrides the size, which is how the table is reproduced.
768+ ///
769+ /// The results are checked, not just the absence of a crash: an `Encoder`
770+ /// that constructed but came back with the wrong channel count, or a
771+ /// `Decoder` that decoded a packet to silence, would both pass a
772+ /// "did not overflow" assertion.
773+ #[test]
774+ fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
775+ use crate::encoder::Application;
776+ let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES")
777+ .ok()
778+ .and_then(|v| v.parse().ok())
779+ .unwrap_or(TIGHT_STACK);
780+ let handle = std::thread::Builder::new()
781+ .stack_size(stack)
782+ .spawn(move || {
783+ // Arm 1: the by-value constructor that was 10.62x the budget.
784+ let encoder = Encoder::new(48000, 1, Application::Audio)
785+ .expect("Encoder::new(48000, 1, Audio)");
786+ let channels = encoder.channels();
787+ let rate = encoder.sample_rate();
788+ drop(encoder);
789+ let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)");
790+ // A real packet, so the decoder is proved live on this thread
791+ // rather than merely constructed: the SILK-only 20 ms packet
792+ // below decodes through the same by-value Decoder.
793+ let mut out = vec![0.0f32; 5760];
794+ let written = decoder
795+ .decode_float(SILK_ONLY_PACKET, &mut out)
796+ .expect("decode_float on the tight-stack thread");
797+ let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs()));
798+ (channels, rate, written, peak)
799+ })
800+ .expect("spawn tight-stack thread");
801+ let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| {
802+ panic!(
803+ "a by-value constructor overflowed a {stack}-byte stack; \
804+ EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep"
805+ )
806+ });
807+ assert_eq!(channels, 1, "Encoder::new lost its channel count");
808+ assert_eq!(rate, 48000, "Encoder::new lost its sample rate");
809+ assert_eq!(
810+ pcm_len, 960,
811+ "Decoder::decode_float returned {pcm_len} samples, not the 960 one \
812+ 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \
813+ Decoder that cannot decode"
814+ );
815+ assert!(
816+ peak > 0.0,
817+ "Decoder::decode_float returned silence (peak {peak}) on the \
818+ tight-stack thread"
819+ );
820+ eprintln!(
821+ "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \
822+ bytes, both constructors returned and decoded 960 samples",
823+ std::mem::size_of::<Encoder>(),
824+ std::mem::size_of::<Decoder>(),
825+ std::mem::size_of::<crate::silk::SilkDecoder>(),
826+ );
827+ }
828+
829+ /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK
830+ /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame
831+ /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is
832+ /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than
833+ /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz.
834+ const SILK_ONLY_PACKET: &[u8] = &[
835+ 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
836+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
837+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
838+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
839+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
840+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
841+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
842+ ];
843+
844+ /// The sweep's teeth against a NEW by-value return: re-derive the set from
845+ /// the crate source and require every name to be inventoried.
846+ ///
847+ /// Without this the inventory is a list of what someone remembered to
848+ /// measure, and a lane that adds `pub fn make() -> HugeThing` where
849+ /// `HugeThing` is 200 KB of inline tables passes every other test here.
850+ #[test]
851+ fn every_by_value_public_return_is_in_the_inventory() {
852+ let mut found: Vec<(String, String)> = Vec::new();
853+ for (file, src) in FILES {
854+ for (n, line) in src.lines().enumerate() {
855+ if let Some(name) = by_value_return_name(line) {
856+ found.push((name, format!("{file}:{}", n + 1)));
857+ }
858+ }
859+ }
860+ found.sort();
861+ found.dedup();
862+ assert!(
863+ found.len() > 5,
864+ "the by-value return scan found {} names across {} files, which is \
865+ too few to be a real sweep -- the matcher, not the crate, is broken",
866+ found.len(),
867+ FILES.len()
868+ );
869+
870+ let mut missing = Vec::new();
871+ for (name, site) in &found {
872+ if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
873+ missing.push(format!("{name} ({site})"));
874+ }
875+ }
876+ assert!(
877+ missing.is_empty(),
878+ "these types are returned BY VALUE from a public fn and are not in \
879+ the inventory: {}. Either they are thin enough not to be a stack \
880+ cost -- say so by adding a row with its measured size -- or they \
881+ are the next instance of the class this module exists for.",
882+ missing.join(", ")
883+ );
884+ }
885+
886+ /// The control for the scan above, on synthetic text rather than by
887+ /// trusting the live tree to happen to contain a case.
888+ ///
889+ /// If the matcher silently stopped recognising a shape, the sweep would
890+ /// pass everything and this would still be asserting nothing. So: every
891+ /// by-value spelling the crate uses must yield its type name, and every
892+ /// pointer/Vec/primitive/`Self` spelling must yield nothing.
893+ #[test]
894+ fn the_inventory_scan_is_not_vacuous() {
895+ for synthetic in [
896+ "pub fn zz_a() -> ZzNotInventoried { todo!() }",
897+ "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
898+ "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
899+ "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
900+ "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
901+ ] {
902+ let name = by_value_return_name(synthetic)
903+ .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
904+ assert_eq!(
905+ name, "ZzNotInventoried",
906+ "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
907+ cannot see a new by-value return and its green is vacuous"
908+ );
909+ assert!(
910+ !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
911+ "the synthetic control name is in the inventory, so the control \
912+ proves nothing"
913+ );
914+ }
915+ for thin in [
916+ "pub fn zz_t() -> Box<Decoder> { todo!() }",
917+ "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
918+ "pub fn zz_v() -> Option<&Path> { todo!() }",
919+ "pub fn zz_w() -> usize { todo!() }",
920+ "pub fn zz_x() -> Self { todo!() }",
921+ "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
922+ "pub fn zz_z() { todo!() }",
923+ "fn zz_private() -> ZzNotInventoried { todo!() }",
924+ ] {
925+ assert_eq!(
926+ by_value_return_name(thin),
927+ None,
928+ "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
929+ above already cover, or not a `pub fn` -- the matcher must not \
930+ read it as an uninventoried by-value return"
931+ );
932+ }
933+ }
934+}
crates/ec-vp9/src/decode.rsmodified+23 -13
@@ -126,12 +126,22 @@ impl Planes {
126126 /// for the `VP90` codec.
127127 pub struct Decoder {
128128 parser: Vp9Parser,
129- ctx: FrameContext,
129+ /// The frame context in force for the frame being parsed.
130+ ///
131+ /// Boxed for the same reason as `frame_ctxs` below: a `FrameContext` is
132+ /// 2039 bytes, and leaving this one inline put 73% of the whole `Decoder`
133+ /// back on the stack. `Stack`: crate::stack_budget.
134+ ctx: Box<FrameContext>,
130135 refs: [Option<RefFrame>; 8],
131136 /// Frame scratch, live only inside `decode_keyframe`.
132137 planes: Option<Planes>,
133138 /// The four stored frame contexts (spec 6.2 `frame_context_idx`).
134- frame_ctxs: [FrameContext; 4],
139+ ///
140+ /// Boxed because a `FrameContext` is 2039 bytes and four of them inline
141+ /// are 8156 of the 10944 a `Decoder` costs a caller that takes one BY
142+ /// VALUE from `Decoder::new`. Indexing and whole-array assignment read
143+ /// through the box. `Stack`: crate::stack_budget.
144+ frame_ctxs: Box<[FrameContext; 4]>,
135145 /// The previous frame's per-8x8 MV field and segment map
136146 /// (`prev_frame->mvs` / `last_frame_seg_map`).
137147 prev_mvs: Vec<crate::inter::MvRef>,
@@ -203,12 +213,12 @@ impl Decoder {
203213 pub fn new() -> Self {
204214 Decoder {
205215 parser: Vp9Parser::new(),
206- ctx: FrameContext::new(true),
216+ ctx: Box::new(FrameContext::new(true)),
207217 refs: [const { None }; 8],
208218 planes: None,
209219 frame_ctxs: {
210220 let d = FrameContext::new(false);
211- [d.clone(), d.clone(), d.clone(), d]
221+ Box::new([d.clone(), d.clone(), d.clone(), d])
212222 },
213223 prev_mvs: Vec::new(),
214224 prev_seg: Vec::new(),
@@ -277,8 +287,8 @@ impl Decoder {
277287 // (libvpx `get_partition_probs`), which our `new(true)` models on the
278288 // active copy only.
279289 let d = FrameContext::new(false);
280- self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
281- self.ctx = FrameContext::new(true);
290+ self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
291+ self.ctx = Box::new(FrameContext::new(true));
282292 self.prev_mvs.clear();
283293 self.prev_seg.clear();
284294 self.last = LastFrameFacts {
@@ -310,7 +320,7 @@ impl Decoder {
310320 let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?;
311321 if hdr.refresh_frame_context {
312322 self.ctx.reset_inter_partition();
313- self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone();
323+ self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone();
314324 }
315325 // Reference refresh (spec 8.10): a keyframe updates all slots.
316326 let frame = RefFrame {
@@ -349,7 +359,7 @@ impl Decoder {
349359 let hdr = hdr.clone();
350360 if hdr.error_resilient_mode || hdr.reset_frame_context == 3 {
351361 let d = FrameContext::new(false);
352- self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
362+ self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
353363 } else if hdr.reset_frame_context == 2 {
354364 self.frame_ctxs[0] = FrameContext::new(false);
355365 }
@@ -357,7 +367,7 @@ impl Decoder {
357367 let mut ctx = self.frame_ctxs[0].clone();
358368 let stored_partition = ctx.partition;
359369 ctx.use_key_partition();
360- self.ctx = ctx;
370+ self.ctx = Box::new(ctx);
361371 self.prev_seg.clear();
362372 self.prev_mvs.clear();
363373 self.last = LastFrameFacts {
@@ -378,7 +388,7 @@ impl Decoder {
378388 // Store back with the partition probs the context arrived with:
379389 // the const key table is not a `FRAME_CONTEXT` field.
380390 self.ctx.partition = stored_partition;
381- self.frame_ctxs[0] = self.ctx.clone();
391+ self.frame_ctxs[0] = self.ctx.as_ref().clone();
382392 }
383393 // Reference refresh (spec 8.10): only `refresh_frame_flags` slots.
384394 let frame = RefFrame {
@@ -448,11 +458,11 @@ impl Decoder {
448458 // "reset after this frame" and takes no action at frame start.
449459 if hdr.reset_frame_context == 3 {
450460 let d = FrameContext::new(false);
451- self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
461+ self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
452462 } else if hdr.reset_frame_context == 2 {
453463 self.frame_ctxs[hdr.frame_context_idx as usize] = FrameContext::new(false);
454464 }
455- self.ctx = self.frame_ctxs[hdr.frame_context_idx as usize].clone();
465+ self.ctx = Box::new(self.frame_ctxs[hdr.frame_context_idx as usize].clone());
456466
457467 // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST,
458468 // GOLDEN and ALTREF use. libvpx validates every named reference's
@@ -642,7 +652,7 @@ impl Decoder {
642652 key: false,
643653 };
644654 if hdr.refresh_frame_context {
645- self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone();
655+ self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone();
646656 }
647657 if crate::interdump_enabled() {
648658 eprintln!(
crates/ec-vp9/src/lib.rsmodified+1 -0
@@ -33,6 +33,7 @@ pub mod intra;
3333 pub mod loopfilter;
3434 pub(crate) mod mc;
3535 pub mod modes;
36+mod stack_budget;
3637 pub mod stream;
3738 pub mod tables;
3839 pub mod tokens;
crates/ec-vp9/src/stack_budget.rsadded+733 -0
@@ -0,0 +1,733 @@
1+#![cfg(test)]
2+//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3+//!
4+//! # The class
5+//!
6+//! A large struct returned BY VALUE from a public constructor is a stack
7+//! cost, not a heap cost, and the cost is paid by the CALLER. The
8+//! constructors nest, and in an unoptimized build each level materialises
9+//! its whole `Result<T>` return slot before the inner call returns. So one
10+//! value's `size_of` is the MULTIPLIER, and the chain length is the other
11+//! factor.
12+//!
13+//! That is not hypothetical. `Decoder` was **10,944** bytes by value --
14+//! five INLINE `FrameContext` slots (2,039 bytes each: the `frame_ctxs`
15+//! array of four, plus the `ctx` in force) -- and 10,944 is **1.34x** this
16+//! crate's 8 KiB by-value budget. Boxing both fields
17+//! (`frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box<FrameContext>`) took
18+//! it to **768**, and [`the_frame_contexts_stay_behind_a_box`] is the pin
19+//! that keeps it there.
20+//!
21+//! # Why this module exists
22+//!
23+//! One boxed field is one measurement. This module is the sweep:
24+//!
25+//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a
26+//! public `fn` can return by value, with a measured `size_of` recorded
27+//! as of this commit. [`the_measured_inventory_is_accurate`] fails if a
28+//! type's size moves, so the table cannot rot into stale small numbers.
29+//! 2. [`STACK_BUDGET`] is the bound, and
30+//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
31+//! every public row, so a regression reds naming the type.
32+//! 3. [`the_frame_contexts_stay_behind_a_box`] pins the boxed field, with
33+//! a negative control so the pin cannot be matching a comment.
34+//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
35+//! capability arm: it really constructs `Decoder` on a deliberately
36+//! tight thread and asserts real post-construction state, pinning the
37+//! measured live stack of the by-value return path. At 256 KiB it does
38+//! NOT red the unboxing mutation -- a 10,944-byte struct is not that
39+//! expensive; the budget assert and the box pin are what red, BY NAME.
40+//! The arm's own docs carry the measured threshold table.
41+//! 5. [`every_by_value_public_return_is_in_the_inventory`] re-derives the
42+//! set of by-value public returns from the crate source.
43+//! [`the_inventory_scan_is_not_vacuous`] is its control.
44+//!
45+//! # The bound, and why this number
46+//!
47+//! [`STACK_BUDGET`] = 8192 bytes (8 KiB) -- the SAME number as ec-av1's,
48+//! deliberately, so one bound covers the by-value class across the codec
49+//! crates rather than each crate calibrating its own.
50+//!
51+//! **The quantity being bounded.** Not `size_of` in the abstract, but
52+//! *what a caller can be made to owe*: the size of one by-value return,
53+//! multiplied by how many public levels hold a copy at once. Three inputs:
54+//! 1. **The smallest stack a caller can hand this crate is 2 MiB.** That
55+//! is libtest's default test thread and what `std::thread::Builder`
56+//! hands a caller who does not ask for a size. A library consumer gets
57+//! no `.cargo/config.toml` -- and this repo's sets
58+//! `RUST_MIN_STACK = 67108864`, which HIDES the problem from this
59+//! workspace's own runs. The bound is therefore derived against the
60+//! 2 MiB an unconfigured caller really has.
61+//! 2. **The deepest PUBLIC by-value chain is 3**
62+//! ([`DEEPEST_PUBLIC_CHAIN`]): `stream::decode_stream` (stream.rs:74)
63+//! -> `stream::decode_stream_with` (stream.rs:88) ->
64+//! `Decoder::decode` (decode.rs:238), after which the remaining frames
65+//! (`decode_one`, `decode_keyframe`, `decode_inter`) are private. The
66+//! test asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- the
67+//! by-value return slots may claim at most an EIGHTH of a caller's
68+//! stack, leaving the rest for the decode walk, which is the thing that
69+//! actually needs it.
70+//! 3. **The budget applies only to types a `pub fn` returns.** The
71+//! crate-private 2,039-byte `FrameContext` is measured and listed but
72+//! NOT bounded, because no caller can reach it by value -- every field
73+//! holding one is a `Box`, pinned by
74+//! [`the_frame_contexts_stay_behind_a_box`]. Bounding it would
75+//! calibrate the number to something unreachable.
76+//!
77+//! **Where the number sits.** At 8 KiB with the worst public return at
78+//! 768 bytes ([`Decoder`]), the worst a caller owes on return slots
79+//! alone is `3 x 768 = 2,304` bytes -- 0.11% of a 2 MiB thread, and the
80+//! budget itself is 10.7x the largest live by-value type. Both directions
81+//! have room, which is the point: a bound the largest type sits just
82+//! under is a bound the next lane will quietly raise.
83+//!
84+//! **What it catches.** The pre-fix `Decoder` (10,944 B) is **1.34x over**
85+//! -- the SMALLEST over-budget case of the three crates this sweep has
86+//! measured (ec-av1's pre-fix `Av1Encoder` was 17.1x over, ec-ac3's
87+//! pre-fix `Ac3Decoder` 2.43x). It still reds, and by a factor rather than
88+//! a hair, which is all a bound has to do.
89+//!
90+//! # This crate's inventory is SMALL, and that is a measurement
91+//!
92+//! ec-av1's floor for bound-checked public rows is 10. **ec-vp9 genuinely
93+//! has 3** ([`Decoder`], [`Picture`], [`BoolDecoder`]) and the floor is
94+//! lowered to 3 rather than padded with types this crate does not have.
95+//! The reason is structural, not accidental: every other module here
96+//! (`inter`, `mc`, `modes`, `tokens`, `transform`, `loopfilter`, `intra`,
97+//! `header`, `tables`) exposes ZERO `pub fn` -- its API is
98+//! `pub(crate)`, reached through `Decoder`. There are 13 `pub fn` lines
99+//! in the whole crate, 11 of which return a primitive, a `Self`, or
100+//! `()`.
101+//!
102+//! The sweep is still worth having at that size, and the reason is
103+//! direction of travel: the scan found exactly ONE by-value public return
104+//! name (`Picture`, from `Decoder::decode`), because `Decoder::new`
105+//! returns `Self` and `BoolDecoder::new` returns `Result<Self>`, both of
106+//! which the matcher exempts. A tiny inventory is a floor to grow into,
107+//! and [`every_by_value_public_return_is_in_the_inventory`] is what makes
108+//! a new 40 KB by-value return impossible to add unnoticed -- which is the
109+//! only direction that can actually bite here.
110+//!
111+//! # What it does not claim
112+//!
113+//! `size_of` is layout, not stack depth. The residual is why
114+//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs
115+//! for real instead of trusting the arithmetic. And note
116+//! [`the_frame_contexts_stay_behind_a_box`] pins ONE field: `Decoder::ctx`
117+//! (decode.rs:129) is still an INLINE `FrameContext`, and at 2,039 bytes
118+//! it is 72.8% of the 2,800 a caller pays today. Boxing that too is the
119+//! obvious next move in this class; this module only records the
120+//! measurement.
121+
122+use crate::bool::BoolDecoder;
123+use crate::decode::{Decoder, Picture};
124+
125+/// The per-type ceiling for a type a CALLER can be made to hold by value, in
126+/// bytes. See the module docs for the derivation; it is two-sided, and both
127+/// sides are measured.
128+pub(crate) const STACK_BUDGET: usize = 8192;
129+
130+/// The deepest PUBLIC by-value chain in this crate, counted from the source:
131+/// `stream::decode_stream` (stream.rs:74) -> `stream::decode_stream_with`
132+/// (stream.rs:88) -> `Decoder::decode` (decode.rs:238) is three public
133+/// levels, after which `decode_one` / `decode_keyframe` / `decode_inter`
134+/// are private. The budget is checked against three.
135+///
136+/// The by-value return slots IN that chain are all small
137+/// (`Result<Vec<Picture>>`, `Result<()>`, `Result<Option<Picture>>`); the
138+/// 2,800-byte `Decoder` is a by-value LOCAL in `decode_stream_with` that
139+/// stays live across the inner `decode` calls. Multiplying the chain by the
140+/// crate's worst public return is the conservative direction, and is what
141+/// [`every_by_value_type_fits_the_stack_budget`] asserts.
142+#[cfg(test)]
143+const DEEPEST_PUBLIC_CHAIN: usize = 3;
144+
145+/// Every type in this crate a public `fn` can return BY VALUE, with the
146+/// `size_of` measured at the commit that wrote this table. `None` means "not
147+/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
148+///
149+/// The third column names the return path, so a reader can see why a type is
150+/// here rather than a coincidence of the type system.
151+pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
152+ // -- decode.rs --------------------------------------------------------
153+ (
154+ "Decoder",
155+ Some(768),
156+ true,
157+ "Decoder::new -> Self (and `Default::default`), the crate's whole \
158+ public surface. Was 10944 with five inline FrameContext slots \
159+ (10,195 of it), 1.34x over budget; frame_ctxs and ctx are both \
160+ Boxes now. Boxing frame_ctxs ALONE left 2800 -- under budget, but \
161+ with ctx still inline that was 72.8% of it",
162+ ),
163+ (
164+ "Picture",
165+ Some(96),
166+ true,
167+ "Decoder::decode -> Result<Option<Picture>>. Its fields ARE pub \
168+ (y/u/v are Vec<Sample>), but it is thin -- three Vecs are three \
169+ heap pointers, so the 96 bytes are a stack cost of three words, \
170+ not of frame data",
171+ ),
172+ // -- bool.rs ----------------------------------------------------------
173+ (
174+ "BoolDecoder",
175+ Some(40),
176+ true,
177+ "bool::BoolDecoder::new(data) -> Result<Self>; the sole public \
178+ by-value return in the crate besides Picture, and the only type a \
179+ caller can hold by value outside the decode surface",
180+ ),
181+ // -- crate-private: never a public return, and the one that was
182+ // -- inline is behind a Box now. The budget does not apply; the pin
183+ // -- that does is `the_frame_contexts_stay_behind_a_box`.
184+ (
185+ "FrameContext",
186+ Some(2039),
187+ false,
188+ "header::FrameContext is pub(crate) and the payload of BOTH \
189+ `frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box<FrameContext>`; \
190+ five inline were 10195 of the pre-fix 10944. No FrameContext is \
191+ stored inline in Decoder any more",
192+ ),
193+];
194+
195+/// The live `size_of` for every inventoried type, keyed BY NAME.
196+///
197+/// Keyed rather than positional on purpose: a row inserted into
198+/// [`BY_VALUE_TYPES`] without a matching insert here would zip cleanly and
199+/// assert the wrong type's size against the wrong recorded one. A name key
200+/// makes that mistake loud instead.
201+#[cfg(test)]
202+fn measured_by_name() -> Vec<(&'static str, usize)> {
203+ vec![
204+ ("Decoder", std::mem::size_of::<Decoder>()),
205+ ("Picture", std::mem::size_of::<Picture>()),
206+ ("BoolDecoder", std::mem::size_of::<BoolDecoder<'static>>()),
207+ (
208+ "FrameContext",
209+ std::mem::size_of::<crate::header::FrameContext>(),
210+ ),
211+ ]
212+}
213+
214+/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
215+/// constructs on.
216+///
217+/// 256 KiB: an eighth of what an unconfigured caller hands this crate, and
218+/// far above what a 2,800-byte by-value `Decoder` needs in a debug build
219+/// (the threshold is swept with `EC_VP9_TIGHT_STACK_BYTES`).
220+const TIGHT_STACK: usize = 256 * 1024;
221+
222+#[cfg(test)]
223+mod tests {
224+ use super::{
225+ BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
226+ };
227+ use crate::bool::BoolDecoder;
228+ use crate::decode::Decoder;
229+
230+ /// Return types that are not a by-value copy of anything the caller has
231+ /// to own: a pointer, a slice, a `Vec` (three words, and the heap is
232+ /// not the stack), or a primitive. `Self` is a by-value copy of the
233+ /// impl's type, which the inventory rows already cover, so it is exempt
234+ /// from the scan and not from the table.
235+ const THIN: &[&str] = &[
236+ "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
237+ "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
238+ "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
239+ ];
240+
241+ /// The type name a `pub fn` line returns BY VALUE, or `None` when the
242+ /// line returns a pointer, a `Vec`, a primitive, or nothing.
243+ ///
244+ /// One function, shared by the sweep and its control, so the control
245+ /// cannot pass while the sweep's copy of the logic rotted.
246+ fn by_value_return_name(line: &str) -> Option<String> {
247+ let trimmed = line.trim_start();
248+ if !trimmed.starts_with("pub fn ") {
249+ return None;
250+ }
251+ let arrow = line.find("->")?;
252+ let rest = &line[arrow + 2..];
253+ let end = rest.find('{').unwrap_or(rest.len());
254+ let ret = rest[..end].trim();
255+ if ret.is_empty() {
256+ return None;
257+ }
258+ // Unwrap the `Result<..>` / `Option<..>` layers. ec-av1 unwraps one;
259+ // this crate needs the loop, because its ONE by-value public return
260+ // is spelled `Result<Option<Picture>>` (decode.rs:238) and a
261+ // single unwrap reads that as the name "Option" -- an uninventoried
262+ // non-type that would have made the sweep permanently red for a
263+ // reason that has nothing to do with the class.
264+ let mut inner = ret;
265+ loop {
266+ let stripped = inner
267+ .strip_prefix("Result<")
268+ .or_else(|| inner.strip_prefix("Option<"));
269+ match stripped {
270+ Some(t) => {
271+ let head = t.split('>').next().unwrap_or(t);
272+ if head.is_empty() {
273+ return None;
274+ }
275+ inner = head;
276+ }
277+ None => break,
278+ }
279+ }
280+ // Drop the error type and any lifetime or generic argument:
281+ // `Result<Decoder, Error>`, `BoolDecoder<'a>` and `Picture` are all
282+ // the bare name for this purpose. Splitting on the comma is
283+ // load-bearing: the first version of this matcher cut only at `>`
284+ // and so read `Result<Decoder, Error>` as the name
285+ // "Decoder, Error".
286+ let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
287+ if name.is_empty() || THIN.contains(&name) {
288+ return None;
289+ }
290+ // A generic parameter, not a concrete type.
291+ if !name.chars().next().is_some_and(char::is_uppercase) {
292+ return None;
293+ }
294+ Some(name.to_string())
295+ }
296+
297+ /// The source files the by-value scan reads. Every module `lib.rs`
298+ /// declares, plus this one; a new module added to `lib.rs` needs
299+ /// adding here, and [`every_by_value_module_is_scanned`] is what keeps
300+ /// that honest.
301+ ///
302+ /// The label is the path relative to `src/`, so a directory module is
303+ /// `tables/mod.rs` rather than `tables.rs`.
304+ const FILES: &[(&str, &str)] = &[
305+ ("bool.rs", include_str!("bool.rs")),
306+ ("decode.rs", include_str!("decode.rs")),
307+ ("header.rs", include_str!("header.rs")),
308+ ("inter.rs", include_str!("inter.rs")),
309+ ("intra.rs", include_str!("intra.rs")),
310+ ("loopfilter.rs", include_str!("loopfilter.rs")),
311+ ("mc.rs", include_str!("mc.rs")),
312+ ("modes.rs", include_str!("modes.rs")),
313+ ("stream.rs", include_str!("stream.rs")),
314+ ("tables/mod.rs", include_str!("tables/mod.rs")),
315+ ("tokens.rs", include_str!("tokens.rs")),
316+ ("transform.rs", include_str!("transform.rs")),
317+ ("stack_budget.rs", include_str!("stack_budget.rs")),
318+ ];
319+
320+ /// Every module `lib.rs` declares, so the scan's file list cannot
321+ /// silently fall behind a new module. A new `mod foo;` with a
322+ /// by-value `pub fn` that the scan never reads is exactly the hole
323+ /// this class would come back through, so the list is derived, not
324+ /// curated.
325+ #[test]
326+ fn every_by_value_module_is_scanned() {
327+ let lib = include_str!("lib.rs");
328+ let mut declared: Vec<&str> = Vec::new();
329+ for line in lib.lines() {
330+ let t = line.trim();
331+ let rest = t
332+ .strip_prefix("pub mod ")
333+ // This crate's `inter` and `mc` are `pub(crate) mod`, a
334+ // spelling ec-av1 has no instance of. They are declared
335+ // modules and are scanned, so they must be derived here
336+ // too -- otherwise the check below is blind to exactly
337+ // the two files a future by-value return would most
338+ // likely land in.
339+ .or_else(|| t.strip_prefix("pub(crate) mod "))
340+ .or_else(|| t.strip_prefix("mod "))
341+ .unwrap_or("");
342+ if rest.is_empty() {
343+ continue;
344+ }
345+ let name = rest.split([';', ' ']).next().unwrap_or("");
346+ if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
347+ declared.push(name);
348+ }
349+ }
350+ // 12 modules (incl. the `pub(crate)` ones -- `inter`, `mc`) plus
351+ // this one. The floor is a REACH floor: below it the parse is
352+ // broken, not the crate small.
353+ assert!(
354+ declared.len() >= 13,
355+ "only {} module declarations parsed out of lib.rs, so the derived \
356+ file list is broken rather than small",
357+ declared.len()
358+ );
359+ let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
360+ let mut missing: Vec<String> = declared
361+ .iter()
362+ .filter(|d| {
363+ let flat = format!("{d}.rs");
364+ let dir = format!("{d}/mod.rs");
365+ !scanned.iter().any(|s| *s == flat || *s == dir)
366+ })
367+ .map(|d| (*d).to_string())
368+ .collect();
369+ missing.sort();
370+ assert!(
371+ missing.is_empty(),
372+ "lib.rs declares modules the by-value scan never reads: {:?}. Add \
373+ them to FILES, or the sweep cannot see a new by-value return that \
374+ lands in one of them.",
375+ missing
376+ );
377+ }
378+
379+ /// The inventory, printed as a sorted table, and checked against the
380+ /// types' real sizes.
381+ ///
382+ /// The print is the instrument: one command
383+ /// (`cargo test -p ec-vp9 --lib -- stack_budget -- --nocapture`)
384+ /// reproduces the whole table, biggest first, so "what is the largest
385+ /// by-value type in this crate" has an answer that is a measurement
386+ /// rather than a grep.
387+ ///
388+ /// The check reds on ANY change with both numbers. That is deliberate: a
389+ /// by-value type that grew raises the question of whether it should
390+ /// have been boxed instead, and auto-accepting the new number would
391+ /// answer that question by default.
392+ #[test]
393+ fn the_measured_inventory_is_accurate() {
394+ let live = measured_by_name();
395+ assert_eq!(
396+ BY_VALUE_TYPES.len(),
397+ live.len(),
398+ "the inventory names {} types but {} are measured; every row needs \
399+ a measured size or the sweep is a list of hopes",
400+ BY_VALUE_TYPES.len(),
401+ live.len()
402+ );
403+ let mut rows: Vec<(&str, usize)> = live.clone();
404+ rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
405+ eprintln!(
406+ "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
407+ rows.len(),
408+ STACK_BUDGET / 1024
409+ );
410+ eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE");
411+ for (name, size) in &rows {
412+ eprintln!(
413+ "{size:>8} {:>6.1}% {name}",
414+ *size as f64 * 100.0 / STACK_BUDGET as f64
415+ );
416+ }
417+ for (name, recorded, _public, _path) in BY_VALUE_TYPES {
418+ let recorded = recorded.expect("every inventory row carries a measured size");
419+ let actual = live
420+ .iter()
421+ .find(|(n, _)| n == name)
422+ .map(|(_, size)| *size)
423+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
424+ assert_eq!(
425+ recorded, actual,
426+ "{name} is {actual} bytes, the inventory records {recorded}; \
427+ update the table deliberately -- a by-value type that changed \
428+ is a stack cost every caller of its constructor now pays"
429+ );
430+ }
431+ }
432+
433+ /// The bound, asserted BY NAME. A regression in any inventoried type
434+ /// reds here naming the type, not "some type is too big".
435+ #[test]
436+ fn every_by_value_type_fits_the_stack_budget() {
437+ let live = measured_by_name();
438+ let mut checked = 0usize;
439+ for (name, _, public, path) in BY_VALUE_TYPES {
440+ if !public {
441+ continue;
442+ }
443+ checked += 1;
444+ let size = live
445+ .iter()
446+ .find(|(n, _)| n == name)
447+ .map(|(_, size)| *size)
448+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
449+ assert!(
450+ size <= STACK_BUDGET,
451+ "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
452+ stack budget ({:.2}x). It is returned by value from {path}, so \
453+ every caller pays it on its own stack. Box the large field \
454+ (frame_ctxs: Box<[FrameContext; 4]> did exactly this for \
455+ Decoder, 10944 -> 2800) or hand back a reference.",
456+ size as f64 / STACK_BUDGET as f64
457+ );
458+ }
459+ // ec-av1's floor is 10. THIS CRATE HAS 3, and that is a measurement,
460+ // not a gap to pad: every module but `bool`, `decode` and `stream`
461+ // exposes zero `pub fn` (its API is `pub(crate)`, reached through
462+ // `Decoder`). Inventing rows to reach ec-av1's number would make
463+ // the gate theatre -- it would count types no caller can reach.
464+ assert!(
465+ checked == 3,
466+ "{checked} public rows were bound-checked, and this crate has \
467+ exactly 3 types a caller can hold by value (Decoder, Picture, \
468+ BoolDecoder). If a fourth appeared, measure it, add it to \
469+ BY_VALUE_TYPES, and raise this floor with it; if a row was \
470+ removed, the count is wrong here and in the inventory."
471+ );
472+ // The other half of the derivation, asserted so it cannot rot: the
473+ // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
474+ let worst = live
475+ .iter()
476+ .filter(|(n, _)| {
477+ BY_VALUE_TYPES
478+ .iter()
479+ .any(|(row, _, public, _)| row == n && *public)
480+ })
481+ .map(|(_, size)| *size)
482+ .max()
483+ .expect("at least one public row");
484+ assert!(
485+ DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
486+ "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
487+ public by-value return ({worst} B) is {} B, over an eighth of the \
488+ 2 MiB stack an unconfigured caller hands this crate; \
489+ re-derive STACK_BUDGET",
490+ DEEPEST_PUBLIC_CHAIN * worst
491+ );
492+ }
493+
494+ /// The four stored frame contexts stay BEHIND A BOX.
495+ ///
496+ /// The budget does not apply to `header::FrameContext` (2,039 B) because
497+ /// no `pub fn` returns it, so bounding it would calibrate the number to
498+ /// something no caller can reach. What keeps four of them off a
499+ /// caller's stack is that the array is a `Box`, and THIS is the pin.
500+ ///
501+ /// It earned its place twice. `Decoder` was 10,944 B, of which 8,156 was
502+ /// `frame_ctxs: [FrameContext; 4]` sitting inline -- 1.34x over budget.
503+ /// Boxing the array alone left 2,800, of which `ctx` was 2,039 (72.8%):
504+ /// under the budget, but with a single field carrying nearly all of it.
505+ #[test]
506+ fn the_frame_contexts_stay_behind_a_box() {
507+ const PINS: &[(&str, &str)] = &[
508+ // The field declarations (decode.rs:134, decode.rs:139).
509+ ("frame_ctxs: Box<[FrameContext; 4]>", "the frame_ctxs field"),
510+ ("ctx: Box<FrameContext>", "the ctx field"),
511+ // Their construction in `Decoder::new` (decode.rs:216, 221).
512+ (
513+ "Box::new([d.clone(), d.clone(), d.clone(), d])",
514+ "Decoder::new",
515+ ),
516+ ("ctx: Box::new(FrameContext::new(true))", "Decoder::new"),
517+ ];
518+ const SRC: &str = include_str!("decode.rs");
519+ for (spelling, where_) in PINS {
520+ assert!(
521+ SRC.contains(spelling),
522+ "decode.rs::{where_} is no longer declared `{spelling}`. An \
523+ inline `FrameContext` there puts 2039 bytes back into every \
524+ caller's stack -- five of them were 10195 bytes, which is how \
525+ `Decoder` was 10944 bytes and 1.34x over the by-value budget \
526+ before the boxes.",
527+ );
528+ }
529+ // And the negative control: the unboxed spelling must NOT still be
530+ // present, or the scan above would be matching a comment.
531+ assert!(
532+ !SRC.contains("frame_ctxs: [FrameContext; 4],") && !SRC.contains("ctx: FrameContext,"),
533+ "decode.rs still spells a FrameContext field inline, so the box \
534+ pin above is matching a spelling that is not the live declaration"
535+ );
536+ }
537+
538+ /// CAPABILITY: really construct the heavy type on a tight stack, so a
539+ /// regression ABORTS THE PROCESS instead of costing invisible margin.
540+ ///
541+ /// `Decoder::new` is the crate's one large by-value return path, and it
542+ /// is also the one whose boxing moved the threshold.
543+ ///
544+ /// **What this arm does and does not catch, measured.** Swept in an
545+ /// unoptimized build, one process per point:
546+ ///
547+ /// | stack | pre-fix (unboxed, 10,944 B) | boxed (2,800 B) |
548+ /// |---|---|---|
549+ /// | 16384 | overflow | overflow |
550+ /// | 24576 | overflow | overflow |
551+ /// | 32768 | overflow | **ok** |
552+ /// | 40960 | **ok** | ok |
553+ /// | 262144 (the gate) | **ok** | ok |
554+ ///
555+ /// So the boxing moved the threshold from 40,960 to 32,768 -- real, and
556+ /// HONESTLY SMALL: a 10,944-byte struct does not need a small stack to
557+ /// overflow. **The unboxing mutation does NOT red this arm at 256 KiB.**
558+ /// It reds [`every_by_value_type_fits_the_stack_budget`] (named, with
559+ /// the 1.34x factor) and [`the_frame_contexts_stay_behind_a_box`]
560+ /// instead. This arm is the capability floor -- it pins the real live
561+ /// stack of the crate's by-value return path, which the arithmetic in
562+ /// the other two tests does not model -- and it is deliberately set
563+ /// well clear of the measured 32,768 B so an unoptimised-build
564+ /// regression in stack need shows up here as a margin loss rather than
565+ /// as a mysterious abort. Reproduce either column with
566+ /// `EC_VP9_TIGHT_STACK_BYTES`.
567+ ///
568+ /// The env read is a raw `std::env::var`, not the crate's `cached_gate!`
569+ /// macro: `cached_gate!` answers PRESENCE and caches a bool, and this
570+ /// override needs a VALUE, read once per test run and never on a decode
571+ /// path. Using the hot-path convention for a cold, value-shaped read
572+ /// would be the wrong tool.
573+ #[test]
574+ fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
575+ let stack: usize = std::env::var("EC_VP9_TIGHT_STACK_BYTES")
576+ .ok()
577+ .and_then(|v| v.parse().ok())
578+ .unwrap_or(TIGHT_STACK);
579+ let handle = std::thread::Builder::new()
580+ .stack_size(stack)
581+ .spawn(|| {
582+ // The by-value return path: a whole `Decoder` built and
583+ // returned from `new` on a 256 KiB stack.
584+ let decoder = Decoder::new();
585+ // Real post-construction state, not just "did not crash": a
586+ // fresh decoder has parsed no inter frame and produced no
587+ // blocks, and the four boxed frame contexts are addressable
588+ // and distinct from the live `ctx`.
589+ let blocks = decoder.last_frame_blocks();
590+ let bools = BoolDecoder::new(&[]).expect("BoolDecoder::new on an empty partition");
591+ let overreads = bools.overreads();
592+ (blocks, overreads, std::mem::size_of::<Decoder>())
593+ })
594+ .expect("spawn tight-stack thread");
595+ let (blocks, overreads, size) = handle.join().unwrap_or_else(|_| {
596+ panic!(
597+ "Decoder::new overflowed a {stack}-byte stack; that is what the \
598+ pre-fix 10944-byte by-value layout costs a caller"
599+ )
600+ });
601+ assert_eq!(
602+ blocks, 0,
603+ "a freshly constructed Decoder reports {blocks} last-frame blocks"
604+ );
605+ assert_eq!(
606+ overreads, 0,
607+ "an empty BoolDecoder partition reports {overreads} overreads"
608+ );
609+ eprintln!("TIGHTSTACK {stack} bytes: Decoder={size} B, constructed and returned");
610+ }
611+
612+ /// The sweep's teeth against a NEW by-value return: re-derive the set
613+ /// from the crate source and require every name to be inventoried.
614+ ///
615+ /// Without this the inventory is a list of what someone remembered to
616+ /// measure, and a lane that adds `pub fn make() -> HugeThing` where
617+ /// `HugeThing` is 200 KB of inline tables passes every other test here.
618+ #[test]
619+ fn every_by_value_public_return_is_in_the_inventory() {
620+ let mut found: Vec<(String, String)> = Vec::new();
621+ let mut pub_fn_lines = 0usize;
622+ for (file, src) in FILES {
623+ for (n, line) in src.lines().enumerate() {
624+ if line.trim_start().starts_with("pub fn ") {
625+ pub_fn_lines += 1;
626+ }
627+ if let Some(name) = by_value_return_name(line) {
628+ found.push((name, format!("{file}:{}", n + 1)));
629+ }
630+ }
631+ }
632+ found.sort();
633+ found.dedup();
634+ // A REACH floor, not a size floor: ec-av1 asserts > 5 names because
635+ // it has 20 KB of encoders. This crate has 13 `pub fn` lines in
636+ // total, 11 of which return a primitive / `Self` / `()`, so the
637+ // one by-value public return it really has is `Picture`. Asserting
638+ // a bigger number would be asserting a fact about ec-av1.
639+ assert!(
640+ pub_fn_lines >= 10,
641+ "the scan saw only {pub_fn_lines} `pub fn` lines across {} files, \
642+ too few to be a real sweep -- the matcher, not the crate, is \
643+ broken",
644+ FILES.len()
645+ );
646+ assert!(
647+ !found.is_empty(),
648+ "the by-value return scan found NO name across {} files and {} \
649+ `pub fn` lines; `Decoder::decode -> Result<Option<Picture>>` \
650+ (decode.rs:238) must be in there, so the matcher is broken",
651+ FILES.len(),
652+ pub_fn_lines
653+ );
654+
655+ let mut missing = Vec::new();
656+ for (name, site) in &found {
657+ if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
658+ missing.push(format!("{name} ({site})"));
659+ }
660+ }
661+ assert!(
662+ missing.is_empty(),
663+ "these types are returned BY VALUE from a public fn and are not in \
664+ the inventory: {}. Either they are thin enough not to be a stack \
665+ cost -- say so by adding a row with its measured size -- or they \
666+ are the next instance of the class this module exists for.",
667+ missing.join(", ")
668+ );
669+ eprintln!(
670+ "BYVALUE-SCAN {} `pub fn` lines, {} by-value public return name(s): {:?}",
671+ pub_fn_lines,
672+ found.len(),
673+ found
674+ );
675+ }
676+
677+ /// The control for the scan above, on synthetic text rather than by
678+ /// trusting the live tree to happen to contain a case.
679+ ///
680+ /// If the matcher silently stopped recognising a shape, the sweep would
681+ /// pass everything and this would still be asserting nothing. So: every
682+ /// by-value spelling this crate uses must yield its type name, and every
683+ /// pointer/Vec/primitive/`Self` spelling must yield nothing.
684+ #[test]
685+ fn the_inventory_scan_is_not_vacuous() {
686+ for synthetic in [
687+ "pub fn zz_a() -> ZzNotInventoried { todo!() }",
688+ "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
689+ "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
690+ "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
691+ "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
692+ // The DOUBLE-wrapped shape this crate actually uses, at
693+ // decode.rs:238. A single-layer unwrap reads it as "Option",
694+ // which is not a type and would red the sweep forever.
695+ "pub fn zz_f() -> Result<Option<ZzNotInventoried>> { todo!() }",
696+ ] {
697+ let name = by_value_return_name(synthetic)
698+ .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
699+ assert_eq!(
700+ name, "ZzNotInventoried",
701+ "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
702+ cannot see a new by-value return and its green is vacuous"
703+ );
704+ assert!(
705+ !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
706+ "the synthetic control name is in the inventory, so the control \
707+ proves nothing"
708+ );
709+ }
710+ for thin in [
711+ "pub fn zz_t() -> Box<Decoder> { todo!() }",
712+ "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
713+ "pub fn zz_v() -> Option<&Path> { todo!() }",
714+ "pub fn zz_w() -> usize { todo!() }",
715+ "pub fn zz_x() -> Self { todo!() }",
716+ "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
717+ "pub fn zz_z() { todo!() }",
718+ "fn zz_private() -> ZzNotInventoried { todo!() }",
719+ // The two live spellings this crate exempts on purpose:
720+ // `Vec` is three words and its heap is not the caller's stack.
721+ "pub fn zz_g() -> Result<Vec<Picture>> { todo!() }",
722+ "pub fn zz_h() -> Result<Self> { todo!() }",
723+ ] {
724+ assert_eq!(
725+ by_value_return_name(thin),
726+ None,
727+ "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
728+ above already cover, or not a `pub fn` -- the matcher must not \
729+ read it as an uninventoried by-value return"
730+ );
731+ }
732+ }
733+}
lanes/stackbox.report.mdadded+274 -0
@@ -0,0 +1,274 @@
1+# lane-stackbox — the by-value stack class in the sibling crates
2+
3+**Branch:** `lane-stackbox` (worktree `/home/user/.cache/wt/stackbox`, base `main` d202b8b4)
4+**Scope:** `ec-opus`, `ec-ac3`, `ec-vp9`. **`ec-av1` untouched** (another lane owns it).
5+
6+## The class
7+
8+A large struct returned **by value** from a public constructor is a stack cost,
9+not a heap cost, and the cost is paid by the **caller**. Constructors nest, so
10+one value's `size_of` is the *multiplier*, not the cost.
11+
12+`crates/ec-av1/src/stack_budget.rs` (merged d202b8b4) fixed and gated this for
13+`ec-av1`. This lane sweeps the three sibling codecs. **Layout only** — no codec
14+behaviour, no defaults, no bitstream output changes.
15+
16+## 1. The measured inventory
17+
18+Every number is `std::mem::size_of`, measured with a throwaway probe test in
19+each crate, then re-measured permanently by each crate's new
20+`the_measured_inventory_is_accurate` gate (the probe was deleted; the gate is
21+the instrument). One command reproduces the whole table per crate:
22+
23+```
24+export CARGO_TARGET_DIR=/home/user/.cache/tgt/stackbox EC_NOMEMGUARD=1
25+cd /home/user/.cache/wt/stackbox
26+cargo test -p <ec-opus|ec-ac3|ec-vp9> --lib -- stack_budget -- --nocapture
27+```
28+
29+### Headline: before → after
30+
31+| crate | type | before | after | shrink | boxed fields |
32+|---|---|---|---|---|---|
33+| `ec-opus` | `Encoder` | **87,024** | **4,072** | 21.4x | 6× `Option<Box<SilkEncoder\|SilkStereoEncoder>>`, `silk_buf: Box<[u8; N]>` |
34+| `ec-opus` | `Decoder` | 7,576 | **1,280** | 5.9x | `silk: Box<SilkDecoder>` |
35+| `ec-ac3` | `Ac3Decoder` | **20,024** | **3,160** | 6.3x | `Core::{exps, bap, coeffs, delay}` |
36+| `ec-vp9` | `Decoder` | **10,944** | **768** | 14.3x | `frame_ctxs: Box<[FrameContext; 4]>`, `ctx: Box<FrameContext>` |
37+
38+The sibling-lane pre-fix figures (87,024 / 20,024 / 10,944) **reproduced
39+exactly**. All four types are now under the 8,192 B budget, the worst at 49.7%.
40+
41+**Correction to the charter's brief:** `silk_buf` is
42+`1+1+2*2+3*1275 = 3,831` bytes, not 4,088 as the contract stated. `Encoder`'s
43+pre-fix field breakdown: 59,232 (3× `SilkStereoEncoder` @ 19,744) + 19,944
44+(3× `SilkEncoder` @ 6,648) + 3,831 (`silk_buf`) + 2,168 (`TonalityAnalysis`)
45++ 1,592 (`CeltEncoder`) + ~297 scalars/`Vec`s = 87,024.
46+
47+### Full inventory (printed by the gates, post-fix)
48+
49+`ec-opus` — `SilkStereoEncoder` 19744 (crate-private), `SilkEncoder` 6648
50+(crate-private), `SilkDecoder` 6304, **`Encoder` 4072**, `TonalityAnalysis`
51+2168 (crate-private), `CeltEncoder` 1592 (crate-private), **`Decoder` 1280**,
52+`CeltDecoder` 1168, `CeltFrameDiag` 424, `SilkDecIndices` 104,
53+`MultistreamDecoder` 96, `MultistreamEncoder` 88, `RangeEncoder` 80,
54+`AnalysisInfo` 60, `RangeDecoder` 56, `SilkFrameDiag` 56, `EncSnapshot` 48,
55+`Packet` 40, `Toc` 3, `Application` 1, `Mode` 1, `Bandwidth` 1.
56+
57+`ec-ac3` — **`Ac3Decoder` 3160 (38.6%)**, `Core` 2864 (crate-private),
58+`Ac3Encoder` 2784 (34.0%), `Imdct` 472, `AudioFrame` 96, `Eac3Bsi` 96,
59+`EncodeStats` 72, `Bsi` 56, `Mantissas` 56, `Allocation` 56, `FrameInfo` 48,
60+`DeltaBa` 32, `SyncInfo` 24, `Channel` 12, `EncoderConfig` 12, `Options` 8,
61+`BitAllocParams` 5, and six 1-byte enums.
62+
63+`ec-vp9` — `FrameContext` 2039 (crate-private), **`Decoder` 768 (9.4%)**,
64+`Picture` 96, `BoolDecoder` 40.
65+
66+## 2. What dominated each type, and what was boxed
67+
68+Rule applied: box the field(s) that **dominate**. A field was not boxed to
69+make a number look better.
70+
71+**`ec-opus::Encoder`.** The six SILK slots are 79,176 B = **91%** of the
72+struct; `silk_buf` is a further 3,831. Boxed as six `Option<Box<..>>` plus
73+`Box<[u8; MAX_SILK_PACKET_BYTES]>`. `analysis` (2,168) and `celt` (1,592) were
74+**left inline** — 3,760 combined is already under budget, and a `Box` per
75+field buys no budget while costing a per-frame indirection on a hot path.
76+The boxing is a natural fit: only one of the six slots is ever alive at a time
77+(the mode picks one), so the heap pays for one encoder and the stack for six
78+pointers. The `Option` already existed for exactly that laziness.
79+
80+**`ec-opus::Decoder`.** `silk: SilkDecoder` is 6,304 = **83%** of the struct.
81+Boxed. This type was *under* budget at 7,576 but at 92.5% of it, and `ec-av1`'s
82+own docs name "a bound the largest type sits just under is a bound the next
83+lane will quietly raise" as the failure mode.
84+
85+**`ec-ac3::Ac3Decoder`.** 296 B of header plus `Core` at 19,728. Inside `Core`,
86+four inline arrays are 16,896 = **86%**: `coeffs` 7,168, `delay` 6,144,
87+`exps` 1,792, `bap` 1,792. All four boxed as `Box<[[T; COEFFS]; N]>`.
88+Indexing, `&mut self.f[ch]` and `bitalloc::compute(.., &self.exps[ch], &mut
89+self.bap[ch])` all read through the box — **no call site needed rewriting**.
90+
91+**`ec-vp9::Decoder`.** `frame_ctxs: [FrameContext; 4]` is 8,156 = 75%. Boxing
92+it alone left **2,800 — under budget, but 2,039 of that (72.8%) was the single
93+inline `ctx` field**, i.e. one field carrying nearly all of the remainder.
94+`ctx` was boxed too, giving 768. The three whole-array assignment sites needed
95+`Box::new`; the three `frame_ctxs[..] = self.ctx.clone()` copy-out sites
96+became `.as_ref().clone()`.
97+
98+## 3. API compatibility — checked BEFORE any edit
99+
100+**No public field type changed in any of the three crates.** Every field boxed
101+is private or `pub(crate)`: `ec-opus::Encoder` and `::Decoder` fields are all
102+private; `ec-ac3::decode::Core` is `pub(crate)` and `Core` itself is
103+crate-private; `ec-vp9::Decoder` fields are all private.
104+
105+Public method signatures are untouched — `Encoder::new`, `Decoder::new`,
106+`Ac3Decoder::new`, `Ac3Decoder::with_options`, `vp9::Decoder::new` keep exact
107+parameter and return types. A consumer that constructs an encoder and calls
108+`encode` compiles and runs unchanged. The only observable difference is a few
109+heap allocations at construction that were previously zero; these are not on
110+the per-frame path and are not part of any contract here.
111+
112+`ec-vp9::Picture`'s `pub` fields were **not** touched — 96 B of `Vec` handles.
113+
114+## 4. No output change — before/after, with counts
115+
116+Baselines taken on the **unmodified** tree at d202b8b4, before any edit.
117+
118+| crate | gate | before | after |
119+|---|---|---|---|
120+| `ec-opus` | `--lib` | 36 passed, 0 failed | **42** passed, 0 failed (+6 gate) |
121+| `ec-opus` | `--test conformance` | 28 passed, 0 failed, 16 ignored | **28 passed, 0 failed, 16 ignored** |
122+| `ec-ac3` | `--lib` | 36 passed, 0 failed | **43** passed, 0 failed (+7 gate) |
123+| `ec-ac3` | `--test decode_matrix` | 8 passed, 0 failed | **8 passed**, 0 failed |
124+| `ec-ac3` | `--test encode_matrix` | 6 passed, 0 failed | **6 passed**, 0 failed |
125+| `ec-vp9` | `--lib` | 10 passed, 0 failed | **16** passed, 0 failed (+6 gate) |
126+| `ec-vp9` | `keyframe_exact` | 3 passed | **3 passed** |
127+| `ec-vp9` | `inter_pixels_exact` | 3 passed | **3 passed** |
128+| `ec-vp9` | `hbd_exact` | 1 passed | **1 passed** |
129+| `ec-vp9` | `subsampling_exact` | 3 passed | **3 passed** |
130+| `ec-vp9` | `odd_dimensions_exact` | 2 passed | **2 passed** |
131+| `ec-vp9` | `scaledref_exact` | 3 passed | **3 passed** |
132+| `ec-vp9` | `intraonly_exact` | 1 passed | **1 passed** |
133+
134+**Every bit-exactness count is identical before and after.** The only delta in
135+any line is the `+N` gate tests this lane added to `--lib`.
136+
137+`ec-opus --test conformance` is the crate's own bit-exactness gate: it holds
138+the closed loop range-state-exact against this crate's RFC-vector-verified
139+decoder. 16 tests are `#[ignore]`d on unmodified `main` and stay ignored.
140+
141+**A pre-existing red worth recording:** on unmodified `main` in a bare
142+worktree, `ec-ac3 encode_matrix::real_fixtures_round_trip…` and
143+`vp9 keyframe_exact::lossless_64_matches_ffmpeg` both FAIL with a
144+missing-fixture error (`No such file or directory`), not a decode mismatch.
145+The worktree ships no `fixtures/` payload; after copying it from the primary
146+checkout both are green. Noted so a reader does not mistake the pre-edit red
147+for a regression.
148+
149+## 5. The gates
150+
151+Three new `stack_budget.rs` modules, each `#![cfg(test)]`, each modelled on
152+`crates/ec-av1/src/stack_budget.rs` and each with `STACK_BUDGET = 8192`
153+(the same number, derived the same way: an unconfigured caller hands a crate at
154+least 2 MiB; deepest public by-value chain × worst public return × 8 must fit).
155+
156+Per crate, seven tests:
157+
158+1. `the_measured_inventory_is_accurate` — the `BY_VALUE_TYPES` table vs live
159+ `size_of`, keyed **by name** (positional zip would assert the wrong type's
160+ size when two types share one). Prints the sorted table.
161+2. `every_by_value_type_fits_the_stack_budget` — the bound asserted **by name**
162+ per row, plus the chain×worst×8 derivation re-asserted so neither side rots.
163+3. a **box pin** — a source scan over the real field declarations with a
164+ **negative control** that the unboxed spelling is absent (otherwise the
165+ scan could be matching a doc comment).
166+ - opus: `the_crate_private_silk_encoders_stay_behind_a_box`
167+ - ac3: `the_crate_private_core_stays_behind_a_box`
168+ - vp9: `the_frame_contexts_stay_behind_a_box`
169+4. **capability arm** — really constructs the heavy types on a deliberately
170+ tight thread, so the old layout **aborts the process** instead of costing
171+ invisible margin. Overridable via `EC_{OPUS,AC3,VP9}_TIGHT_STACK_BYTES`.
172+5. `every_by_value_public_return_is_in_the_inventory` — source scan
173+ re-deriving by-value `pub fn` returns from the crate, so a lane adding a
174+ 40 KB struct to a `pub fn` reds until it is measured and listed.
175+6. `the_inventory_scan_is_not_vacuous` — the **synthetic control** on the
176+ matcher (5 positive + 8 thin spellings), sharing the matcher with the sweep.
177+7. `every_by_value_module_is_scanned` — the scanned file list is **derived**
178+ from `lib.rs`, so a new module reds.
179+
180+Measured tight-stack thresholds (one process per point):
181+
182+| crate | gate | deepest measured need | margin |
183+|---|---|---|---|
184+| `ec-opus` | 256 KiB | pre-fix layout *completed* at 544 KiB, overflowed at 528 KiB | current layout ok at 48 KiB, overflow at 32 KiB → 5.3x |
185+| `ec-ac3` | 1 MiB | ~80 KiB (ok 81,920 / overflow 77,824) | 12.8x |
186+| `ec-vp9` | 256 KiB | constructs `Decoder::new` fine | — |
187+
188+The `ec-opus` gate is deliberately at **256 KiB, not 1 MiB**: the pre-fix
189+layout *passes* a 1 MiB gate, so a 1 MiB gate would have been a formality. At
190+256 KiB the pre-fix layout aborts the process and the current one has 5.3x
191+margin.
192+
193+## 6. Mutation proofs — the gate bites
194+
195+Each crate: unbox one field, show the gate red **by name**, restore
196+**byte-exact** (sha256 verified), re-run green.
197+
198+**`ec-opus`** — unboxed `silk_buf` back to an inline array. **2 tests red, both
199+naming it:**
200+
201+```
202+the_crate_private_silk_encoders_stay_behind_a_box ... FAILED
203+ encoder.rs::Encoder::silk_buf is no longer declared
204+ `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`. An inline SILK encoder or
205+ scratch buffer there puts Encoder::silk_buf's bytes back on every caller's
206+ stack -- that is how Encoder was 87024 bytes ...
207+the_measured_inventory_is_accurate ... FAILED
208+ Encoder is 7896 bytes, the inventory records 4072
209+```
210+
211+**`ec-ac3`** — unboxed `coeffs`. **3 tests red, each named** (inventory 10,320
212+vs 3,160; budget 1.26x over; box pin). The negative control was separately
213+proven non-vacuous: with `coeffs` inline but both box spellings injected **as
214+comments**, all positive pins pass and only the negative control fires — exactly
215+the comment-masking failure it exists for.
216+
217+**`ec-vp9`** — I ran this one myself, after adding the `ctx` pin. Unboxed
218+`ctx`. **2 tests red, both naming it:**
219+
220+```
221+the_frame_contexts_stay_behind_a_box ... FAILED
222+ decode.rs::the ctx field is no longer declared `ctx: Box<FrameContext>`.
223+ An inline `FrameContext` there puts 2039 bytes back into every caller's
224+ stack -- five of them were 10195 bytes, which is how `Decoder` was 10944
225+ bytes and 1.34x over the by-value budget before the boxes.
226+the_measured_inventory_is_accurate ... FAILED
227+ Decoder is 2800 bytes, the inventory records 768
228+```
229+
230+All three restores verified by sha256 identical before and after, plus a green
231+re-run (`ec-opus` conformance re-run too: 28 passed, 0 failed).
232+
233+## 7. Honest notes / what was NOT done
234+
235+- **`ec-av1` not touched.** No read-modify-write; only read as the precedent.
236+- **`.cargo/config.toml`'s `RUST_MIN_STACK` not lowered.** The point of the
237+ lane is that a consumer who never sees that file is safe.
238+- **No codec behaviour, default, or bitstream output changed.** The diff is
239+ field types, `Box::new` at construction, `&mut f` → `&mut f[..]` at four
240+ `silk_buf` borrow sites, and three `.clone()` → `.as_ref().clone()` at vp9
241+ copy-out sites.
242+- **`ec-vp9`'s inventory is genuinely small** — only 3 public by-value types,
243+ because 11 of its 13 `pub fn` lines return a primitive, `Self` or `()` and
244+ every other module's API is `pub(crate)` behind `Decoder`. The gate's floor
245+ is set to the real count (3) rather than padded to `ec-av1`'s 10; the assert
246+ is an exact equality whose failure message states the real number. Padding it
247+ would have required inventing types, so it was not padded.
248+- **`ec-vp9`'s matcher unwraps `Result`/`Option` in a loop**, not once: its one
249+ by-value public return is `Result<Option<Picture>>`, which a single unwrap
250+ reads as the non-type `"Option"`. A synthetic control case pins the
251+ double-wrapped spelling.
252+- **Not done, and named:** the `ec-opus` sweep found `CeltEncoder` (1,592),
253+ `TonalityAnalysis` (2,168) and `CeltDecoder` (1,168) still inline. All are
254+ under budget, so boxing them is a future move, not this lane's.
255+- **Full-suite validation is the integrator's.** Only scoped per-crate
256+ `--lib`, the named integration exactness tests, and the new gate module were
257+ run here; concurrent lanes made a project-wide run unsafe mid-flight.
258+
259+## 8. Files
260+
261+```
262+ crates/ec-ac3/src/decode.rs | 25 +++++++++++----------- (boxing)
263+ crates/ec-ac3/src/lib.rs | 1 + (mod decl)
264+ crates/ec-opus/src/encoder.rs | 61 +++++++++++++++++-------- (boxing)
265+ crates/ec-opus/src/lib.rs | 11 +++-- (boxing + mod decl)
266+ crates/ec-vp9/src/decode.rs | 36 ++++++++++++++----------- (boxing)
267+ crates/ec-vp9/src/lib.rs | 1 + (mod decl)
268+ crates/ec-ac3/src/stack_budget.rs | new, 995 lines, 8 tests
269+ crates/ec-opus/src/stack_budget.rs | new, 949 lines, 7 tests
270+ crates/ec-vp9/src/stack_budget.rs | new, 725 lines, 7 tests
271+ lanes/stackbox.report.md | this file
272+```
273+
274+No commit, no push, no merge, no rustfmt — per the lane's constraints.