A rate-loop level at its quantizer bound hands its bytes to the others
Browse files at this commit366d5d6d5d1718b58fb9ab93493bc18dac495664Parent: 7c94ff1- fix
- a rate-loop level at its quantizer bound hands its bytes to the others
1 changed file +161 -7
- crates/ec-av1/src/encoder.rs +161 -7
crates/ec-av1/src/encoder.rsmodified+161 -7
| @@ -181,6 +181,11 @@ const WEIGHT_LEVEL_GAIN: f64 = 0.0557; | |||
| 181 | /// keeps growing with reference depth). | 181 | /// keeps growing with reference depth). |
| 182 | const KEY_WEIGHT: f64 = 1.08; | 182 | const KEY_WEIGHT: f64 = 1.08; |
| 183 | 183 | ||
| 184 | +/// `EC_AV1_RL_CENSUS=1` — one stderr line per frame the rate loop steers. | ||
| 185 | +fn census_on() -> bool { | ||
| 186 | + std::env::var("EC_AV1_RL_CENSUS").is_ok_and(|v| v == "1") | ||
| 187 | +} | ||
| 188 | + | ||
| 184 | /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and | 189 | /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and |
| 185 | /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from | 190 | /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from |
| 186 | /// the calibration sweep's own log-linear slope (bytes roughly halve every | 191 | /// the calibration sweep's own log-linear slope (bytes roughly halve every |
| @@ -223,6 +228,24 @@ struct RateLoop { | |||
| 223 | /// What is left of both, ahead of the next frame. | 228 | /// What is left of both, ahead of the next frame. |
| 224 | left_weight: f64, | 229 | left_weight: f64, |
| 225 | left_bytes: f64, | 230 | left_bytes: f64, |
| 231 | + /// The same weights split PER SLOT ([`RateLoop::slot`]): the run's, and | ||
| 232 | + /// what is left of it. A level whose effective quantizer has hit a bound | ||
| 233 | + /// cannot follow the plan, so [`RateLoop::replan`] prices its remaining | ||
| 234 | + /// weight at what it MEASURABLY spends and re-solves the run's budget | ||
| 235 | + /// over the levels that can still move. | ||
| 236 | + run_weight_slot: [f64; 3], | ||
| 237 | + left_weight_slot: [f64; 3], | ||
| 238 | + /// Per slot: whether its last coded frame's `base_q_idx + offset` hit the | ||
| 239 | + /// 1..=255 bound, and the leaf-equivalent bytes it spends while it does. | ||
| 240 | + bound: [bool; 3], | ||
| 241 | + bound_rate: [f64; 3], | ||
| 242 | + /// The plan's scale at construction — the WINDUP BOUND on the re-plan: | ||
| 243 | + /// a level held at its bound hands its unspent bytes to the others, but | ||
| 244 | + /// no level's target may exceed this many times its own opening share. | ||
| 245 | + scale0: f64, | ||
| 246 | + /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr. | ||
| 247 | + census: bool, | ||
| 248 | + coded: usize, | ||
| 226 | } | 249 | } |
| 227 | 250 | ||
| 228 | impl RateLoop { | 251 | impl RateLoop { |
| @@ -234,6 +257,11 @@ impl RateLoop { | |||
| 234 | /// The calibration sweep's own slope (see the struct doc), inverted to | 257 | /// The calibration sweep's own slope (see the struct doc), inverted to |
| 235 | /// convert a bytes ratio into a `q_idx` step. | 258 | /// convert a bytes ratio into a `q_idx` step. |
| 236 | const GAIN: f64 = 1.0 / 0.0154; | 259 | const GAIN: f64 = 1.0 / 0.0154; |
| 260 | + /// The windup bound on [`RateLoop::replan`]: however much a bound level | ||
| 261 | + /// fails to spend, no other level's target may grow past this multiple of | ||
| 262 | + /// its opening share. Without it a run whose hidden levels are all at the | ||
| 263 | + /// floor would keep piling the whole run's budget onto the leaves. | ||
| 264 | + const REPLAN_CLAMP: f64 = 4.0; | ||
| 237 | 265 | ||
| 238 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { | 266 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { |
| 239 | let Some(p) = pyramid else { | 267 | let Some(p) = pyramid else { |
| @@ -248,6 +276,13 @@ impl RateLoop { | |||
| 248 | run_bytes: 0.0, | 276 | run_bytes: 0.0, |
| 249 | left_weight: 0.0, | 277 | left_weight: 0.0, |
| 250 | left_bytes: 0.0, | 278 | left_bytes: 0.0, |
| 279 | + run_weight_slot: [0.0; 3], | ||
| 280 | + left_weight_slot: [0.0; 3], | ||
| 281 | + bound: [false; 3], | ||
| 282 | + bound_rate: [0.0; 3], | ||
| 283 | + scale0: target_bytes, | ||
| 284 | + census: census_on(), | ||
| 285 | + coded: 0, | ||
| 251 | }; | 286 | }; |
| 252 | }; | 287 | }; |
| 253 | // THE LEVEL MODEL. Every coded frame of the run is priced by its own | 288 | // THE LEVEL MODEL. Every coded frame of the run is priced by its own |
| @@ -278,6 +313,7 @@ impl RateLoop { | |||
| 278 | // `w(offset)`. Measuring each hidden frame against its OWN predicted | 313 | // `w(offset)`. Measuring each hidden frame against its OWN predicted |
| 279 | // size is what keeps the shared slot from oscillating between the | 314 | // size is what keeps the shared slot from oscillating between the |
| 280 | // levels it mixes. | 315 | // levels it mixes. |
| 316 | + let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum(); | ||
| 281 | Self { | 317 | Self { |
| 282 | target: [scale * key, scale, scale], | 318 | target: [scale * key, scale, scale], |
| 283 | q: [start_q; 3], | 319 | q: [start_q; 3], |
| @@ -289,6 +325,13 @@ impl RateLoop { | |||
| 289 | run_bytes: target_bytes * gop.max(1) as f64, | 325 | run_bytes: target_bytes * gop.max(1) as f64, |
| 290 | left_weight: total, | 326 | left_weight: total, |
| 291 | left_bytes: target_bytes * gop.max(1) as f64, | 327 | left_bytes: target_bytes * gop.max(1) as f64, |
| 328 | + run_weight_slot: [key, hidden_weight, leaves as f64], | ||
| 329 | + left_weight_slot: [key, hidden_weight, leaves as f64], | ||
| 330 | + bound: [false; 3], | ||
| 331 | + bound_rate: [0.0; 3], | ||
| 332 | + scale0: scale, | ||
| 333 | + census: census_on(), | ||
| 334 | + coded: 0, | ||
| 292 | } | 335 | } |
| 293 | } | 336 | } |
| 294 | 337 | ||
| @@ -319,7 +362,11 @@ impl RateLoop { | |||
| 319 | 362 | ||
| 320 | /// Steers this level's `q` toward its own target from the frame's actual | 363 | /// Steers this level's `q` toward its own target from the frame's actual |
| 321 | /// coded size. | 364 | /// coded size. |
| 322 | - fn update(&mut self, level: Level, offset: i16, actual_bytes: usize) { | 365 | + /// |
| 366 | + /// `raw_q` is the quantizer the frame WANTED (`base_q_idx + offset`, | ||
| 367 | + /// before the coder's own 1..=255 clamp): outside that range the level is | ||
| 368 | + /// at its bound and its share of the budget has to move elsewhere. | ||
| 369 | + fn update(&mut self, level: Level, offset: i16, raw_q: i16, actual_bytes: usize) { | ||
| 323 | let slot = self.slot(level); | 370 | let slot = self.slot(level); |
| 324 | if self.target[slot] <= 0.0 || actual_bytes == 0 { | 371 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 325 | return; | 372 | return; |
| @@ -354,7 +401,22 @@ impl RateLoop { | |||
| 354 | raw | 401 | raw |
| 355 | }; | 402 | }; |
| 356 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); | 403 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 357 | - self.replan(level, frame_weight, actual_bytes as f64); | 404 | + self.bound[slot] = !(1..=255).contains(&raw_q); |
| 405 | + self.bound_rate[slot] = actual_bytes as f64 / frame_weight.max(f64::EPSILON); | ||
| 406 | + if self.census { | ||
| 407 | + eprintln!( | ||
| 408 | + "RLCENSUS n={} level={level:?} slot={slot} target={target:.0} actual={actual_bytes} \ | ||
| 409 | + base_q={:.1} raw_q={raw_q} eff_q={} bound={} left_bytes={:.0} left_w={:.1}", | ||
| 410 | + self.coded, | ||
| 411 | + self.q[slot], | ||
| 412 | + raw_q.clamp(1, 255), | ||
| 413 | + self.bound[slot], | ||
| 414 | + self.left_bytes, | ||
| 415 | + self.left_weight, | ||
| 416 | + ); | ||
| 417 | + self.coded += 1; | ||
| 418 | + } | ||
| 419 | + self.replan(level, slot, frame_weight, actual_bytes as f64); | ||
| 358 | } | 420 | } |
| 359 | 421 | ||
| 360 | /// Re-plans the REST OF THE RUN from what it has actually spent: the | 422 | /// Re-plans the REST OF THE RUN from what it has actually spent: the |
| @@ -374,22 +436,51 @@ impl RateLoop { | |||
| 374 | /// clamped proportional step, the re-plan only moves the TARGET the next | 436 | /// 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, | 437 | /// frame is measured against, and every key frame resets the whole plan, |
| 376 | /// so no debt outlives one run. | 438 | /// so no debt outlives one run. |
| 377 | - fn replan(&mut self, level: Level, frame_weight: f64, actual_bytes: f64) { | 439 | + fn replan(&mut self, level: Level, slot: usize, frame_weight: f64, actual_bytes: f64) { |
| 378 | if !self.per_level { | 440 | if !self.per_level { |
| 379 | return; | 441 | return; |
| 380 | } | 442 | } |
| 381 | if level == Level::Key { | 443 | if level == Level::Key { |
| 382 | self.left_weight = self.run_weight; | 444 | self.left_weight = self.run_weight; |
| 383 | self.left_bytes = self.run_bytes; | 445 | self.left_bytes = self.run_bytes; |
| 446 | + self.left_weight_slot = self.run_weight_slot; | ||
| 384 | } | 447 | } |
| 385 | self.left_weight -= frame_weight; | 448 | self.left_weight -= frame_weight; |
| 386 | self.left_bytes -= actual_bytes; | 449 | self.left_bytes -= actual_bytes; |
| 450 | + self.left_weight_slot[slot] = (self.left_weight_slot[slot] - frame_weight).max(0.0); | ||
| 387 | // The tail of a run is not re-planned: under a leaf's worth of weight | 451 | // The tail of a run is not re-planned: under a leaf's worth of weight |
| 388 | // left, the division is noise. | 452 | // left, the division is noise. |
| 389 | if self.left_weight <= 1.0 { | 453 | if self.left_weight <= 1.0 { |
| 390 | return; | 454 | return; |
| 391 | } | 455 | } |
| 392 | - let scale = (self.left_bytes / self.left_weight).max(0.0); | 456 | + // A BOUND level is held at what it measurably spends and its weight |
| 457 | + // is taken out of the division, so the bytes it cannot spend land on | ||
| 458 | + // the levels that can (and, at the ceiling, the other way round). The | ||
| 459 | + // old code divided the whole remainder by the whole remaining weight, | ||
| 460 | + // which handed the biggest share of the shortfall straight back to | ||
| 461 | + // the level that had just failed to spend it -- at the default | ||
| 462 | + // pyramid the hidden levels carry most of the run's weight, so most | ||
| 463 | + // of the surplus evaporated there every frame. | ||
| 464 | + // ABLATION (`EC_AV1_RL_NOREDIST=1`, this lane's before/after arm): | ||
| 465 | + // the old division, whole remainder over whole remaining weight. | ||
| 466 | + if std::env::var("EC_AV1_RL_NOREDIST").is_ok_and(|v| v == "1") { | ||
| 467 | + let scale = (self.left_bytes / self.left_weight).max(0.0); | ||
| 468 | + self.target = [scale * self.key_weight, scale, scale]; | ||
| 469 | + return; | ||
| 470 | + } | ||
| 471 | + let (mut bytes, mut weight) = (self.left_bytes, 0.0); | ||
| 472 | + for s in 0..3 { | ||
| 473 | + if self.bound[s] { | ||
| 474 | + bytes -= self.bound_rate[s] * self.left_weight_slot[s]; | ||
| 475 | + } else { | ||
| 476 | + weight += self.left_weight_slot[s]; | ||
| 477 | + } | ||
| 478 | + } | ||
| 479 | + if weight <= 1.0 { | ||
| 480 | + // Every movable level is spent: nothing left to re-solve over. | ||
| 481 | + return; | ||
| 482 | + } | ||
| 483 | + let scale = (bytes / weight).max(0.0).min(self.scale0 * Self::REPLAN_CLAMP); | ||
| 393 | self.target = [scale * self.key_weight, scale, scale]; | 484 | self.target = [scale * self.key_weight, scale, scale]; |
| 394 | } | 485 | } |
| 395 | } | 486 | } |
| @@ -1567,7 +1658,7 @@ impl Av1Encoder { | |||
| 1567 | let level = if is_key { Level::Key } else { Level::Leaf }; | 1658 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 1568 | if let Some(rate_loop) = self.rate_loop.as_mut() { | 1659 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1569 | // The flat path codes every frame at the slot's own q, no offset. | 1660 | // The flat path codes every frame at the slot's own q, no offset. |
| 1570 | - rate_loop.update(level, 0, cropped.stream.len()); | 1661 | + rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len()); |
| 1571 | } | 1662 | } |
| 1572 | Ok(self.packet(cropped.stream, is_key, order, level)) | 1663 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 1573 | } | 1664 | } |
| @@ -1692,7 +1783,7 @@ impl Av1Encoder { | |||
| 1692 | self.leaf_hist.clear(); | 1783 | self.leaf_hist.clear(); |
| 1693 | let cropped = crop_encoded(&encoded, render.0, render.1); | 1784 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1694 | if let Some(rate_loop) = self.rate_loop.as_mut() { | 1785 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1695 | - rate_loop.update(Level::Key, 0, cropped.stream.len()); | 1786 | + rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len()); |
| 1696 | } | 1787 | } |
| 1697 | if let Some(collected) = self.collected.as_mut() { | 1788 | if let Some(collected) = self.collected.as_mut() { |
| 1698 | collected.push((order, cropped.clone())); | 1789 | collected.push((order, cropped.clone())); |
| @@ -1855,7 +1946,7 @@ impl Av1Encoder { | |||
| 1855 | self.refresh(&[self_slot], &encoded, order_hint); | 1946 | self.refresh(&[self_slot], &encoded, order_hint); |
| 1856 | let cropped = crop_encoded(&encoded, render.0, render.1); | 1947 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1857 | if let Some(rate_loop) = self.rate_loop.as_mut() { | 1948 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1858 | - rate_loop.update(level, offset, cropped.stream.len()); | 1949 | + rate_loop.update(level, offset, base + offset, cropped.stream.len()); |
| 1859 | } | 1950 | } |
| 1860 | if let Some(collected) = self.collected.as_mut() { | 1951 | if let Some(collected) = self.collected.as_mut() { |
| 1861 | collected.push((order, cropped.clone())); | 1952 | collected.push((order, cropped.clone())); |
| @@ -2224,6 +2315,69 @@ mod tests { | |||
| 2224 | } | 2315 | } |
| 2225 | } | 2316 | } |
| 2226 | 2317 | ||
| 2318 | + /// A level at its quantizer BOUND hands its unspent bytes to the levels | ||
| 2319 | + /// that can still move ([[vorbis-rate-loop-windup]]'s class in the | ||
| 2320 | + /// small), and it does so AT ONCE, not once the bound level's frames are | ||
| 2321 | + /// all coded: the loop is driven by a synthetic per-level model where the | ||
| 2322 | + /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255 | ||
| 2323 | + /// clamp) and spends half its plan, and the leaves' target must jump to | ||
| 2324 | + /// the run's remainder with EVERY remaining hidden frame priced at that | ||
| 2325 | + /// measured rate. The old division -- whole remainder over whole | ||
| 2326 | + /// remaining weight -- handed most of the shortfall straight back to the | ||
| 2327 | + /// hidden slot (which carries most of the pyramid's weight and cannot | ||
| 2328 | + /// spend it), so the leaves only saw the surplus at the end of the run, | ||
| 2329 | + /// when there was nothing left to code with it. | ||
| 2330 | + #[test] | ||
| 2331 | + fn a_bound_level_hands_its_unspent_bytes_to_the_others() { | ||
| 2332 | + let pyramid = Pyramid::default(); | ||
| 2333 | + let (gop, target_bytes) = (48usize, 2_000.0); | ||
| 2334 | + let (hidden, leaves) = gop_shape(pyramid, gop); | ||
| 2335 | + let run_bytes = target_bytes * gop as f64; | ||
| 2336 | + let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); | ||
| 2337 | + let scale0 = rl.target[2]; | ||
| 2338 | + let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum(); | ||
| 2339 | + // The key codes exactly its plan; the first hidden frame is at the | ||
| 2340 | + // floor and spends half of its. | ||
| 2341 | + let key_bytes = rl.target[0].round(); | ||
| 2342 | + rl.update(Level::Key, 0, 100, key_bytes as usize); | ||
| 2343 | + let (offset, _) = hidden[0]; | ||
| 2344 | + let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round(); | ||
| 2345 | + rl.update(Level::Arf, offset, 0, arf_bytes as usize); | ||
| 2346 | + // Every hidden frame still to come is priced at the rate the bound | ||
| 2347 | + // one measured; the leaves get the whole rest. | ||
| 2348 | + let rate = arf_bytes / rl.weight(offset); | ||
| 2349 | + let want = | ||
| 2350 | + (run_bytes - key_bytes - arf_bytes - rate * (hidden_weight - rl.weight(offset))) | ||
| 2351 | + / leaves as f64; | ||
| 2352 | + assert!( | ||
| 2353 | + want < scale0 * RateLoop::REPLAN_CLAMP, | ||
| 2354 | + "this arm must not reach the windup bound: {want:.1} vs {:.1}", | ||
| 2355 | + scale0 * RateLoop::REPLAN_CLAMP | ||
| 2356 | + ); | ||
| 2357 | + assert!( | ||
| 2358 | + (rl.target[2] - want).abs() < 1e-6, | ||
| 2359 | + "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \ | ||
| 2360 | + give {:.3})", | ||
| 2361 | + rl.target[2], | ||
| 2362 | + (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset)) | ||
| 2363 | + ); | ||
| 2364 | + // And the re-plan stays BOUNDED: hidden levels that spend nothing at | ||
| 2365 | + // all cannot run the leaves' target away. | ||
| 2366 | + let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); | ||
| 2367 | + rl.update(Level::Key, 0, 100, key_bytes as usize); | ||
| 2368 | + for &(offset, n) in &hidden { | ||
| 2369 | + for _ in 0..n { | ||
| 2370 | + rl.update(Level::Arf, offset, 0, 1); | ||
| 2371 | + } | ||
| 2372 | + } | ||
| 2373 | + assert!( | ||
| 2374 | + rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9, | ||
| 2375 | + "the re-plan is unbounded: leaf target {:.1} past {:.1}", | ||
| 2376 | + rl.target[2], | ||
| 2377 | + scale0 * RateLoop::REPLAN_CLAMP | ||
| 2378 | + ); | ||
| 2379 | + } | ||
| 2380 | + | ||
| 2227 | /// The mini-GOP layout leaves no short tail group, and leaves the long | 2381 | /// The mini-GOP layout leaves no short tail group, and leaves the long |
| 2228 | /// GOP the fixed rule already coded alone: 47 inter pictures are | 2382 | /// GOP the fixed rule already coded alone: 47 inter pictures are |
| 2229 | /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical), | 2383 | /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical), |