forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-rc' (4c2ff222): the rate loop prices a run by the frames the pyramid really codes with a measured per-level weight, and re-plans the remaining budget each frame; bitrate gate tightened to 5%

Browse files at this commit

7eb3134e1b9dbe6c82afa62e111ac35ed5196ccdAhmet Kaan GümüşParent: eabe538b1137ab
crates/ec-av1/src/encoder.rsmodified+292 -60
@@ -159,14 +159,27 @@ fn quality_to_q_idx(quality: u8) -> u8 {
159 (240.0 - quality * 2.0).round() as u8159 (240.0 - quality * 2.0).round() as u8
160 }160 }
161 161
162-/// How much of a mini-GOP's byte budget the hidden `ALTREF` frame is worth162+/// What one coded frame is worth, relative to a leaf, as a function of how
163-/// relative to one leaf: every leaf of the group predicts off it, so it is163+/// much FINER than the leaf it is coded (`leaf_q_offset - own offset`, in
164-/// bought at roughly twice a leaf's size (libaom's `gf_group` spends its164+/// `q_idx` steps): `exp(WEIGHT_LEVEL_GAIN * delta)`.
165-/// `ARF` the same way, through a lower quantizer rather than a byte target).165+///
166-const ARF_WEIGHT: f64 = 2.0;166+/// This is the level model the byte budget is split by, and it is MEASURED,
167-167+/// not the old flat "a hidden frame is worth two leaves" guess: the long-GOP
168-/// How much a key frame is worth relative to one leaf, same units.168+/// census (`lanes/rc.report.md`, films A and B at three quantizers each,
169-const KEY_WEIGHT: f64 = 3.0;169+/// `lanes/census-longgop-v2.md`'s q150 row among them) reads a level's
170+/// bytes/frame as very close to log-linear in its own q offset, at
171+/// d(ln bytes)/d(q_idx) = -0.0557 -- three and a half times the SLOPE of the
172+/// controller's own `RateLoop::GAIN` (0.0154), because a deeper level is not
173+/// just quantized finer, it also carries the group's residual for every
174+/// frame that predicts off it.
175+const WEIGHT_LEVEL_GAIN: f64 = 0.0557;
176+
177+/// The key frame's own correction on top of `WEIGHT_LEVEL_GAIN`: an intra
178+/// frame at the key's offset codes this much of what the level model alone
179+/// predicts (the census's key frames are consistently smaller than the pure
180+/// exponential, since the exponential is fitted on INTER levels whose size
181+/// keeps growing with reference depth).
182+const KEY_WEIGHT: f64 = 1.08;
170 183
171 /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and184 /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
172 /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from185 /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
@@ -196,6 +209,20 @@ struct RateLoop {
196 /// FIRST update of a slot is the seeding one and takes the model's whole209 /// FIRST update of a slot is the seeding one and takes the model's whole
197 /// step ([`RateLoop::update`]); every later one is clamped.210 /// step ([`RateLoop::update`]); every later one is clamped.
198 seeded: [bool; 3],211 seeded: [bool; 3],
212+ /// The leaf's own q offset: the zero of the level weight
213+ /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in
214+ /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset.
215+ leaf_q_offset: i16,
216+ /// The key frame's own leaf-equivalent weight ([`KEY_WEIGHT`]).
217+ key_weight: f64,
218+ /// The leaf-equivalent weight of a whole run (key included), and the
219+ /// run's whole byte budget (`gop` frame targets): what a run RE-PLANS
220+ /// from, and what a key frame resets the re-plan to.
221+ run_weight: f64,
222+ run_bytes: f64,
223+ /// What is left of both, ahead of the next frame.
224+ left_weight: f64,
225+ left_bytes: f64,
199 }226 }
200 227
201 impl RateLoop {228 impl RateLoop {
@@ -215,48 +242,62 @@ impl RateLoop {
215 q: [start_q; 3],242 q: [start_q; 3],
216 per_level: false,243 per_level: false,
217 seeded: [false; 3],244 seeded: [false; 3],
245+ leaf_q_offset: 0,
246+ key_weight: 1.0,
247+ run_weight: 0.0,
248+ run_bytes: 0.0,
249+ left_weight: 0.0,
250+ left_bytes: 0.0,
218 };251 };
219 };252 };
220- let m = p.mini_gop as f64;253+ // THE LEVEL MODEL. Every coded frame of the run is priced by its own
221- // THE KEY FRAME'S SHARE, in frame targets. `KEY_WEIGHT` prices it at254+ // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the
222- // the quantizer the loop steers it to, and255+ // run's `gop` frame targets are shared out in those units. The old
223- // [`Pyramid::key_q_offset`] then codes it that much FINER, which the256+ // model priced a group as "one hidden frame worth `ARF_WEIGHT` = 2
224- // key's own slot cannot steer back: a run holds exactly one key257+ // leaves plus `m - 1` leaves", which was wrong twice over and the two
225- // frame, so the slot never gets a second frame to correct on. The258+ // errors cancelled (lane-pyr6): the group has coded TWO hidden frames
226- // calibration slope (`GAIN`) says what the offset costs in bytes, and259+ // since the mid level landed (four with
227- // the rest of the run pays for it -- without this the deeper key ran260+ // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far
228- // the 48-frame bitrate gate +10.8% over target.261+ // more than two leaves -- the census reads the top ARF at 24x a leaf
229- let key = KEY_WEIGHT * (-f64::from(p.key_q_offset) / Self::GAIN).exp();262+ // and the mid at 5x. Both are fixed here, in one diff.
230- // What is left for the `gop - 1` non-key pictures, per picture: a run263+ let w = |offset: i16| {
231- // of `gop` pictures is worth `gop` frame targets in total.264+ ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
232- let rest = match gop > 1 {
233- true => (target_bytes * (gop as f64 - key) / (gop as f64 - 1.0)).max(0.0),
234- false => target_bytes,
235 };265 };
236- // A group of `m` pictures gets `m * rest`, split one `ARF_WEIGHT`266+ let (hidden, leaves) = gop_shape(p, gop);
237- // share to the hidden frame and one each to the `m - 1` leaves, so267+ let key = KEY_WEIGHT * w(p.key_q_offset);
238- // the group's own average is `rest` exactly.268+ let total: f64 = key
239- //269+ + leaves as f64
240- // ONE hidden frame, deliberately, even though the group has coded two270+ + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
241- // since the mid level landed (and four with271+ // One leaf's byte target: the run is worth `gop` frame targets and
242- // [`Pyramid::quarter_q_offset`] on). Pricing the real count272+ // `total` leaves.
243- // (`m / (m - h + h * ARF_WEIGHT)`, h = 2) is the truthful model and273+ let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON);
244- // it lands the 48-frame bitrate gate -9.4% / -14.9% under target274+ // THE HIDDEN SLOT holds every hidden level at once (`Level::Arf` is
245- // against this line's -1.8% / -6.3%: the h = 1 split over-allocates275+ // the top ARF, the mid and the quarters alike -- one controller,
246- // the group by exactly the amount `ARF_WEIGHT` under-prices a hidden276+ // different q offsets), so its target is kept in LEAF-EQUIVALENT
247- // frame, and the two errors cancel. Fixing the split alone therefore277+ // bytes and [`RateLoop::update`] scales it by the coded frame's own
248- // makes the loop WORSE; `ARF_WEIGHT` has to be recalibrated in the278+ // `w(offset)`. Measuring each hidden frame against its OWN predicted
249- // same diff, which is a rate-control lane, not a pyramid-shape one279+ // size is what keeps the shared slot from oscillating between the
250- // (lane-pyr6, `lanes/pyr6.sweep.txt`).280+ // levels it mixes.
251- let share = rest * m / (m - 1.0 + ARF_WEIGHT);
252 Self {281 Self {
253- target: [target_bytes * key, share * ARF_WEIGHT, share],282+ target: [scale * key, scale, scale],
254 q: [start_q; 3],283 q: [start_q; 3],
255 per_level: true,284 per_level: true,
256 seeded: [false; 3],285 seeded: [false; 3],
286+ leaf_q_offset: p.leaf_q_offset,
287+ key_weight: key,
288+ run_weight: total,
289+ run_bytes: target_bytes * gop.max(1) as f64,
290+ left_weight: total,
291+ left_bytes: target_bytes * gop.max(1) as f64,
257 }292 }
258 }293 }
259 294
295+ /// What a frame coded `offset` steps off `base_q_idx` is worth in
296+ /// leaf-equivalent bytes ([`WEIGHT_LEVEL_GAIN`]).
297+ fn weight(&self, offset: i16) -> f64 {
298+ ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
299+ }
300+
260 /// Which controller a level uses: one shared slot on the flat path, three301 /// Which controller a level uses: one shared slot on the flat path, three
261 /// separate ones under a pyramid.302 /// separate ones under a pyramid.
262 fn slot(&self, level: Level) -> usize {303 fn slot(&self, level: Level) -> usize {
@@ -278,12 +319,23 @@ impl RateLoop {
278 319
279 /// Steers this level's `q` toward its own target from the frame's actual320 /// Steers this level's `q` toward its own target from the frame's actual
280 /// coded size.321 /// coded size.
281- fn update(&mut self, level: Level, actual_bytes: usize) {322+ fn update(&mut self, level: Level, offset: i16, actual_bytes: usize) {
282 let slot = self.slot(level);323 let slot = self.slot(level);
283 if self.target[slot] <= 0.0 || actual_bytes == 0 {324 if self.target[slot] <= 0.0 || actual_bytes == 0 {
284 return;325 return;
285 }326 }
286- let ratio = actual_bytes as f64 / self.target[slot];327+ // A hidden frame is measured against ITS OWN level's predicted size:
328+ // slot 1's target is in leaf-equivalent bytes.
329+ let frame_weight = match slot {
330+ 0 => self.key_weight,
331+ 1 => self.weight(offset),
332+ _ => 1.0,
333+ };
334+ let target = match self.per_level && slot == 1 {
335+ true => self.target[slot] * frame_weight,
336+ false => self.target[slot],
337+ };
338+ let ratio = actual_bytes as f64 / target;
287 // `STEP_CLAMP` protects an operating point this slot has not found339 // `STEP_CLAMP` protects an operating point this slot has not found
288 // yet: its `q` is still the caller's `base_q_idx` guess, and the340 // yet: its `q` is still the caller's `base_q_idx` guess, and the
289 // clamp makes the loop WALK to the right quantizer at twelve steps a341 // clamp makes the loop WALK to the right quantizer at twelve steps a
@@ -302,6 +354,43 @@ impl RateLoop {
302 raw354 raw
303 };355 };
304 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);356 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
357+ self.replan(level, frame_weight, actual_bytes as f64);
358+ }
359+
360+ /// Re-plans the REST OF THE RUN from what it has actually spent: the
361+ /// level model says how the budget SPLITS, and nothing but a measurement
362+ /// says what a frame of this content costs at all.
363+ ///
364+ /// Two frames of a run cannot be steered by the loop and both are pure
365+ /// model error without this: the KEY, coded once at the caller's seed `q`
366+ /// before anything has been measured (the census's key frames run 0.5x to
367+ /// 2.7x the model across the two films), and any level whose `q` has hit
368+ /// the floor -- at 3 Mbit/s on the gate's clip the hidden slot codes at
369+ /// `q_idx` 1 and physically cannot spend its share, which the leaves must
370+ /// then absorb or the stream lands a third under target.
371+ ///
372+ /// It is NOT an accumulated error term in `q` ([[vorbis-rate-loop-windup]]
373+ /// is about exactly that): `q` still moves only by this frame's own
374+ /// clamped proportional step, the re-plan only moves the TARGET the next
375+ /// frame is measured against, and every key frame resets the whole plan,
376+ /// so no debt outlives one run.
377+ fn replan(&mut self, level: Level, frame_weight: f64, actual_bytes: f64) {
378+ if !self.per_level {
379+ return;
380+ }
381+ if level == Level::Key {
382+ self.left_weight = self.run_weight;
383+ self.left_bytes = self.run_bytes;
384+ }
385+ self.left_weight -= frame_weight;
386+ self.left_bytes -= actual_bytes;
387+ // The tail of a run is not re-planned: under a leaf's worth of weight
388+ // left, the division is noise.
389+ if self.left_weight <= 1.0 {
390+ return;
391+ }
392+ let scale = (self.left_bytes / self.left_weight).max(0.0);
393+ self.target = [scale * self.key_weight, scale, scale];
305 }394 }
306 }395 }
307 396
@@ -460,6 +549,47 @@ fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize {
460 }549 }
461 }550 }
462 551
552+/// How one GOP of `gop` pictures is actually coded, as [`Av1Encoder::encode_frames`]
553+/// and [`Av1Encoder::drain_pending`] lay it out: the HIDDEN frames as
554+/// `(q offset, count)` (the group's top `ALTREF`, the mid level and the two
555+/// quarter-point ARFs, each at its own offset) and the number of shown
556+/// leaves. The key frame is the remaining picture and is not listed.
557+///
558+/// This is what [`RateLoop::new`] prices the run by, so the two must agree on
559+/// the gating rules -- a mid level needs three leaves and a run longer than
560+/// 1.5 mini-GOPs, quarters need seven leaves and a mid -- which
561+/// `the_rate_loop_prices_the_frames_the_pyramid_codes` pins against the real
562+/// packet stream.
563+fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) {
564+ let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize);
565+ let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) {
566+ Some((_, c)) => *c += n,
567+ None => hidden.push((offset, n)),
568+ };
569+ let long_run = gop > p.mini_gop + p.mini_gop / 2;
570+ let mut left = gop.saturating_sub(1);
571+ while left > 0 {
572+ let g = group_target(left, p.mini_gop, absorb_tail()).min(left);
573+ left -= g;
574+ if g == 1 {
575+ leaves += 1;
576+ continue;
577+ }
578+ let inner = g - 1;
579+ add(p.arf_q_offset, 1);
580+ let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run);
581+ let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7);
582+ if let Some(o) = mid {
583+ add(o, 1);
584+ }
585+ if let Some(o) = quarters {
586+ add(o, 2);
587+ }
588+ leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some());
589+ }
590+ (hidden, leaves)
591+}
592+
463 /// Whether this run absorbs a short tail group (the default) or cuts every593 /// Whether this run absorbs a short tail group (the default) or cuts every
464 /// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once.594 /// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once.
465 fn absorb_tail() -> bool {595 fn absorb_tail() -> bool {
@@ -1318,7 +1448,8 @@ impl Av1Encoder {
1318 let cropped = crop_encoded(&encoded, render.0, render.1);1448 let cropped = crop_encoded(&encoded, render.0, render.1);
1319 let level = if is_key { Level::Key } else { Level::Leaf };1449 let level = if is_key { Level::Key } else { Level::Leaf };
1320 if let Some(rate_loop) = self.rate_loop.as_mut() {1450 if let Some(rate_loop) = self.rate_loop.as_mut() {
1321- rate_loop.update(level, cropped.stream.len());1451+ // The flat path codes every frame at the slot's own q, no offset.
1452+ rate_loop.update(level, 0, cropped.stream.len());
1322 }1453 }
1323 Ok(self.packet(cropped.stream, is_key, order, level))1454 Ok(self.packet(cropped.stream, is_key, order, level))
1324 }1455 }
@@ -1440,7 +1571,7 @@ impl Av1Encoder {
1440 self.anchor = 0;1571 self.anchor = 0;
1441 let cropped = crop_encoded(&encoded, render.0, render.1);1572 let cropped = crop_encoded(&encoded, render.0, render.1);
1442 if let Some(rate_loop) = self.rate_loop.as_mut() {1573 if let Some(rate_loop) = self.rate_loop.as_mut() {
1443- rate_loop.update(Level::Key, cropped.stream.len());1574+ rate_loop.update(Level::Key, 0, cropped.stream.len());
1444 }1575 }
1445 if let Some(collected) = self.collected.as_mut() {1576 if let Some(collected) = self.collected.as_mut() {
1446 collected.push((order, cropped.clone()));1577 collected.push((order, cropped.clone()));
@@ -1551,7 +1682,7 @@ impl Av1Encoder {
1551 self.refresh(&[self_slot], &encoded, order_hint);1682 self.refresh(&[self_slot], &encoded, order_hint);
1552 let cropped = crop_encoded(&encoded, render.0, render.1);1683 let cropped = crop_encoded(&encoded, render.0, render.1);
1553 if let Some(rate_loop) = self.rate_loop.as_mut() {1684 if let Some(rate_loop) = self.rate_loop.as_mut() {
1554- rate_loop.update(level, cropped.stream.len());1685+ rate_loop.update(level, offset, cropped.stream.len());
1555 }1686 }
1556 if let Some(collected) = self.collected.as_mut() {1687 if let Some(collected) = self.collected.as_mut() {
1557 collected.push((order, cropped.clone()));1688 collected.push((order, cropped.clone()));
@@ -1791,6 +1922,73 @@ mod tests {
1791 packets1922 packets
1792 }1923 }
1793 1924
1925+ /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
1926+ /// counts and leaf count match the packets a real run emits, at three
1927+ /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
1928+ /// the run's budget exactly (`gop` frame targets, no more and no less).
1929+ ///
1930+ /// Both halves matter: a shape that misses a level (the old model priced
1931+ /// ONE hidden frame per group when the mid level had made it two) splits
1932+ /// the budget by weights that do not add up to the run.
1933+ #[test]
1934+ fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
1935+ let _knobs = crate::speed::knob_read();
1936+ let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
1937+ let quarters = Pyramid {
1938+ quarter_q_offset: Some(-20),
1939+ ..Pyramid::default()
1940+ };
1941+ let two_level = Pyramid {
1942+ mid_q_offset: None,
1943+ ..Pyramid::default()
1944+ };
1945+ for (gop, pyramid) in [
1946+ (48, Pyramid::default()),
1947+ (12, Pyramid::default()),
1948+ (48, quarters),
1949+ (48, two_level),
1950+ ] {
1951+ let config = EncoderConfig {
1952+ width: 64,
1953+ height: 64,
1954+ base_q_idx: 100,
1955+ gop,
1956+ colour: Colour::Bt709Limited,
1957+ tile_cols_log2: 0,
1958+ tile_rows_log2: 0,
1959+ };
1960+ let rate = RateTarget::BytesPerFrame(2_000);
1961+ let mut enc =
1962+ Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
1963+ let packets = encode_all(&mut enc, &pictures[..gop]);
1964+ let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
1965+ let (hidden, leaves) = gop_shape(pyramid, gop);
1966+ let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
1967+ assert_eq!(
1968+ (hidden_frames, leaves, 1),
1969+ (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
1970+ "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
1971+ );
1972+ assert_eq!(
1973+ hidden_frames + leaves + 1,
1974+ gop,
1975+ "gop {gop}: every picture is coded exactly once"
1976+ );
1977+ // The plan adds up: one leaf's target times the run's whole
1978+ // weight is the run's whole budget.
1979+ let target_bytes = 2_000.0;
1980+ let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
1981+ let planned = loop_.target[0]
1982+ + loop_.target[2] * (leaves as f64
1983+ + hidden.iter().map(|&(o, n)| n as f64 * loop_.weight(o)).sum::<f64>());
1984+ assert!(
1985+ (planned - target_bytes * gop as f64).abs() < 1.0,
1986+ "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
1987+ target_bytes * gop as f64
1988+ );
1989+ }
1990+ }
1991+
1794 /// The mini-GOP layout leaves no short tail group, and leaves the long1992 /// The mini-GOP layout leaves no short tail group, and leaves the long
1795 /// GOP the fixed rule already coded alone: 47 inter pictures are1993 /// GOP the fixed rule already coded alone: 47 inter pictures are
1796 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),1994 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
@@ -2361,21 +2559,31 @@ mod tests {
2361 );2559 );
2362 }2560 }
2363 2561
2364- /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±10% of the2562+ /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
2365- /// target over 48 frames of a real clip, flat and under a pyramid alike.2563+ /// target over 48 frames of a real clip, flat and under a pyramid alike,
2366- /// This is the accuracy claim of the target-bitrate mode: no two-pass, no2564+ /// across a 5x span of bitrates. This is the accuracy claim of the
2367- /// lookahead, just each frame's size predicted from the previous frame of2565+ /// target-bitrate mode: no two-pass, no lookahead, just each frame's size
2368- /// its own level and one clamped proportional step.2566+ /// predicted from the previous frame of its own level, one clamped
2567+ /// proportional step, and the level model
2568+ /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
2569+ ///
2570+ /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
2571+ /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
2572+ /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
2573+ /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
2574+ /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
2575+ /// `leaf_q_offset`, so this clip cannot be made to spend much past
2576+ /// 2.4 Mbit/s under the default pyramid however the budget is split.
2369 #[test]2577 #[test]
2370- fn bitrate_target_lands_within_10_percent_over_48_frames() {2578+ fn bitrate_target_lands_within_5_percent_over_48_frames() {
2371 let _knobs = crate::speed::knob_read();2579 let _knobs = crate::speed::knob_read();
2372 let (width, height, frames) = (640usize, 384usize, 48usize);2580 let (width, height, frames) = (640usize, 384usize, 48usize);
2373 let Some(pictures) = h264_clip_frames(width, height, frames) else {2581 let Some(pictures) = h264_clip_frames(width, height, frames) else {
2374- eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture");2582+ eprintln!("SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture");
2375 return;2583 return;
2376 };2584 };
2377 let fps = 24.0;2585 let fps = 24.0;
2378- for bits_per_second in [768_000u32, 1_536_000] {2586+ for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
2379 let config = EncoderConfig {2587 let config = EncoderConfig {
2380 width,2588 width,
2381 height,2589 height,
@@ -2394,26 +2602,50 @@ mod tests {
2394 None => Av1Encoder::with_rate_target(config, rate).unwrap(),2602 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
2395 Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),2603 Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
2396 };2604 };
2605+ let targets = enc.rate_loop.as_ref().unwrap().target;
2397 let mut coded = 0usize;2606 let mut coded = 0usize;
2398- for picture in &pictures {2607+ // Per level, so a miss reads as WHICH level's model is off
2399- for packet in enc.encode_frames(picture).unwrap() {2608+ // rather than as one aggregate percentage.
2609+ let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]);
2610+ let mut take = |packets: Vec<Packet>| {
2611+ for packet in packets {
2400 coded += packet.data.len();2612 coded += packet.data.len();
2613+ let i = match packet.level {
2614+ Level::Key => 0,
2615+ Level::Arf => 1,
2616+ Level::Leaf => 2,
2617+ Level::ShowExisting => 3,
2618+ };
2619+ bytes[i] += packet.data.len();
2620+ count[i] += 1;
2401 }2621 }
2622+ };
2623+ for picture in &pictures {
2624+ take(enc.encode_frames(picture).unwrap());
2402 }2625 }
2403- for packet in enc.flush().unwrap() {2626+ take(enc.flush().unwrap());
2404- coded += packet.data.len();
2405- }
2406 let seconds = frames as f64 / fps;2627 let seconds = frames as f64 / fps;
2407 let achieved = coded as f64 * 8.0 / seconds;2628 let achieved = coded as f64 * 8.0 / seconds;
2408 let error = achieved / f64::from(bits_per_second) - 1.0;2629 let error = achieved / f64::from(bits_per_second) - 1.0;
2630+ let per = |i: usize| match count[i] {
2631+ 0 => "-".to_string(),
2632+ n => format!("{n}x{}", bytes[i] / n),
2633+ };
2409 eprintln!(2634 eprintln!(
2410 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \2635 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
2411- = {achieved:.0} bps ({:+.1}%)",2636+ = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
2637+ coded key {} arf {} leaf {}",
2412 pyramid.is_some(),2638 pyramid.is_some(),
2413 100.0 * error,2639 100.0 * error,
2640+ targets[0],
2641+ targets[1],
2642+ targets[2],
2643+ per(0),
2644+ per(1),
2645+ per(2),
2414 );2646 );
2415 assert!(2647 assert!(
2416- error.abs() <= 0.10,2648+ error.abs() <= 0.05,
2417 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \2649 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
2418 (pyramid {})",2650 (pyramid {})",
2419 100.0 * error,2651 100.0 * error,
lanes/rc.report.mdadded+91 -0
@@ -0,0 +1,91 @@
1+# lane-rc — the rate loop's level model
2+
3+`crates/ec-av1/src/encoder.rs` only (`RateLoop`, `gop_shape`, their tests).
4+
5+## The defect (lane-pyr6's debt)
6+
7+`RateLoop::new` split a mini-GOP as `m / (m - 1 + ARF_WEIGHT)`: ONE hidden
8+frame per group, priced at a flat two leaves. Since the mid level landed a
9+group codes TWO hidden frames at different q offsets, and a hidden frame is
10+worth far more than two leaves. The two errors cancelled, which is why fixing
11+either alone made the loop worse.
12+
13+## The fitted weight function
14+
15+Census: `EC_ENC_SS=<gate seek> EC_ENC_OUT=<dir> enc_probe <film> gate 0 48
16+110,150,190` then `EC_AV1_BITCENSUS=1 syntax_census <dir>/ours-q<q>.obu`,
17+film A (1080p, seek 00:35:00) and film B (2160p, seek 00:40:00). 48 pictures =
18+1 key + 6 top ARF + 6 mid + 35 leaves at the default pyramid
19+(8 : -32 : +12 : -8 : -48). Film B q150 reproduces `lanes/census-longgop-v2.md`
20+byte for byte (90674 B stream, key 19321 / ARF 8021 / mid 1722 / leaf 335).
21+
22+Bytes per frame, and the ratio to that stream's own leaf:
23+
24+| film | q | key (dq 60) | ARF (dq 44) | mid (dq 20) | leaf |
25+|---|---|---|---|---|---|
26+| A | 110 | 65594 (13.9x) | 29421 (6.3x) | 11023 (2.3x) | 4706 |
27+| A | 150 | 39722 (19.9x) | 13668 (6.9x) | 4730 (2.4x) | 1994 |
28+| A | 190 | 22621 (26.3x) | 6092 (7.1x) | 2194 (2.6x) | 860 |
29+| B | 110 | 37854 (25.2x) | 22798 (15.2x) | 6570 (4.4x) | 1504 |
30+| B | 150 | 19321 (57.7x) | 8021 (23.9x) | 1722 (5.1x) | 335 |
31+| B | 190 | 9733 (76.0x) | 2414 (18.9x) | 465 (3.6x) | 128 |
32+
33+`dq` is `leaf_q_offset - own offset`. Least squares through the origin on the
34+12 INTER points (mid, ARF; both films, all three q) gives
35+
36+ weight(offset) = exp(0.0557 * (leaf_q_offset - offset)) WEIGHT_LEVEL_GAIN
37+
38+i.e. `d(ln bytes)/d(q_idx) = -0.0557`, three and a half times the controller's
39+own `GAIN` slope (0.0154), because a deeper level also carries the residual of
40+every frame that predicts off it. The six KEY points, divided by that same
41+function at `dq` 60, leave a residual of geometric mean 1.08 (spread 0.47 film
42+A q110 .. 2.68 film B q190), which is `KEY_WEIGHT`.
43+
44+The run's plan is then `gop_shape` (the hidden frames a run really codes, by
45+offset, plus the leaf count -- mid needs 3 leaves and a run > 1.5 mini-GOPs,
46+quarters need 7 leaves and a mid) priced through `weight`, so the plan spends
47+`gop` frame targets exactly.
48+
49+Two things the model alone cannot price, both re-planned from measurement
50+(`RateLoop::replan`, reset by every key frame so no debt outlives a run):
51+the KEY, coded at the caller's seed `q` before anything is measured (0.47x to
52+2.68x the model above), and any level whose `q` has hit the floor.
53+
54+## The landed table (`bitrate_target_lands_within_5_percent_over_48_frames`)
55+
56+48 frames, 640x384 clip, 24 fps. Flat arm is untouched by this diff (the model
57+is pyramid-only) and is shown for reference.
58+
59+| bps | flat before | flat after | pyramid before | pyramid after |
60+|---|---|---|---|---|
61+| 384k | - | -0.4% | - | +3.0% |
62+| 768k | -1.8% | -1.8% | -0.4% | -0.0% |
63+| 1536k | -3.0% | -3.0% | -6.3% | +0.2% |
64+| 2M | - | -2.8% | - | -4.4% |
65+
66+Tolerance SHIPPED: +-5% (was +-10%), on all 8 arms.
67+
68+CEILING, stated rather than hidden: the charter's 3 Mbit/s arm is not
69+reachable on this clip under the default pyramid and is NOT in the test. At
70+3 Mbit/s the hidden slot already codes at `q_idx` 1 (22863 bytes a frame, the
71+same figure it reaches at 1.5 Mbit/s) and the leaves sit at 1 + 12
72+`leaf_q_offset`; the whole stream tops out near 2.4 Mbit/s however the budget
73+is split. The top arm is 2 Mbit/s, inside the reach, and its -4.4% is that
74+ceiling showing through. Lifting it is a pyramid-shape change (the offsets
75+would have to collapse as `q` approaches the floor), out of this lane's scope.
76+
77+## Gates
78+
79+- `cargo test --release -p ec-av1 --lib encoder::` — 26 passed / 0 failed / 8
80+ ignored, including `the_facade_codes_the_same_bytes_as_encode_sequence`
81+ (the rate-loop-off path is untouched) and the new
82+ `the_rate_loop_prices_the_frames_the_pyramid_codes`.
83+- Same, with `EC_COMP_MISMATCH=1` — 26 passed / 0 failed, no mismatch.
84+- Full crate suite (detached): `test result: ok. 559 passed; 0 failed;
85+ 44 ignored` in 850 s — 558 + this lane's one new test. That run contains
86+ `encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins`,
87+ so the constant-q pins 9835 (q150) / 35798 (q60) are unchanged.
88+- `cargo check --workspace --all-targets -j4` — 0 errors, 0 ec-av1 warnings
89+ (the 22 warnings are pre-existing ec-opus/ec-vorbis ones).
90+- `rustfmt --edition 2024 --check crates/ec-av1/src/encoder.rs` — clean.
91+- /tmp at 68%.