Align the QP ladders from a probe encode
Browse files at this commit8b6026d57d3083542945af33f5b9b42b8862ed1aParent: 4ae6e08- test
- align the QP ladders from a probe encode
1 changed file +132 -50
- crates/ec-h265/tests/encode.rs +132 -50
crates/ec-h265/tests/encode.rsmodified+132 -50
| @@ -17,18 +17,25 @@ type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); | |||
| 17 | /// shrink but not grow unnoticed; it is not a claim that the number is fine. | 17 | /// shrink but not grow unnoticed; it is not a claim that the number is fine. |
| 18 | /// | 18 | /// |
| 19 | /// Measured +2.456 dB luma / +3.158 dB YUV on the recalibrated run (352x288, | 19 | /// Measured +2.456 dB luma / +3.158 dB YUV on the recalibrated run (352x288, |
| 20 | -/// 24 pictures of `Clip::render_smooth`, ours at QP 16/20/24/28, x265 at QP | 20 | +/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder |
| 21 | -/// 22/26/30/34, both sides decoded through ffmpeg, union-range BD-PSNR, 0% | 21 | +/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through |
| 22 | -/// extrapolation both sides). Our encoder is leaner than x265 — it spends fewer | 22 | +/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a |
| 23 | -/// bits at matched QP — so the QP ladders are offset to make the bitrate ranges | 23 | +/// smooth-gradient result: it does NOT hold on real content, where our |
| 24 | -/// overlap; at matched bitrate our PSNR is higher on this smooth synthetic clip. | 24 | +/// encoder is no leaner than x265 at matched QP (the probe measures a shift of |
| 25 | +/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after | ||
| 26 | +/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides: | ||
| 27 | +/// • 3840x1608 film: -0.731 dB luma / -0.730 dB YUV | ||
| 28 | +/// • 1138x640 web clip: -0.603 dB luma / -0.632 dB YUV | ||
| 29 | +/// Those two are the real gap to close; the synthetic number only guards | ||
| 30 | +/// against regression on a clip whose content is pinned. | ||
| 25 | /// | 31 | /// |
| 26 | /// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; | 32 | /// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; |
| 27 | -/// that number was meaningless — the curves did not overlap (50% extrapolation | 33 | +/// that number was meaningless because the two curves' bitrate ranges did not |
| 28 | -/// on our side) because x265's `-qp` was thought not to reach its rate control. | 34 | +/// overlap (50% extrapolation on our side) — a fixed QP offset could not |
| 29 | -/// In fact `-qp` and `rc=cqp:qp=N` produce identical output; the shallow | 35 | +/// bridge encoders whose relative leanness varies with content. The shallow |
| 30 | -/// rate-quality slope was genuine for this clip, and the fix was to offset the | 36 | +/// all-intra rate-quality slope is genuine content behaviour (x264 forced |
| 31 | -/// QP ladders, not to change x265's rate control. | 37 | +/// all-intra shows the same shape); the fix is to auto-align the ladders from |
| 38 | +/// a probe encode, not to change x265's rate control. | ||
| 32 | const BD_PSNR_VS_X265_FLOOR: f64 = 2.306; | 39 | const BD_PSNR_VS_X265_FLOOR: f64 = 2.306; |
| 33 | 40 | ||
| 34 | /// A synthetic source with real structure: smooth gradients, a band of | 41 | /// A synthetic source with real structure: smooth gradients, a band of |
| @@ -202,13 +209,14 @@ fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | |||
| 202 | /// | 209 | /// |
| 203 | /// The h264 gate's encoders land in the same bitrate band at the same QP, so | 210 | /// The h264 gate's encoders land in the same bitrate band at the same QP, so |
| 204 | /// the intersection is non-empty and the standard Bjøntegaard cubic integral | 211 | /// the intersection is non-empty and the standard Bjøntegaard cubic integral |
| 205 | -/// over it is well defined. Our h265 encoder is leaner than x265 at matched QP | 212 | +/// over it is well defined. Our h265 encoder's bitrate at matched QP can be |
| 206 | -/// — it spends fewer bits — so our QP sweep is shifted below x265's to make | 213 | +/// leaner or fatter than x265's depending on content, so the QP-ladder shift |
| 207 | -/// the bitrate ranges overlap. The union range is kept (not clipped to the | 214 | +/// is measured from a probe encode, not fixed — the union range is kept (not |
| 208 | -/// intersection) so the extrapolation share can be measured: if either curve | 215 | +/// clipped to the intersection) so the extrapolation share can be measured: |
| 209 | -/// is extrapolated over more than 20% of the range, the test fails with a | 216 | +/// if either curve is extrapolated over more than 20% of the range, the test |
| 210 | -/// named message instead of reporting a BD number that is a cubic guess, not | 217 | +/// fails with a named message instead of reporting a BD number that is a cubic |
| 211 | -/// a measurement. The extrapolation shares are returned alongside the number. | 218 | +/// guess, not a measurement. The extrapolation shares are returned alongside |
| 219 | +/// the number. | ||
| 212 | /// | 220 | /// |
| 213 | /// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the | 221 | /// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the |
| 214 | /// fraction of the integration range that each curve's measured bitrate span | 222 | /// fraction of the integration range that each curve's measured bitrate span |
| @@ -334,12 +342,12 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec | |||
| 334 | // plus the in-loop filters x265 adds and x264 does not have (no-sao, | 342 | // plus the in-loop filters x265 adds and x264 does not have (no-sao, |
| 335 | // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits | 343 | // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits |
| 336 | // the same way ours does. The quantiser goes inside the param string as | 344 | // the same way ours does. The quantiser goes inside the param string as |
| 337 | - // `rc=cqp:qp=N` because ffmpeg's `-qp` flag does not reach libx265's rate | 345 | + // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce |
| 338 | - // control — without `rc=cqp` x265 defaults to ABR and its bitrate barely | 346 | + // byte-identical streams, so the `rc=cqp:` prefix is unnecessary. |
| 339 | - // moves across a 12-QP span. EC_H265_X265_PARAMS appends to attribute a | 347 | + // EC_H265_X265_PARAMS appends to attribute a single feature the same way |
| 340 | - // single feature the same way EC_H264_X264_PARAMS does. | 348 | + // EC_H264_X264_PARAMS does. |
| 341 | let params = format!( | 349 | let params = format!( |
| 342 | - "rc=cqp:qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:\ | 350 | + "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:\ |
| 343 | aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ | 351 | aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ |
| 344 | pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", | 352 | pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", |
| 345 | match std::env::var("EC_H265_X265_PARAMS") { | 353 | match std::env::var("EC_H265_X265_PARAMS") { |
| @@ -369,12 +377,14 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec | |||
| 369 | stream | 377 | stream |
| 370 | } | 378 | } |
| 371 | 379 | ||
| 372 | -/// BD-PSNR of this encoder against x265 at matched features. Our encoder is | 380 | +/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored |
| 373 | -/// leaner than x265 at every QP, so our sweep (16/20/24/28) is shifted below | 381 | +/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a |
| 374 | -/// x265's (22/26/30/34) to make the bitrate ranges overlap and the cubic fit | 382 | +/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the |
| 375 | -/// interpolate instead of extrapolate. Runs on the synthetic clip by default, | 383 | +/// cubic fit interpolates instead of extrapolating — regardless of whether |
| 376 | -/// so the number cannot rot behind an `#[ignore]`; point `EC_H265_CLIP` at a | 384 | +/// our encoder is leaner or fatter than x265 at matched QP on the content at |
| 377 | -/// media file to measure the same thing on real content. | 385 | +/// hand. Runs on the synthetic clip by default, so the number cannot rot |
| 386 | +/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the | ||
| 387 | +/// same thing on real content. | ||
| 378 | /// | 388 | /// |
| 379 | /// Both curves are (bits, luma PSNR against the same source pictures), and | 389 | /// Both curves are (bits, luma PSNR against the same source pictures), and |
| 380 | /// both are measured on ffmpeg's decode of the stream rather than on an | 390 | /// both are measured on ffmpeg's decode of the stream rather than on an |
| @@ -507,38 +517,110 @@ fn bd_psnr_vs_x265() { | |||
| 507 | ((stream.len() * 8) as f64, sum / n, sum_yuv / n) | 517 | ((stream.len() * 8) as f64, sum / n, sum_yuv / n) |
| 508 | }; | 518 | }; |
| 509 | 519 | ||
| 510 | - // Our encoder is leaner than x265 at every QP — it spends fewer bits on | 520 | + // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP |
| 511 | - // the same content — so at matched QP our entire curve sits below x265's. | 521 | + // delta measured from a single probe encode, not a constant: both sides |
| 512 | - // Widening our sweep to lower QPs pushes our bitrate up into x265's range | 522 | + // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP |
| 513 | - // so the cubic fit interpolates instead of extrapolating. x265 stays at | 523 | + // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that |
| 514 | - // 22/26/30/34; ours drops to 16/20/24/28 to meet it. | 524 | + // shift. If the extrapolation share still exceeds 20% after measuring, the |
| 515 | - let our_qps = [16, 20, 24, 28]; | 525 | + // shift is re-estimated from the geometric-mean bit ratio of the two full |
| 526 | + // curves and the ladder is rebuilt — at most 2 extra alignment rounds | ||
| 527 | + // before the existing panic fires. | ||
| 528 | + const EXTRAP_LIMIT: f64 = 0.20; | ||
| 516 | let x265_qps = [22, 26, 30, 34]; | 529 | let x265_qps = [22, 26, 30, 34]; |
| 517 | - let mine: Vec<_> = our_qps.iter().map(|&q| ours(q)).collect(); | 530 | + let probe_qp = 26; |
| 518 | - let theirs: Vec<_> = x265_qps.iter().map(|&q| x265(q)).collect(); | 531 | + |
| 519 | - for (i, &qp) in our_qps.iter().enumerate() { | 532 | + // Probe both encoders at QP 26 to measure the bit ratio. |
| 520 | - let (ob, op, oy) = mine[i]; | 533 | + let probe_ours = ours(probe_qp); |
| 521 | - eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); | 534 | + let probe_x265 = x265(probe_qp); |
| 522 | - } | 535 | + let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; |
| 523 | - for (i, &qp) in x265_qps.iter().enumerate() { | 536 | + eprintln!( |
| 524 | - let (xb, xp, xy) = theirs[i]; | 537 | + "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", |
| 525 | - eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); | 538 | + probe_ours.0 / 1e6, |
| 526 | - } | 539 | + probe_x265.0 / 1e6, |
| 540 | + ); | ||
| 541 | + | ||
| 527 | let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { | 542 | let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { |
| 528 | v.iter() | 543 | v.iter() |
| 529 | .map(|&(b, p, y)| (b, if luma { p } else { y })) | 544 | .map(|&(b, p, y)| (b, if luma { p } else { y })) |
| 530 | .collect() | 545 | .collect() |
| 531 | }; | 546 | }; |
| 532 | - let (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | 547 | + |
| 533 | - let (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = | 548 | + // x265 ladder is fixed; reuse the probe for its QP-26 point. |
| 534 | - bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | 549 | + let theirs: Vec<(f64, f64, f64)> = x265_qps |
| 535 | - eprintln!("BD-PSNR ours (q16/20/24/28) vs x265 (q22/26/30/34): {bd:+.3} dB"); | 550 | + .iter() |
| 536 | - eprintln!("BD-PSNR-YUV ours (q16/20/24/28) vs x265 (q22/26/30/34): {bd_yuv:+.3} dB"); | 551 | + .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) |
| 552 | + .collect(); | ||
| 553 | + | ||
| 554 | + let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); | ||
| 555 | + let qps_str = |qs: &[i32; 4]| { | ||
| 556 | + qs.iter() | ||
| 557 | + .map(|q| q.to_string()) | ||
| 558 | + .collect::<Vec<_>>() | ||
| 559 | + .join("/") | ||
| 560 | + }; | ||
| 561 | + | ||
| 562 | + #[allow(unused_assignments)] | ||
| 563 | + let ( | ||
| 564 | + mut bd, | ||
| 565 | + mut bd_yuv, | ||
| 566 | + mut cand_extrap, | ||
| 567 | + mut anc_extrap, | ||
| 568 | + mut cand_extrap_yuv, | ||
| 569 | + mut anc_extrap_yuv, | ||
| 570 | + ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); | ||
| 571 | + let mut mine: Vec<(f64, f64, f64)>; | ||
| 572 | + let mut our_qps: [i32; 4]; | ||
| 573 | + | ||
| 574 | + for round in 0..=2u32 { | ||
| 575 | + our_qps = x265_qps.map(|q| (q + shift).clamp(1, 45)); | ||
| 576 | + mine = our_qps | ||
| 577 | + .iter() | ||
| 578 | + .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) | ||
| 579 | + .collect(); | ||
| 580 | + for (i, &qp) in our_qps.iter().enumerate() { | ||
| 581 | + let (ob, op, oy) = mine[i]; | ||
| 582 | + eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); | ||
| 583 | + } | ||
| 584 | + for (i, &qp) in x265_qps.iter().enumerate() { | ||
| 585 | + let (xb, xp, xy) = theirs[i]; | ||
| 586 | + eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); | ||
| 587 | + } | ||
| 588 | + (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | ||
| 589 | + (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = | ||
| 590 | + bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | ||
| 591 | + eprintln!( | ||
| 592 | + "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", | ||
| 593 | + qps_str(&our_qps), | ||
| 594 | + qps_str(&x265_qps), | ||
| 595 | + ); | ||
| 596 | + eprintln!( | ||
| 597 | + "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", | ||
| 598 | + qps_str(&our_qps), | ||
| 599 | + qps_str(&x265_qps), | ||
| 600 | + ); | ||
| 601 | + let aligned = cand_extrap <= EXTRAP_LIMIT | ||
| 602 | + && anc_extrap <= EXTRAP_LIMIT | ||
| 603 | + && cand_extrap_yuv <= EXTRAP_LIMIT | ||
| 604 | + && anc_extrap_yuv <= EXTRAP_LIMIT; | ||
| 605 | + if aligned || round == 2 { | ||
| 606 | + break; | ||
| 607 | + } | ||
| 608 | + // Re-estimate the shift from the geometric-mean bit ratio of the two | ||
| 609 | + // full curves, then rebuild the ladder. | ||
| 610 | + let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; | ||
| 611 | + shift += delta; | ||
| 612 | + eprintln!( | ||
| 613 | + "alignment round {}: shift {delta:+} -> {shift:+} \ | ||
| 614 | + (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", | ||
| 615 | + round + 1, | ||
| 616 | + gm(&mine) / 1e6, | ||
| 617 | + gm(&theirs) / 1e6, | ||
| 618 | + ); | ||
| 619 | + } | ||
| 537 | 620 | ||
| 538 | // A BD number over a range where the two QP ladders do not overlap is not a | 621 | // A BD number over a range where the two QP ladders do not overlap is not a |
| 539 | // measurement — the cubic is extrapolating, not interpolating. Fail loudly | 622 | // measurement — the cubic is extrapolating, not interpolating. Fail loudly |
| 540 | // with the side that is out of range instead of reporting a meaningless gap. | 623 | // with the side that is out of range instead of reporting a meaningless gap. |
| 541 | - const EXTRAP_LIMIT: f64 = 0.20; | ||
| 542 | let out_of_range = |c: f64, a: f64| { | 624 | let out_of_range = |c: f64, a: f64| { |
| 543 | let mut parts = Vec::new(); | 625 | let mut parts = Vec::new(); |
| 544 | if c > EXTRAP_LIMIT { | 626 | if c > EXTRAP_LIMIT { |