Merge branch 'lane-h264rd': transform-8x8 RD priced by full syntax bit delta and standard lambda, QP clamp removed, rd-ablation instrumentation
Browse files at this commit6 changed files +746 -110
- crates/ec-h264/Cargo.toml +4 -0
- crates/ec-h264/src/enc/cabac_enc.rs +1 -0
- crates/ec-h264/src/enc/entropy.rs +1 -0
- crates/ec-h264/src/enc/mb.rs +436 -67
- crates/ec-h264/src/enc/mod.rs +228 -20
- crates/ec-h264/tests/encode.rs +76 -23
crates/ec-h264/Cargo.tomlmodified+4 -0
| @@ -6,6 +6,10 @@ edition.workspace = true | |||
| 6 | license.workspace = true | 6 | license.workspace = true |
| 7 | authors.workspace = true | 7 | authors.workspace = true |
| 8 | 8 | ||
| 9 | +[features] | ||
| 10 | +# Internal-only RD experiment switches, compiled only by the measurement harness. | ||
| 11 | +rd-ablation = [] | ||
| 12 | + | ||
| 9 | [dependencies] | 13 | [dependencies] |
| 10 | ec-core = { workspace = true } | 14 | ec-core = { workspace = true } |
| 11 | ec-h264-syntax = { workspace = true } | 15 | ec-h264-syntax = { workspace = true } |
crates/ec-h264/src/enc/cabac_enc.rsmodified+1 -0
| @@ -30,6 +30,7 @@ use crate::entropy::{ | |||
| 30 | BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo, | 30 | BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo, |
| 31 | }; | 31 | }; |
| 32 | 32 | ||
| 33 | +#[derive(Clone)] | ||
| 33 | /// The arithmetic encoder of 9.3.4 plus the context state. | 34 | /// The arithmetic encoder of 9.3.4 plus the context state. |
| 34 | pub(crate) struct CabacEnc { | 35 | pub(crate) struct CabacEnc { |
| 35 | w: BitWriter, | 36 | w: BitWriter, |
crates/ec-h264/src/enc/entropy.rsmodified+1 -0
| @@ -19,6 +19,7 @@ pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] { | |||
| 19 | std::array::from_fn(|i| c8[4 * i + j]) | 19 | std::array::from_fn(|i| c8[4 * i + j]) |
| 20 | } | 20 | } |
| 21 | 21 | ||
| 22 | +#[derive(Clone)] | ||
| 22 | pub(crate) enum EncEntropy { | 23 | pub(crate) enum EncEntropy { |
| 23 | Cavlc { | 24 | Cavlc { |
| 24 | w: BitWriter, | 25 | w: BitWriter, |
crates/ec-h264/src/enc/mb.rsmodified+436 -67
| @@ -16,31 +16,34 @@ use ec_h264_syntax::SliceType; | |||
| 16 | use wide::i16x16; | 16 | use wide::i16x16; |
| 17 | 17 | ||
| 18 | use crate::decoder::{ | 18 | use crate::decoder::{ |
| 19 | - MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, | 19 | + chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors, |
| 20 | }; | 20 | }; |
| 21 | -use crate::dpb::{BLK_SKIP, Picture}; | 21 | +use crate::dpb::{Picture, BLK_SKIP}; |
| 22 | use crate::entropy::{ | 22 | use crate::entropy::{ |
| 23 | - BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, | 23 | + BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, |
| 24 | - MbCtx, MbInfo, | 24 | + FLAG_TRANS8X8, |
| 25 | }; | 25 | }; |
| 26 | -use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; | 26 | +use crate::inter::{integer_origin, mc_chroma, mc_luma, RefPlane}; |
| 27 | -use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; | 27 | +use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx}; |
| 28 | use crate::pred::{ | 28 | use crate::pred::{ |
| 29 | - PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, | 29 | + add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8, |
| 30 | - pred_chroma_8x8, | 30 | + pred_chroma_8x8, PlaneWindow, |
| 31 | }; | 31 | }; |
| 32 | use crate::tables::{BLK4_POS, CHROMA_QP}; | 32 | use crate::tables::{BLK4_POS, CHROMA_QP}; |
| 33 | use crate::transform::{ | 33 | use crate::transform::{ |
| 34 | - LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8, | 34 | + chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4, |
| 35 | - inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, | 35 | + inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4, |
| 36 | - unzigzag_ac15, | 36 | + LevelScale8x8, |
| 37 | }; | 37 | }; |
| 38 | 38 | ||
| 39 | -use super::entropy::{EncEntropy, sub_block_4x4}; | ||
| 40 | use super::quant::{ | 39 | use super::quant::{ |
| 41 | forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8, | 40 | forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8, |
| 42 | quant_chroma_dc, quant_luma_dc, | 41 | quant_chroma_dc, quant_luma_dc, |
| 43 | }; | 42 | }; |
| 43 | +use super::{ | ||
| 44 | + entropy::{sub_block_4x4, EncEntropy}, | ||
| 45 | + lambda_ssd, | ||
| 46 | +}; | ||
| 44 | 47 | ||
| 45 | /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are | 48 | /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are |
| 46 | /// the two edith actually picks between. | 49 | /// the two edith actually picks between. |
| @@ -75,12 +78,25 @@ pub(crate) struct MbEnc<'a> { | |||
| 75 | pub qp: i32, | 78 | pub qp: i32, |
| 76 | /// What rate control wants this macroblock coded at. | 79 | /// What rate control wants this macroblock coded at. |
| 77 | pub target_qp: i32, | 80 | pub target_qp: i32, |
| 78 | - /// Lagrangian multiplier in the SATD domain. | 81 | + /// Lagrangian multiplier; it is in the squared-error domain when 8x8 |
| 79 | - pub lambda: i32, | 82 | + /// transform decisions are enabled. |
| 83 | + pub lambda: f64, | ||
| 84 | + /// Whether `lambda` is the standard squared-error multiplier. | ||
| 85 | + pub lambda_standard: bool, | ||
| 86 | + /// Extra rate saving an 8x8 trial must buy before it may replace 4x4. | ||
| 87 | + pub t8x8_margin_bits: f64, | ||
| 80 | pub preset: Preset, | 88 | pub preset: Preset, |
| 81 | /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must | 89 | /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must |
| 82 | /// be written for every eligible macroblock (7.3.5). | 90 | /// be written for every eligible macroblock (7.3.5). |
| 83 | pub transform_8x8: bool, | 91 | pub transform_8x8: bool, |
| 92 | + /// Whether intra macroblocks may select 8x8. The PPS can remain enabled | ||
| 93 | + /// while an ablation measures the classes independently. | ||
| 94 | + pub transform_8x8_intra: bool, | ||
| 95 | + /// Whether inter macroblocks may select 8x8. | ||
| 96 | + pub transform_8x8_inter: bool, | ||
| 97 | + /// Whether the ablation restricts 8x8 eligibility to even macroblock | ||
| 98 | + /// rows; odd rows then code exactly as they would with 8x8 disabled. | ||
| 99 | + pub transform_8x8_roweven: bool, | ||
| 84 | pub ls: LevelScale4x4, | 100 | pub ls: LevelScale4x4, |
| 85 | pub ls8: LevelScale8x8, | 101 | pub ls8: LevelScale8x8, |
| 86 | /// Neighbourhood of the macroblock being written (CABAC). | 102 | /// Neighbourhood of the macroblock being written (CABAC). |
| @@ -92,7 +108,20 @@ pub(crate) struct MbEnc<'a> { | |||
| 92 | pub qp_delta_inc: u8, | 108 | pub qp_delta_inc: u8, |
| 93 | } | 109 | } |
| 94 | 110 | ||
| 111 | +impl MbEnc<'_> { | ||
| 112 | + /// Intra 8x8 eligibility of macroblock row `mb_y`. | ||
| 113 | + fn t8x8_intra(&self, mb_y: usize) -> bool { | ||
| 114 | + self.transform_8x8_intra && (mb_y % 2 == 0 || !self.transform_8x8_roweven) | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + /// Inter 8x8 eligibility of macroblock row `mb_y`. | ||
| 118 | + fn t8x8_inter(&self, mb_y: usize) -> bool { | ||
| 119 | + self.transform_8x8_inter && (mb_y % 2 == 0 || !self.transform_8x8_roweven) | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 95 | /// Quantised levels of one macroblock, scan order per block. | 123 | /// Quantised levels of one macroblock, scan order per block. |
| 124 | +#[derive(Clone)] | ||
| 96 | struct Levels { | 125 | struct Levels { |
| 97 | /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. | 126 | /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. |
| 98 | luma: [[i32; 16]; 16], | 127 | luma: [[i32; 16]; 16], |
| @@ -276,6 +305,16 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { | |||
| 276 | ] | 305 | ] |
| 277 | } | 306 | } |
| 278 | 307 | ||
| 308 | +#[inline] | ||
| 309 | +fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { | ||
| 310 | + let lambda = if e.lambda_standard { | ||
| 311 | + e.lambda.sqrt() | ||
| 312 | + } else { | ||
| 313 | + e.lambda | ||
| 314 | + }; | ||
| 315 | + (lambda * bits).round() as i32 | ||
| 316 | +} | ||
| 317 | + | ||
| 279 | /// Code one macroblock: decide its mode, reconstruct it into `pic` and write | 318 | /// Code one macroblock: decide its mode, reconstruct it into `pic` and write |
| 280 | /// its syntax into `w`. | 319 | /// its syntax into `w`. |
| 281 | pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) { | 320 | pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) { |
| @@ -323,7 +362,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | |||
| 323 | let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); | 362 | let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); |
| 324 | let go_intra = match &inter { | 363 | let go_intra = match &inter { |
| 325 | None => true, | 364 | None => true, |
| 326 | - Some(i) => intra_cost.best() + e.lambda * 8 < i.cost, | 365 | + Some(i) => intra_cost.best() + motion_rate(e, 8.0) < i.cost, |
| 327 | }; | 366 | }; |
| 328 | 367 | ||
| 329 | if go_intra { | 368 | if go_intra { |
| @@ -502,9 +541,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter | |||
| 502 | // which is what a search can afford; the winner is re-costed on SATD | 541 | // which is what a search can afford; the winner is re-costed on SATD |
| 503 | // because the intra candidates are SATD and the two scales differ. | 542 | // because the intra candidates are SATD and the two scales differ. |
| 504 | let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { | 543 | let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { |
| 505 | - let bits = e.lambda | 544 | + let bits = motion_rate( |
| 506 | - * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) | 545 | + e, |
| 507 | - / 2; | 546 | + f64::from(se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) |
| 547 | + / 2.0, | ||
| 548 | + ); | ||
| 508 | if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { | 549 | if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { |
| 509 | let o = integer_origin( | 550 | let o = integer_origin( |
| 510 | &plane, | 551 | &plane, |
| @@ -592,7 +633,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter | |||
| 592 | let skip_cost = { | 633 | let skip_cost = { |
| 593 | let mut buf = [0u8; 256]; | 634 | let mut buf = [0u8; 256]; |
| 594 | mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf); | 635 | mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf); |
| 595 | - satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - e.lambda * 4 | 636 | + satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 4.0) |
| 596 | }; | 637 | }; |
| 597 | 638 | ||
| 598 | let mut best = (PShape::Whole, [mv16, mv16], cost16); | 639 | let mut best = (PShape::Whole, [mv16, mv16], cost16); |
| @@ -607,7 +648,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter | |||
| 607 | // time. That is a Balanced trade, not a Fast one. | 648 | // time. That is a Balanced trade, not a Fast one. |
| 608 | if e.preset == Preset::Balanced && cost16 > 16 * 16 { | 649 | if e.preset == Preset::Balanced && cost16 > 16 * 16 { |
| 609 | for shape in [PShape::Horizontal, PShape::Vertical] { | 650 | for shape in [PShape::Horizontal, PShape::Vertical] { |
| 610 | - let mut total = e.lambda * 6; // the partition's own signalling | 651 | + let mut total = motion_rate(e, 6.0); // the partition's own signalling |
| 611 | let mut mvs = [[0i16; 2]; 2]; | 652 | let mut mvs = [[0i16; 2]; 2]; |
| 612 | for part in 0..2 { | 653 | for part in 0..2 { |
| 613 | let ((bx, by), (w, h)) = shape.geometry(part); | 654 | let ((bx, by), (w, h)) = shape.geometry(part); |
| @@ -671,7 +712,14 @@ fn code_luma_4x4( | |||
| 671 | // half of rate-distortion optimised quantisation, and the half that | 712 | // half of rate-distortion optimised quantisation, and the half that |
| 672 | // pays. Intra blocks are left alone: their reconstruction is what the | 713 | // pays. Intra blocks are left alone: their reconstruction is what the |
| 673 | // next block in the macroblock predicts from. | 714 | // next block in the macroblock predicts from. |
| 674 | - if !intra && !worth_coding(&source, &resid, &lv.luma[blk], qp) { | 715 | + if !intra |
| 716 | + && !worth_coding( | ||
| 717 | + &source, | ||
| 718 | + &resid, | ||
| 719 | + &lv.luma[blk], | ||
| 720 | + zero_block_lambda(e, qp, e.t8x8_inter(mb_y)), | ||
| 721 | + ) | ||
| 722 | + { | ||
| 675 | lv.luma[blk] = [0; 16]; | 723 | lv.luma[blk] = [0; 16]; |
| 676 | lv.luma_nz[blk] = 0; | 724 | lv.luma_nz[blk] = 0; |
| 677 | continue; | 725 | continue; |
| @@ -691,9 +739,17 @@ fn code_luma_4x4( | |||
| 691 | /// without costing camera content. | 739 | /// without costing camera content. |
| 692 | const ZERO_BLOCK_LAMBDA: f64 = 0.4; | 740 | const ZERO_BLOCK_LAMBDA: f64 = 0.4; |
| 693 | 741 | ||
| 742 | +fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 { | ||
| 743 | + if transform_8x8 { | ||
| 744 | + e.lambda | ||
| 745 | + } else { | ||
| 746 | + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) | ||
| 747 | + } | ||
| 748 | +} | ||
| 749 | + | ||
| 694 | /// The rate-distortion test behind the per-block zero decision: coding the | 750 | /// The rate-distortion test behind the per-block zero decision: coding the |
| 695 | /// block has to buy more squared error than its bits are worth. | 751 | /// block has to buy more squared error than its bits are worth. |
| 696 | -fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool { | 752 | +fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool { |
| 697 | let mut ssd_zero = 0i64; | 753 | let mut ssd_zero = 0i64; |
| 698 | let mut ssd_coded = 0i64; | 754 | let mut ssd_coded = 0i64; |
| 699 | for i in 0..source.len() { | 755 | for i in 0..source.len() { |
| @@ -702,8 +758,7 @@ fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool | |||
| 702 | ssd_zero += z * z; | 758 | ssd_zero += z * z; |
| 703 | ssd_coded += c * c; | 759 | ssd_coded += c * c; |
| 704 | } | 760 | } |
| 705 | - ssd_coded as f64 + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) * (block_bits(levels) as f64) | 761 | + ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64 |
| 706 | - < ssd_zero as f64 | ||
| 707 | } | 762 | } |
| 708 | 763 | ||
| 709 | /// Predict and code the luma of an Intra_16x16 macroblock. | 764 | /// Predict and code the luma of an Intra_16x16 macroblock. |
| @@ -847,7 +902,20 @@ fn code_chroma( | |||
| 847 | dequant_4x4(&mut raster, &e.ls, qp_c, true); | 902 | dequant_4x4(&mut raster, &e.ls, qp_c, true); |
| 848 | let mut resid = [0i32; 16]; | 903 | let mut resid = [0i32; 16]; |
| 849 | inverse_transform_4x4(&raster, &mut resid); | 904 | inverse_transform_4x4(&raster, &mut resid); |
| 850 | - if !worth_coding(&source, &resid, &ac[comp][blk], qp_c) { | 905 | + if !worth_coding( |
| 906 | + &source, | ||
| 907 | + &resid, | ||
| 908 | + &ac[comp][blk], | ||
| 909 | + zero_block_lambda( | ||
| 910 | + e, | ||
| 911 | + qp_c, | ||
| 912 | + if intra { | ||
| 913 | + e.t8x8_intra(mb_y) | ||
| 914 | + } else { | ||
| 915 | + e.t8x8_inter(mb_y) | ||
| 916 | + }, | ||
| 917 | + ), | ||
| 918 | + ) { | ||
| 851 | ac[comp][blk] = [0; 16]; | 919 | ac[comp][blk] = [0; 16]; |
| 852 | nz = 0; | 920 | nz = 0; |
| 853 | } | 921 | } |
| @@ -1019,7 +1087,7 @@ fn code_intra_4x4( | |||
| 1019 | } | 1087 | } |
| 1020 | pred_4x4(mode, &n, &mut p); | 1088 | pred_4x4(mode, &n, &mut p); |
| 1021 | let bits = if mode == predicted { 1 } else { 4 }; | 1089 | let bits = if mode == predicted { 1 } else { 4 }; |
| 1022 | - let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; | 1090 | + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits)); |
| 1023 | if c < best.0 { | 1091 | if c < best.0 { |
| 1024 | best = (c, mode); | 1092 | best = (c, mode); |
| 1025 | } | 1093 | } |
| @@ -1101,7 +1169,14 @@ fn code_block_8x8( | |||
| 1101 | dequant_8x8(&mut raster, &e.ls8, qp); | 1169 | dequant_8x8(&mut raster, &e.ls8, qp); |
| 1102 | let mut resid = [0i32; 64]; | 1170 | let mut resid = [0i32; 64]; |
| 1103 | inverse_transform_8x8(&raster, &mut resid); | 1171 | inverse_transform_8x8(&raster, &mut resid); |
| 1104 | - if !intra && !worth_coding(&d, &resid, out, qp) { | 1172 | + if !intra |
| 1173 | + && !worth_coding( | ||
| 1174 | + &d, | ||
| 1175 | + &resid, | ||
| 1176 | + out, | ||
| 1177 | + zero_block_lambda(e, qp, e.transform_8x8_inter), | ||
| 1178 | + ) | ||
| 1179 | + { | ||
| 1105 | *out = [0; 64]; | 1180 | *out = [0; 64]; |
| 1106 | return 0; | 1181 | return 0; |
| 1107 | } | 1182 | } |
| @@ -1140,7 +1215,7 @@ fn code_intra_8x8( | |||
| 1140 | } | 1215 | } |
| 1141 | pred_8x8(mode, &n, &mut p); | 1216 | pred_8x8(mode, &n, &mut p); |
| 1142 | let bits = if mode == predicted { 1 } else { 4 }; | 1217 | let bits = if mode == predicted { 1 } else { 4 }; |
| 1143 | - let mut c = e.lambda * bits; | 1218 | + let mut c = motion_rate(e, f64::from(bits)); |
| 1144 | for q in 0..4 { | 1219 | for q in 0..4 { |
| 1145 | let (ox, oy) = ((q % 2) * 4, (q / 2) * 4); | 1220 | let (ox, oy) = ((q % 2) * 4, (q / 2) * 4); |
| 1146 | c += satd4(&e.src.y, e.src.stride, x + ox, y + oy, &p[oy * 8 + ox..], 8); | 1221 | c += satd4(&e.src.y, e.src.stride, x + ox, y + oy, &p[oy * 8 + ox..], 8); |
| @@ -1220,13 +1295,9 @@ fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { | |||
| 1220 | } | 1295 | } |
| 1221 | } | 1296 | } |
| 1222 | 1297 | ||
| 1223 | -/// Bits the luma residual and the mode signalling of an intra macroblock cost, | 1298 | +fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { |
| 1224 | -/// to the accuracy the mode decision needs. | ||
| 1225 | -fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { | ||
| 1226 | let mut bits = estimate_luma_bits(lv); | 1299 | let mut bits = estimate_luma_bits(lv); |
| 1227 | match i4 { | 1300 | match i4 { |
| 1228 | - // Sixteen (or four) mode signals plus the coded_block_pattern the | ||
| 1229 | - // 16x16 form derives from its macroblock type instead. | ||
| 1230 | Some((modes, pred)) => { | 1301 | Some((modes, pred)) => { |
| 1231 | bits += 6; | 1302 | bits += 6; |
| 1232 | for blk in 0..modes.len() { | 1303 | for blk in 0..modes.len() { |
| @@ -1238,6 +1309,256 @@ fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { | |||
| 1238 | bits | 1309 | bits |
| 1239 | } | 1310 | } |
| 1240 | 1311 | ||
| 1312 | +fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 { | ||
| 1313 | + let mut probe = w.clone(); | ||
| 1314 | + let before = probe.bit_len(); | ||
| 1315 | + write(&mut probe); | ||
| 1316 | + (probe.bit_len() - before) as i64 | ||
| 1317 | +} | ||
| 1318 | + | ||
| 1319 | +fn cost_luma_nz_pair( | ||
| 1320 | + pic: &Picture, | ||
| 1321 | + nbr: &MbNeighbors, | ||
| 1322 | + local: &[u8; 16], | ||
| 1323 | + bx0: usize, | ||
| 1324 | + by0: usize, | ||
| 1325 | + bx: usize, | ||
| 1326 | + by: usize, | ||
| 1327 | +) -> (Option<u8>, Option<u8>) { | ||
| 1328 | + let w4 = pic.mb_w * 4; | ||
| 1329 | + let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true }; | ||
| 1330 | + let top_avail = if by.is_multiple_of(4) { nbr.b } else { true }; | ||
| 1331 | + let left = (left_avail && bx > 0).then(|| { | ||
| 1332 | + if bx > bx0 { | ||
| 1333 | + local[(by - by0) * 4 + (bx - bx0 - 1)] | ||
| 1334 | + } else { | ||
| 1335 | + pic.nz_y[by * w4 + bx - 1] | ||
| 1336 | + } | ||
| 1337 | + }); | ||
| 1338 | + let top = (top_avail && by > 0).then(|| { | ||
| 1339 | + if by > by0 { | ||
| 1340 | + local[(by - by0 - 1) * 4 + (bx - bx0)] | ||
| 1341 | + } else { | ||
| 1342 | + pic.nz_y[(by - 1) * w4 + bx] | ||
| 1343 | + } | ||
| 1344 | + }); | ||
| 1345 | + (left, top) | ||
| 1346 | +} | ||
| 1347 | + | ||
| 1348 | +fn write_luma_for_cost( | ||
| 1349 | + pic: &Picture, | ||
| 1350 | + nbr: &MbNeighbors, | ||
| 1351 | + w: &mut EncEntropy, | ||
| 1352 | + mb_x: usize, | ||
| 1353 | + mb_y: usize, | ||
| 1354 | + lv: &Levels, | ||
| 1355 | + is_i16: bool, | ||
| 1356 | +) { | ||
| 1357 | + let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 1358 | + let mut nz = [0u8; 16]; | ||
| 1359 | + if is_i16 { | ||
| 1360 | + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0); | ||
| 1361 | + nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); | ||
| 1362 | + } | ||
| 1363 | + if lv.trans8 { | ||
| 1364 | + for blk8 in 0..4 { | ||
| 1365 | + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); | ||
| 1366 | + if lv.cbp_luma & (1 << blk8) == 0 { | ||
| 1367 | + continue; | ||
| 1368 | + } | ||
| 1369 | + if w.is_cabac() { | ||
| 1370 | + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); | ||
| 1371 | + for dy in 0..2 { | ||
| 1372 | + let base = (by - by0 + dy) * 4 + bx - bx0; | ||
| 1373 | + nz[base..base + 2].fill(tc.min(16)); | ||
| 1374 | + } | ||
| 1375 | + } else { | ||
| 1376 | + for i4 in 0..4 { | ||
| 1377 | + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; | ||
| 1378 | + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); | ||
| 1379 | + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy); | ||
| 1380 | + let sub = sub_block_4x4(&lv.luma8[blk8], i4); | ||
| 1381 | + nz[(sy - by0) * 4 + (sx - bx0)] = | ||
| 1382 | + w.residual_block(&sub, BlockCat::Luma4x4, na, nb); | ||
| 1383 | + } | ||
| 1384 | + } | ||
| 1385 | + } | ||
| 1386 | + return; | ||
| 1387 | + } | ||
| 1388 | + for blk in 0..16 { | ||
| 1389 | + let (dx, dy) = BLK4_POS[blk]; | ||
| 1390 | + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | ||
| 1391 | + let group = 1 << (blk >> 2); | ||
| 1392 | + let coded_block = if is_i16 { | ||
| 1393 | + lv.cbp_luma != 0 | ||
| 1394 | + } else { | ||
| 1395 | + lv.cbp_luma & group != 0 | ||
| 1396 | + }; | ||
| 1397 | + if coded_block { | ||
| 1398 | + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by); | ||
| 1399 | + let (levels, cat) = if is_i16 { | ||
| 1400 | + (&lv.luma[blk][..15], BlockCat::LumaAc) | ||
| 1401 | + } else { | ||
| 1402 | + (&lv.luma[blk][..16], BlockCat::Luma4x4) | ||
| 1403 | + }; | ||
| 1404 | + nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb); | ||
| 1405 | + } | ||
| 1406 | + } | ||
| 1407 | +} | ||
| 1408 | +fn cost_chroma_nz_pair( | ||
| 1409 | + pic: &Picture, | ||
| 1410 | + nbr: &MbNeighbors, | ||
| 1411 | + local: &[[u8; 4]; 2], | ||
| 1412 | + comp: usize, | ||
| 1413 | + cx0: usize, | ||
| 1414 | + cy0: usize, | ||
| 1415 | + cx: usize, | ||
| 1416 | + cy: usize, | ||
| 1417 | +) -> (Option<u8>, Option<u8>) { | ||
| 1418 | + let w2 = pic.mb_w * 2; | ||
| 1419 | + let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true }; | ||
| 1420 | + let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true }; | ||
| 1421 | + let left = (left_avail && cx > 0).then(|| { | ||
| 1422 | + if cx > cx0 { | ||
| 1423 | + local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)] | ||
| 1424 | + } else { | ||
| 1425 | + pic.nz_c[comp][cy * w2 + cx - 1] | ||
| 1426 | + } | ||
| 1427 | + }); | ||
| 1428 | + let top = (top_avail && cy > 0).then(|| { | ||
| 1429 | + if cy > cy0 { | ||
| 1430 | + local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)] | ||
| 1431 | + } else { | ||
| 1432 | + pic.nz_c[comp][(cy - 1) * w2 + cx] | ||
| 1433 | + } | ||
| 1434 | + }); | ||
| 1435 | + (left, top) | ||
| 1436 | +} | ||
| 1437 | + | ||
| 1438 | +fn write_chroma_for_cost( | ||
| 1439 | + pic: &Picture, | ||
| 1440 | + nbr: &MbNeighbors, | ||
| 1441 | + w: &mut EncEntropy, | ||
| 1442 | + mb_x: usize, | ||
| 1443 | + mb_y: usize, | ||
| 1444 | + lv: &Levels, | ||
| 1445 | +) { | ||
| 1446 | + if lv.cbp_chroma != 0 { | ||
| 1447 | + for comp in 0..2 { | ||
| 1448 | + w.residual_block( | ||
| 1449 | + &lv.chroma_dc[comp][..4], | ||
| 1450 | + BlockCat::ChromaDc(comp as u8), | ||
| 1451 | + None, | ||
| 1452 | + None, | ||
| 1453 | + ); | ||
| 1454 | + } | ||
| 1455 | + } | ||
| 1456 | + if lv.cbp_chroma != 2 { | ||
| 1457 | + return; | ||
| 1458 | + } | ||
| 1459 | + let (cx0, cy0) = (mb_x * 2, mb_y * 2); | ||
| 1460 | + let mut nz = [[0u8; 4]; 2]; | ||
| 1461 | + for comp in 0..2 { | ||
| 1462 | + for blk in 0..4 { | ||
| 1463 | + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); | ||
| 1464 | + let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy); | ||
| 1465 | + nz[comp][blk] = | ||
| 1466 | + w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb); | ||
| 1467 | + } | ||
| 1468 | + } | ||
| 1469 | +} | ||
| 1470 | + | ||
| 1471 | +fn intra_mb_bits( | ||
| 1472 | + pic: &Picture, | ||
| 1473 | + e: &MbEnc<'_>, | ||
| 1474 | + w: &EncEntropy, | ||
| 1475 | + mb_addr: usize, | ||
| 1476 | + nbr: &MbNeighbors, | ||
| 1477 | + lv: &Levels, | ||
| 1478 | + i4: Option<(&[u8], &[u8])>, | ||
| 1479 | + i16_mode: u8, | ||
| 1480 | + chroma_mode: u8, | ||
| 1481 | +) -> i64 { | ||
| 1482 | + let use_i4 = i4.is_some(); | ||
| 1483 | + let p_slice = e.slice_type == SliceType::P; | ||
| 1484 | + let offset = if p_slice { 5 } else { 0 }; | ||
| 1485 | + let intra_type = if use_i4 { | ||
| 1486 | + 0 | ||
| 1487 | + } else { | ||
| 1488 | + 1 + u32::from(i16_mode) | ||
| 1489 | + + 4 * u32::from(lv.cbp_chroma) | ||
| 1490 | + + if lv.cbp_luma != 0 { 12 } else { 0 } | ||
| 1491 | + }; | ||
| 1492 | + entropy_bits(w, |cw| { | ||
| 1493 | + cw.begin_mb(&e.mb_ctx); | ||
| 1494 | + cw.coded_mb(p_slice, e.skip_inc); | ||
| 1495 | + cw.set_intra(true); | ||
| 1496 | + cw.mb_type(p_slice, intra_type + offset); | ||
| 1497 | + if let Some((modes, pred)) = i4 { | ||
| 1498 | + if e.transform_8x8 { | ||
| 1499 | + cw.transform_size_8x8_flag(lv.trans8); | ||
| 1500 | + } | ||
| 1501 | + for blk in 0..modes.len() { | ||
| 1502 | + let rem = if modes[blk] == pred[blk] { | ||
| 1503 | + None | ||
| 1504 | + } else if modes[blk] > pred[blk] { | ||
| 1505 | + Some(modes[blk] - 1) | ||
| 1506 | + } else { | ||
| 1507 | + Some(modes[blk]) | ||
| 1508 | + }; | ||
| 1509 | + cw.intra4x4_pred_mode(rem); | ||
| 1510 | + } | ||
| 1511 | + } | ||
| 1512 | + cw.intra_chroma_pred_mode(chroma_mode); | ||
| 1513 | + if use_i4 { | ||
| 1514 | + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); | ||
| 1515 | + } | ||
| 1516 | + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4; | ||
| 1517 | + if coded { | ||
| 1518 | + cw.mb_qp_delta(e.target_qp - e.qp); | ||
| 1519 | + } | ||
| 1520 | + let mb_x = mb_addr % pic.mb_w; | ||
| 1521 | + let mb_y = mb_addr / pic.mb_w; | ||
| 1522 | + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4); | ||
| 1523 | + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); | ||
| 1524 | + }) | ||
| 1525 | +} | ||
| 1526 | + | ||
| 1527 | +fn inter_mb_bits( | ||
| 1528 | + pic: &Picture, | ||
| 1529 | + e: &MbEnc<'_>, | ||
| 1530 | + w: &EncEntropy, | ||
| 1531 | + mb_addr: usize, | ||
| 1532 | + nbr: &MbNeighbors, | ||
| 1533 | + shape: PShape, | ||
| 1534 | + mvd: &[[i16; 2]; 2], | ||
| 1535 | + inc: &[[usize; 2]; 2], | ||
| 1536 | + lv: &Levels, | ||
| 1537 | +) -> i64 { | ||
| 1538 | + entropy_bits(w, |cw| { | ||
| 1539 | + cw.begin_mb(&e.mb_ctx); | ||
| 1540 | + cw.coded_mb(true, e.skip_inc); | ||
| 1541 | + cw.set_intra(false); | ||
| 1542 | + cw.mb_type(true, shape.mb_type()); | ||
| 1543 | + for part in 0..shape.parts() { | ||
| 1544 | + for comp in 0..2 { | ||
| 1545 | + cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); | ||
| 1546 | + } | ||
| 1547 | + } | ||
| 1548 | + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); | ||
| 1549 | + if lv.cbp_luma != 0 && e.transform_8x8 { | ||
| 1550 | + cw.transform_size_8x8_flag(lv.trans8); | ||
| 1551 | + } | ||
| 1552 | + if lv.cbp_luma != 0 || lv.cbp_chroma != 0 { | ||
| 1553 | + cw.mb_qp_delta(e.target_qp - e.qp); | ||
| 1554 | + let mb_x = mb_addr % pic.mb_w; | ||
| 1555 | + let mb_y = mb_addr / pic.mb_w; | ||
| 1556 | + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false); | ||
| 1557 | + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); | ||
| 1558 | + } | ||
| 1559 | + }) | ||
| 1560 | +} | ||
| 1561 | + | ||
| 1241 | /// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real | 1562 | /// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real |
| 1242 | /// rate and real distortion. | 1563 | /// rate and real distortion. |
| 1243 | /// | 1564 | /// |
| @@ -1260,19 +1581,37 @@ fn encode_intra_mb( | |||
| 1260 | let (bx0, by0) = (mb_x * 4, mb_y * 4); | 1581 | let (bx0, by0) = (mb_x * 4, mb_y * 4); |
| 1261 | let qp = e.target_qp; | 1582 | let qp = e.target_qp; |
| 1262 | write_intra_mb(pic, mb_x, mb_y); | 1583 | write_intra_mb(pic, mb_x, mb_y); |
| 1263 | - let mut lv = Levels::default(); | 1584 | + let mut lv: Levels; |
| 1264 | let mut modes = [2u8; 16]; | 1585 | let mut modes = [2u8; 16]; |
| 1265 | let mut pred_modes = [2u8; 16]; | 1586 | let mut pred_modes = [2u8; 16]; |
| 1266 | let mut modes8 = [2u8; 4]; | 1587 | let mut modes8 = [2u8; 4]; |
| 1267 | let mut pred_modes8 = [2u8; 4]; | 1588 | let mut pred_modes8 = [2u8; 4]; |
| 1268 | let mut use_i4 = false; | 1589 | let mut use_i4 = false; |
| 1590 | + let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); | ||
| 1591 | + let mut chroma_lv = Levels::default(); | ||
| 1592 | + code_chroma(pic, e, mb_x, mb_y, qp, true, &mut chroma_lv); | ||
| 1269 | let mut use_i8 = false; | 1593 | let mut use_i8 = false; |
| 1270 | 1594 | ||
| 1271 | if cost.allow_i4 { | 1595 | if cost.allow_i4 { |
| 1272 | - let mut lv4 = Levels::default(); | 1596 | + let mut lv4 = chroma_lv.clone(); |
| 1273 | let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); | 1597 | let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); |
| 1274 | - let cost4 = ssd_luma(pic, e, mb_x, mb_y) as f64 | 1598 | + let cost4 = if e.t8x8_intra(mb_y) { |
| 1275 | - + lambda_ssd(qp) * intra_bits(&lv4, Some((&m4, &p4))) as f64; | 1599 | + let bits = intra_mb_bits( |
| 1600 | + pic, | ||
| 1601 | + e, | ||
| 1602 | + w, | ||
| 1603 | + mb_addr, | ||
| 1604 | + &nbr, | ||
| 1605 | + &lv4, | ||
| 1606 | + Some((&m4, &p4)), | ||
| 1607 | + cost.i16_mode, | ||
| 1608 | + chroma_mode, | ||
| 1609 | + ); | ||
| 1610 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 | ||
| 1611 | + } else { | ||
| 1612 | + ssd_luma(pic, e, mb_x, mb_y) as f64 | ||
| 1613 | + + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64 | ||
| 1614 | + }; | ||
| 1276 | let mut recon4 = [0u8; 256]; | 1615 | let mut recon4 = [0u8; 256]; |
| 1277 | save_luma(pic, mb_x, mb_y, &mut recon4); | 1616 | save_luma(pic, mb_x, mb_y, &mut recon4); |
| 1278 | let mut modes4 = [2u8; 16]; | 1617 | let mut modes4 = [2u8; 16]; |
| @@ -1282,25 +1621,52 @@ fn encode_intra_mb( | |||
| 1282 | } | 1621 | } |
| 1283 | 1622 | ||
| 1284 | // Intra_8x8 on the same terms, when the PPS allows it. | 1623 | // Intra_8x8 on the same terms, when the PPS allows it. |
| 1285 | - let mut lv8 = Levels::default(); | 1624 | + let mut lv8 = chroma_lv.clone(); |
| 1286 | let mut recon8 = [0u8; 256]; | 1625 | let mut recon8 = [0u8; 256]; |
| 1287 | - let cost8 = if e.transform_8x8 { | 1626 | + let cost8 = if e.t8x8_intra(mb_y) { |
| 1288 | let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8); | 1627 | let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8); |
| 1289 | modes8 = m8; | 1628 | modes8 = m8; |
| 1290 | pred_modes8 = p8; | 1629 | pred_modes8 = p8; |
| 1291 | save_luma(pic, mb_x, mb_y, &mut recon8); | 1630 | save_luma(pic, mb_x, mb_y, &mut recon8); |
| 1292 | - ssd_luma(pic, e, mb_x, mb_y) as f64 | 1631 | + let bits = intra_mb_bits( |
| 1293 | - + lambda_ssd(qp) * intra_bits(&lv8, Some((&m8, &p8))) as f64 | 1632 | + pic, |
| 1633 | + e, | ||
| 1634 | + w, | ||
| 1635 | + mb_addr, | ||
| 1636 | + &nbr, | ||
| 1637 | + &lv8, | ||
| 1638 | + Some((&m8, &p8)), | ||
| 1639 | + cost.i16_mode, | ||
| 1640 | + chroma_mode, | ||
| 1641 | + ); | ||
| 1642 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 | ||
| 1294 | } else { | 1643 | } else { |
| 1295 | f64::INFINITY | 1644 | f64::INFINITY |
| 1296 | }; | 1645 | }; |
| 1297 | 1646 | ||
| 1298 | - let mut lv16 = Levels::default(); | 1647 | + let mut lv16 = chroma_lv; |
| 1299 | code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); | 1648 | code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); |
| 1300 | - let cost16 = | 1649 | + let cost16 = if e.t8x8_intra(mb_y) { |
| 1301 | - ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64; | 1650 | + let bits = intra_mb_bits( |
| 1651 | + pic, | ||
| 1652 | + e, | ||
| 1653 | + w, | ||
| 1654 | + mb_addr, | ||
| 1655 | + &nbr, | ||
| 1656 | + &lv16, | ||
| 1657 | + None, | ||
| 1658 | + cost.i16_mode, | ||
| 1659 | + chroma_mode, | ||
| 1660 | + ); | ||
| 1661 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 | ||
| 1662 | + } else { | ||
| 1663 | + ssd_luma(pic, e, mb_x, mb_y) as f64 | ||
| 1664 | + + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 | ||
| 1665 | + }; | ||
| 1302 | 1666 | ||
| 1303 | - if cost8 <= cost4 && cost8 <= cost16 { | 1667 | + if cost8 + e.lambda * e.t8x8_margin_bits <= cost4 |
| 1668 | + && cost8 + e.lambda * e.t8x8_margin_bits <= cost16 | ||
| 1669 | + { | ||
| 1304 | use_i4 = true; | 1670 | use_i4 = true; |
| 1305 | use_i8 = true; | 1671 | use_i8 = true; |
| 1306 | restore_luma(pic, mb_x, mb_y, &recon8); | 1672 | restore_luma(pic, mb_x, mb_y, &recon8); |
| @@ -1325,12 +1691,10 @@ fn encode_intra_mb( | |||
| 1325 | lv = lv16; | 1691 | lv = lv16; |
| 1326 | } | 1692 | } |
| 1327 | } else { | 1693 | } else { |
| 1694 | + lv = chroma_lv; | ||
| 1328 | code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); | 1695 | code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); |
| 1329 | } | 1696 | } |
| 1330 | 1697 | ||
| 1331 | - let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); | ||
| 1332 | - code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv); | ||
| 1333 | - | ||
| 1334 | // ---- syntax ---- | 1698 | // ---- syntax ---- |
| 1335 | w.begin_mb(&e.mb_ctx); | 1699 | w.begin_mb(&e.mb_ctx); |
| 1336 | w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); | 1700 | w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); |
| @@ -1455,7 +1819,11 @@ fn block_bits(b: &[i32]) -> i64 { | |||
| 1455 | n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; | 1819 | n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; |
| 1456 | } | 1820 | } |
| 1457 | } | 1821 | } |
| 1458 | - if n > 0 { n + 6 } else { 2 } | 1822 | + if n > 0 { |
| 1823 | + n + 6 | ||
| 1824 | + } else { | ||
| 1825 | + 2 | ||
| 1826 | + } | ||
| 1459 | } | 1827 | } |
| 1460 | 1828 | ||
| 1461 | /// Rough bit cost of a macroblock's residual, for the skip decision: a level | 1829 | /// Rough bit cost of a macroblock's residual, for the skip decision: a level |
| @@ -1475,12 +1843,6 @@ fn estimate_bits(lv: &Levels) -> i64 { | |||
| 1475 | bits | 1843 | bits |
| 1476 | } | 1844 | } |
| 1477 | 1845 | ||
| 1478 | -/// Lagrangian multiplier in the squared-error domain, paired with | ||
| 1479 | -/// [`super::lambda_for`] in the SATD one. | ||
| 1480 | -fn lambda_ssd(qp: i32) -> f64 { | ||
| 1481 | - 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() | ||
| 1482 | -} | ||
| 1483 | - | ||
| 1484 | /// Motion-compensate one partition into the picture planes. | 1846 | /// Motion-compensate one partition into the picture planes. |
| 1485 | fn compensate_part( | 1847 | fn compensate_part( |
| 1486 | pic: &mut Picture, | 1848 | pic: &mut Picture, |
| @@ -1613,38 +1975,45 @@ fn encode_inter_mb( | |||
| 1613 | // quantisation churn costs bits every picture and improves nothing. | 1975 | // quantisation churn costs bits every picture and improves nothing. |
| 1614 | let may_skip = choice.prefer_skip; | 1976 | let may_skip = choice.prefer_skip; |
| 1615 | let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); | 1977 | let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); |
| 1616 | - let mut lv = Levels::default(); | 1978 | + let mut chroma_lv = Levels::default(); |
| 1617 | - if e.transform_8x8 { | 1979 | + code_chroma(pic, e, mb_x, mb_y, qp, false, &mut chroma_lv); |
| 1980 | + let mut lv = chroma_lv.clone(); | ||
| 1981 | + if e.t8x8_inter(mb_y) { | ||
| 1618 | // Both transform sizes on the same prediction; the cheaper | 1982 | // Both transform sizes on the same prediction; the cheaper |
| 1619 | // rate-distortion cost is coded. | 1983 | // rate-distortion cost is coded. |
| 1620 | let mut pred = [0u8; 256]; | 1984 | let mut pred = [0u8; 256]; |
| 1621 | save_luma(pic, mb_x, mb_y, &mut pred); | 1985 | save_luma(pic, mb_x, mb_y, &mut pred); |
| 1622 | - code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | 1986 | + let mut lv4 = chroma_lv.clone(); |
| 1623 | - let cost4 = | 1987 | + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4); |
| 1624 | - ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv) as f64; | 1988 | + let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4); |
| 1989 | + let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64; | ||
| 1625 | let mut recon4 = [0u8; 256]; | 1990 | let mut recon4 = [0u8; 256]; |
| 1626 | save_luma(pic, mb_x, mb_y, &mut recon4); | 1991 | save_luma(pic, mb_x, mb_y, &mut recon4); |
| 1627 | restore_luma(pic, mb_x, mb_y, &pred); | 1992 | restore_luma(pic, mb_x, mb_y, &pred); |
| 1628 | - let mut lv8 = Levels::default(); | 1993 | + let mut lv8 = chroma_lv; |
| 1629 | code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); | 1994 | code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); |
| 1630 | - let cost8 = | 1995 | + let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); |
| 1631 | - ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv8) as f64; | 1996 | + let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; |
| 1632 | - if cost8 < cost4 { | 1997 | + if cost8 + e.lambda * e.t8x8_margin_bits < cost4 { |
| 1633 | lv = lv8; | 1998 | lv = lv8; |
| 1634 | } else { | 1999 | } else { |
| 2000 | + lv = lv4; | ||
| 1635 | restore_luma(pic, mb_x, mb_y, &recon4); | 2001 | restore_luma(pic, mb_x, mb_y, &recon4); |
| 1636 | } | 2002 | } |
| 1637 | } else { | 2003 | } else { |
| 1638 | code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | 2004 | code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); |
| 1639 | } | 2005 | } |
| 1640 | - code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv); | ||
| 1641 | let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; | 2006 | let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; |
| 1642 | let skip = match ssd_skip { | 2007 | let skip = match ssd_skip { |
| 1643 | None => false, | 2008 | None => false, |
| 1644 | Some(_) if empty => true, | 2009 | Some(_) if empty => true, |
| 1645 | Some(ssd_skip) => { | 2010 | Some(ssd_skip) => { |
| 1646 | - let coded = | 2011 | + let coded = if e.t8x8_inter(mb_y) { |
| 1647 | - ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64; | 2012 | + let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); |
| 2013 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 | ||
| 2014 | + } else { | ||
| 2015 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64 | ||
| 2016 | + }; | ||
| 1648 | if ssd_skip as f64 <= coded { | 2017 | if ssd_skip as f64 <= coded { |
| 1649 | // Put the prediction back: the residual has been added to it. | 2018 | // Put the prediction back: the residual has been added to it. |
| 1650 | compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); | 2019 | compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); |
crates/ec-h264/src/enc/mod.rsmodified+228 -20
| @@ -28,19 +28,21 @@ mod quant; | |||
| 28 | mod rc; | 28 | mod rc; |
| 29 | mod vlc; | 29 | mod vlc; |
| 30 | 30 | ||
| 31 | -use ec_core::BitWriter; | ||
| 32 | use ec_core::error::{Error, Result}; | 31 | use ec_core::error::{Error, Result}; |
| 33 | -use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; | 32 | +use ec_core::BitWriter; |
| 33 | +use ec_h264_syntax::nal::{escape_rbsp, NalUnitType}; | ||
| 34 | use ec_h264_syntax::{SliceType, Sps}; | 34 | use ec_h264_syntax::{SliceType, Sps}; |
| 35 | 35 | ||
| 36 | use crate::decoder::deblock_picture; | 36 | use crate::decoder::deblock_picture; |
| 37 | use crate::dpb::{Picture, SliceParams as DeblockParams}; | 37 | use crate::dpb::{Picture, SliceParams as DeblockParams}; |
| 38 | use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; | 38 | use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; |
| 39 | +#[cfg(feature = "rd-ablation")] | ||
| 40 | +use crate::entropy::FLAG_SKIP; | ||
| 39 | use crate::transform::{LevelScale4x4, LevelScale8x8}; | 41 | use crate::transform::{LevelScale4x4, LevelScale8x8}; |
| 40 | 42 | ||
| 41 | use entropy::EncEntropy; | 43 | use entropy::EncEntropy; |
| 42 | -use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; | 44 | +use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams}; |
| 43 | -use mb::{MbEnc, Source, encode_mb}; | 45 | +use mb::{encode_mb, MbEnc, Source}; |
| 44 | use rc::RateControl; | 46 | use rc::RateControl; |
| 45 | 47 | ||
| 46 | pub use mb::Preset; | 48 | pub use mb::Preset; |
| @@ -74,17 +76,21 @@ pub struct EncoderConfig { | |||
| 74 | pub qp: i32, | 76 | pub qp: i32, |
| 75 | /// 8x8 transform (High profile). Off by default. | 77 | /// 8x8 transform (High profile). Off by default. |
| 76 | /// | 78 | /// |
| 77 | - /// NOT SAFE TO SET YET: this only flips the SPS/PPS High-profile tail | 79 | + /// When enabled, eligible intra and inter luma macroblocks write |
| 78 | - /// (`profile_idc` 100, `transform_8x8_mode_flag`). Once the PPS carries | 80 | + /// `transform_size_8x8_flag` and choose the 8x8 path with a squared-error |
| 79 | - /// that flag, a conformant decoder unconditionally reads an extra | 81 | + /// rate-distortion cost. Leaving it off preserves the Baseline/Main-profile |
| 80 | - /// `transform_size_8x8_flag` per macroblock (7.3.5: every non-I16x16 | 82 | + /// 4x4 path. |
| 81 | - /// intra macroblock, and every inter macroblock with a nonzero luma cbp — | ||
| 82 | - /// see `decoder.rs:1151` and `:1789-1793`). Nothing in `enc::entropy` / | ||
| 83 | - /// `enc::mb` writes that bit yet, so turning this on desyncs every real | ||
| 84 | - /// stream (headers.rs's own tests only exercise the parameter sets, not a | ||
| 85 | - /// full encode). Wiring that emission — and then the mode decision that | ||
| 86 | - /// actually picks 8x8 blocks — is later work. | ||
| 87 | pub transform_8x8: bool, | 83 | pub transform_8x8: bool, |
| 84 | + #[cfg(feature = "rd-ablation")] | ||
| 85 | + rd_lambda_standard: bool, | ||
| 86 | + #[cfg(feature = "rd-ablation")] | ||
| 87 | + rd_transform_8x8_intra: bool, | ||
| 88 | + #[cfg(feature = "rd-ablation")] | ||
| 89 | + rd_transform_8x8_inter: bool, | ||
| 90 | + #[cfg(feature = "rd-ablation")] | ||
| 91 | + rd_transform_8x8_roweven: bool, | ||
| 92 | + #[cfg(feature = "rd-ablation")] | ||
| 93 | + rd_transform_8x8_margin_bits: f64, | ||
| 88 | } | 94 | } |
| 89 | 95 | ||
| 90 | impl EncoderConfig { | 96 | impl EncoderConfig { |
| @@ -102,6 +108,16 @@ impl EncoderConfig { | |||
| 102 | threads: 0, | 108 | threads: 0, |
| 103 | qp: 26, | 109 | qp: 26, |
| 104 | transform_8x8: false, | 110 | transform_8x8: false, |
| 111 | + #[cfg(feature = "rd-ablation")] | ||
| 112 | + rd_lambda_standard: false, | ||
| 113 | + #[cfg(feature = "rd-ablation")] | ||
| 114 | + rd_transform_8x8_intra: false, | ||
| 115 | + #[cfg(feature = "rd-ablation")] | ||
| 116 | + rd_transform_8x8_inter: false, | ||
| 117 | + #[cfg(feature = "rd-ablation")] | ||
| 118 | + rd_transform_8x8_roweven: false, | ||
| 119 | + #[cfg(feature = "rd-ablation")] | ||
| 120 | + rd_transform_8x8_margin_bits: 0.0, | ||
| 105 | } | 121 | } |
| 106 | } | 122 | } |
| 107 | } | 123 | } |
| @@ -176,6 +192,10 @@ impl<'a> PictureView<'a> { | |||
| 176 | impl Encoder { | 192 | impl Encoder { |
| 177 | /// Build an encoder for `cfg`, refusing what it cannot code. | 193 | /// Build an encoder for `cfg`, refusing what it cannot code. |
| 178 | pub fn new(cfg: EncoderConfig) -> Result<Encoder> { | 194 | pub fn new(cfg: EncoderConfig) -> Result<Encoder> { |
| 195 | + #[cfg(feature = "rd-ablation")] | ||
| 196 | + let mut cfg = cfg; | ||
| 197 | + #[cfg(feature = "rd-ablation")] | ||
| 198 | + apply_rd_ablation(&mut cfg); | ||
| 179 | if cfg.width < 16 || cfg.height < 16 { | 199 | if cfg.width < 16 || cfg.height < 16 { |
| 180 | return Err(Error::unsupported( | 200 | return Err(Error::unsupported( |
| 181 | "picture smaller than one macroblock", | 201 | "picture smaller than one macroblock", |
| @@ -385,7 +405,16 @@ impl Encoder { | |||
| 385 | } | 405 | } |
| 386 | } | 406 | } |
| 387 | } | 407 | } |
| 408 | + // H5 measurement hook: the chosen candidate's trial SSD is the | ||
| 409 | + // pre-deblock SSD of the macroblock in this picture (round 4 verified | ||
| 410 | + // trial bits and SSD against the final picture), so capturing the | ||
| 411 | + // per-macroblock SSD right before and right after the filter is the | ||
| 412 | + // exact pre/post comparison with no hooks inside the RD trials. | ||
| 413 | + #[cfg(feature = "rd-ablation")] | ||
| 414 | + let rd_pre = rd_trace_capture(master, &self.src); | ||
| 388 | deblock_picture(master); | 415 | deblock_picture(master); |
| 416 | + #[cfg(feature = "rd-ablation")] | ||
| 417 | + rd_trace_write(master, &self.src, self.frames, rd_pre); | ||
| 389 | master.extend_borders(); | 418 | master.extend_borders(); |
| 390 | master.complete = true; | 419 | master.complete = true; |
| 391 | std::mem::swap(master, &mut self.reference); | 420 | std::mem::swap(master, &mut self.reference); |
| @@ -516,9 +545,14 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | |||
| 516 | slice_id: job.slice_id, | 545 | slice_id: job.slice_id, |
| 517 | qp: job.qp, | 546 | qp: job.qp, |
| 518 | target_qp: job.qp, | 547 | target_qp: job.qp, |
| 519 | - lambda: lambda_for(job.qp), | 548 | + lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)), |
| 549 | + t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg), | ||
| 520 | preset: job.cfg.preset, | 550 | preset: job.cfg.preset, |
| 551 | + lambda_standard: rd_lambda_standard(job.cfg), | ||
| 521 | transform_8x8: job.cfg.transform_8x8, | 552 | transform_8x8: job.cfg.transform_8x8, |
| 553 | + transform_8x8_intra: rd_transform_8x8_intra(job.cfg), | ||
| 554 | + transform_8x8_inter: rd_transform_8x8_inter(job.cfg), | ||
| 555 | + transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg), | ||
| 522 | ls: LevelScale4x4::new(&[16; 16]), | 556 | ls: LevelScale4x4::new(&[16; 16]), |
| 523 | ls8: LevelScale8x8::new(&[16; 64]), | 557 | ls8: LevelScale8x8::new(&[16; 64]), |
| 524 | mb_ctx: crate::entropy::MbCtx::default(), | 558 | mb_ctx: crate::entropy::MbCtx::default(), |
| @@ -534,7 +568,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | |||
| 534 | let expected = job.band_target * n as f64 / rows as f64; | 568 | let expected = job.band_target * n as f64 / rows as f64; |
| 535 | let delta = job.rc.row_delta(spent, expected); | 569 | let delta = job.rc.row_delta(spent, expected); |
| 536 | e.target_qp = (job.qp + delta).clamp(10, 51); | 570 | e.target_qp = (job.qp + delta).clamp(10, 51); |
| 537 | - e.lambda = lambda_for(e.target_qp); | 571 | + e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg)); |
| 538 | } | 572 | } |
| 539 | for mb_x in 0..mb_w { | 573 | for mb_x in 0..mb_w { |
| 540 | let addr = mb_y * mb_w + mb_x; | 574 | let addr = mb_y * mb_w + mb_x; |
| @@ -546,10 +580,174 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | |||
| 546 | w.finish(job.slice_type == SliceType::P) | 580 | w.finish(job.slice_type == SliceType::P) |
| 547 | } | 581 | } |
| 548 | 582 | ||
| 549 | -/// Lagrangian multiplier for mode decision in the SATD domain. | 583 | +/// Standard Lagrangian multiplier in the squared-error domain. |
| 550 | -fn lambda_for(qp: i32) -> i32 { | 584 | +pub(crate) fn lambda_ssd(qp: i32) -> f64 { |
| 551 | - // 2^((qp - 12) / 6), the usual ladder, floored at 1. | 585 | + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() |
| 552 | - (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1) | 586 | +} |
| 587 | + | ||
| 588 | +/// Lagrangian multiplier. Production uses the established byte-stable ladder; | ||
| 589 | +/// the ablation feature can select the standard squared-error multiplier. | ||
| 590 | +fn lambda_for(qp: i32, standard: bool) -> f64 { | ||
| 591 | + if standard { | ||
| 592 | + lambda_ssd(qp) | ||
| 593 | + } else { | ||
| 594 | + (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) | ||
| 595 | + } | ||
| 596 | +} | ||
| 597 | + | ||
| 598 | +#[cfg(feature = "rd-ablation")] | ||
| 599 | +fn apply_rd_ablation(cfg: &mut EncoderConfig) { | ||
| 600 | + if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") { | ||
| 601 | + cfg.rd_lambda_standard = match lambda.as_str() { | ||
| 602 | + "ladder" => false, | ||
| 603 | + "standard" => true, | ||
| 604 | + _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"), | ||
| 605 | + }; | ||
| 606 | + } | ||
| 607 | + if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") { | ||
| 608 | + let (intra, inter, roweven) = match transform.as_str() { | ||
| 609 | + "off" => (false, false, false), | ||
| 610 | + "on" => (true, true, false), | ||
| 611 | + "roweven" => (true, true, true), | ||
| 612 | + "intra" => (true, false, false), | ||
| 613 | + "inter" => (false, true, false), | ||
| 614 | + _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"), | ||
| 615 | + }; | ||
| 616 | + cfg.rd_transform_8x8_intra = intra; | ||
| 617 | + cfg.rd_transform_8x8_inter = inter; | ||
| 618 | + cfg.rd_transform_8x8_roweven = roweven; | ||
| 619 | + cfg.transform_8x8 = intra || inter; | ||
| 620 | + } else if cfg.transform_8x8 { | ||
| 621 | + cfg.rd_transform_8x8_intra = true; | ||
| 622 | + cfg.rd_transform_8x8_inter = true; | ||
| 623 | + } | ||
| 624 | + if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") { | ||
| 625 | + cfg.rd_transform_8x8_margin_bits = margin | ||
| 626 | + .parse() | ||
| 627 | + .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number"); | ||
| 628 | + } | ||
| 629 | +} | ||
| 630 | + | ||
| 631 | +/// Luma and chroma SSD of every macroblock against the source, before the | ||
| 632 | +/// deblocking filter — the distortion the RD decision actually paid. | ||
| 633 | +#[cfg(feature = "rd-ablation")] | ||
| 634 | +fn rd_trace_capture(pic: &Picture, src: &Source) -> Option<Vec<(i64, i64)>> { | ||
| 635 | + if std::env::var_os("EC_H264_RD_TRACE").is_none() { | ||
| 636 | + return None; | ||
| 637 | + } | ||
| 638 | + let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h); | ||
| 639 | + for mb_y in 0..pic.mb_h { | ||
| 640 | + for mb_x in 0..pic.mb_w { | ||
| 641 | + out.push(rd_trace_ssd(pic, src, mb_x, mb_y)); | ||
| 642 | + } | ||
| 643 | + } | ||
| 644 | + Some(out) | ||
| 645 | +} | ||
| 646 | + | ||
| 647 | +/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma | ||
| 648 | +/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`. | ||
| 649 | +#[cfg(feature = "rd-ablation")] | ||
| 650 | +fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64, i64)>>) { | ||
| 651 | + use std::io::Write; | ||
| 652 | + let Some(pre) = pre else { return }; | ||
| 653 | + let mut out = std::fs::OpenOptions::new() | ||
| 654 | + .create(true) | ||
| 655 | + .append(true) | ||
| 656 | + .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture")) | ||
| 657 | + .expect("open EC_H264_RD_TRACE"); | ||
| 658 | + for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() { | ||
| 659 | + let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w); | ||
| 660 | + let f = pic.mb_flags[addr]; | ||
| 661 | + let _ = writeln!( | ||
| 662 | + out, | ||
| 663 | + "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}", | ||
| 664 | + u8::from(f & FLAG_INTER == 0), | ||
| 665 | + u8::from(f & FLAG_TRANS8X8 != 0), | ||
| 666 | + u8::from(f & FLAG_SKIP != 0), | ||
| 667 | + pic.mb_qp[addr] | ||
| 668 | + ); | ||
| 669 | + } | ||
| 670 | +} | ||
| 671 | + | ||
| 672 | +/// Luma and chroma SSD of one macroblock against the source planes. | ||
| 673 | +#[cfg(feature = "rd-ablation")] | ||
| 674 | +fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) { | ||
| 675 | + let mut luma = 0i64; | ||
| 676 | + let stride = pic.y.stride; | ||
| 677 | + let origin = pic.y.at(mb_x * 16, mb_y * 16); | ||
| 678 | + for row in 0..16 { | ||
| 679 | + let s = (mb_y * 16 + row) * src.stride + mb_x * 16; | ||
| 680 | + for x in 0..16 { | ||
| 681 | + let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); | ||
| 682 | + luma += d * d; | ||
| 683 | + } | ||
| 684 | + } | ||
| 685 | + let mut chroma = 0i64; | ||
| 686 | + for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] { | ||
| 687 | + let stride = plane.stride; | ||
| 688 | + let origin = plane.at(mb_x * 8, mb_y * 8); | ||
| 689 | + for row in 0..8 { | ||
| 690 | + let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8; | ||
| 691 | + for x in 0..8 { | ||
| 692 | + let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]); | ||
| 693 | + chroma += d * d; | ||
| 694 | + } | ||
| 695 | + } | ||
| 696 | + } | ||
| 697 | + (luma, chroma) | ||
| 698 | +} | ||
| 699 | + | ||
| 700 | +#[cfg(feature = "rd-ablation")] | ||
| 701 | +fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { | ||
| 702 | + cfg.rd_lambda_standard | ||
| 703 | +} | ||
| 704 | + | ||
| 705 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 706 | +fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { | ||
| 707 | + cfg.transform_8x8 | ||
| 708 | +} | ||
| 709 | + | ||
| 710 | +#[cfg(feature = "rd-ablation")] | ||
| 711 | +fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { | ||
| 712 | + cfg.rd_transform_8x8_intra | ||
| 713 | +} | ||
| 714 | + | ||
| 715 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 716 | +fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { | ||
| 717 | + cfg.transform_8x8 | ||
| 718 | +} | ||
| 719 | + | ||
| 720 | +#[cfg(feature = "rd-ablation")] | ||
| 721 | +fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { | ||
| 722 | + cfg.rd_transform_8x8_inter | ||
| 723 | +} | ||
| 724 | + | ||
| 725 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 726 | +fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { | ||
| 727 | + cfg.transform_8x8 | ||
| 728 | +} | ||
| 729 | + | ||
| 730 | +#[cfg(feature = "rd-ablation")] | ||
| 731 | +fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool { | ||
| 732 | + cfg.rd_transform_8x8_roweven | ||
| 733 | +} | ||
| 734 | + | ||
| 735 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 736 | +fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool { | ||
| 737 | + false | ||
| 738 | +} | ||
| 739 | + | ||
| 740 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 741 | +const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0; | ||
| 742 | + | ||
| 743 | +#[cfg(feature = "rd-ablation")] | ||
| 744 | +fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 { | ||
| 745 | + cfg.rd_transform_8x8_margin_bits | ||
| 746 | +} | ||
| 747 | + | ||
| 748 | +#[cfg(not(feature = "rd-ablation"))] | ||
| 749 | +fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 { | ||
| 750 | + TRANSFORM_8X8_MARGIN_BITS | ||
| 553 | } | 751 | } |
| 554 | 752 | ||
| 555 | /// Split `mb_h` macroblock rows into at most `n` contiguous bands. | 753 | /// Split `mb_h` macroblock rows into at most `n` contiguous bands. |
| @@ -707,4 +905,14 @@ mod tests { | |||
| 707 | assert!(matches!(err, Error::Unsupported { .. }), "{err}"); | 905 | assert!(matches!(err, Error::Unsupported { .. }), "{err}"); |
| 708 | assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok()); | 906 | assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok()); |
| 709 | } | 907 | } |
| 908 | + #[test] | ||
| 909 | + fn production_lambda_tracks_transform_mode() { | ||
| 910 | + let mut cfg = EncoderConfig::new(640, 480); | ||
| 911 | + assert_eq!( | ||
| 912 | + lambda_for(26, rd_lambda_standard(&cfg)), | ||
| 913 | + lambda_for(26, false) | ||
| 914 | + ); | ||
| 915 | + cfg.transform_8x8 = true; | ||
| 916 | + assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26)); | ||
| 917 | + } | ||
| 710 | } | 918 | } |
crates/ec-h264/tests/encode.rsmodified+76 -23
| @@ -122,6 +122,66 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | |||
| 122 | } | 122 | } |
| 123 | } | 123 | } |
| 124 | 124 | ||
| 125 | +fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { | ||
| 126 | + let mut a = [[0.0; 5]; 4]; | ||
| 127 | + for i in 0..4 { | ||
| 128 | + a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; | ||
| 129 | + } | ||
| 130 | + for col in 0..4 { | ||
| 131 | + let mut pivot = col; | ||
| 132 | + for row in col + 1..4 { | ||
| 133 | + if a[row][col].abs() > a[pivot][col].abs() { | ||
| 134 | + pivot = row; | ||
| 135 | + } | ||
| 136 | + } | ||
| 137 | + a.swap(col, pivot); | ||
| 138 | + let div = a[col][col]; | ||
| 139 | + assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); | ||
| 140 | + for j in col..5 { | ||
| 141 | + a[col][j] /= div; | ||
| 142 | + } | ||
| 143 | + for row in 0..4 { | ||
| 144 | + if row == col { | ||
| 145 | + continue; | ||
| 146 | + } | ||
| 147 | + let f = a[row][col]; | ||
| 148 | + for j in col..5 { | ||
| 149 | + a[row][j] -= f * a[col][j]; | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + } | ||
| 153 | + [a[0][4], a[1][4], a[2][4], a[3][4]] | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | ||
| 157 | + c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { | ||
| 161 | + let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); | ||
| 162 | + let ys_candidate = std::array::from_fn(|i| candidate[i].1); | ||
| 163 | + let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); | ||
| 164 | + let ys_anchor = std::array::from_fn(|i| anchor[i].1); | ||
| 165 | + let lo = xs_candidate | ||
| 166 | + .iter() | ||
| 167 | + .copied() | ||
| 168 | + .fold(f64::INFINITY, f64::min) | ||
| 169 | + .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); | ||
| 170 | + let hi = xs_candidate | ||
| 171 | + .iter() | ||
| 172 | + .copied() | ||
| 173 | + .fold(f64::NEG_INFINITY, f64::max) | ||
| 174 | + .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); | ||
| 175 | + assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); | ||
| 176 | + let c_candidate = cubic_fit(xs_candidate, ys_candidate); | ||
| 177 | + let c_anchor = cubic_fit(xs_anchor, ys_anchor); | ||
| 178 | + (cubic_integral(c_candidate, hi) | ||
| 179 | + - cubic_integral(c_candidate, lo) | ||
| 180 | + - cubic_integral(c_anchor, hi) | ||
| 181 | + + cubic_integral(c_anchor, lo)) | ||
| 182 | + / (hi - lo) | ||
| 183 | +} | ||
| 184 | + | ||
| 125 | /// The encoder's reconstruction and a decode of its bitstream agree sample for | 185 | /// The encoder's reconstruction and a decode of its bitstream agree sample for |
| 126 | /// sample, over a QP sweep, both presets, single and multi threaded. | 186 | /// sample, over a QP sweep, both presets, single and multi threaded. |
| 127 | #[test] | 187 | #[test] |
| @@ -350,8 +410,8 @@ fn encode_clip( | |||
| 350 | } | 410 | } |
| 351 | 411 | ||
| 352 | /// Flat gradients and glyph-like rectangles: the content the 8x8 transform | 412 | /// Flat gradients and glyph-like rectangles: the content the 8x8 transform |
| 353 | -/// exists for. A 10-frame clip with the flag on must beat the flag off by at | 413 | +/// exists for. A 10-frame clip with the flag on must keep a clear positive |
| 354 | -/// least 0.3 dB at equal bits, or by 5% fewer bits at equal PSNR. | 414 | +/// gain at equal bits, or cut bits at equal PSNR. |
| 355 | #[test] | 415 | #[test] |
| 356 | fn eight_by_eight_gains_on_flat_and_text() { | 416 | fn eight_by_eight_gains_on_flat_and_text() { |
| 357 | let (w, h) = (320, 240); | 417 | let (w, h) = (320, 240); |
| @@ -382,11 +442,12 @@ fn eight_by_eight_gains_on_flat_and_text() { | |||
| 382 | clip.u.fill(128); | 442 | clip.u.fill(128); |
| 383 | clip.v.fill(128); | 443 | clip.v.fill(128); |
| 384 | }; | 444 | }; |
| 385 | - let run = |t8x8: bool, qp: i32| { | 445 | + let run = |t8x8: bool, qp: i32, cabac: bool| { |
| 386 | let mut cfg = EncoderConfig::new(w as u32, h as u32); | 446 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 387 | cfg.qp = qp; | 447 | cfg.qp = qp; |
| 388 | cfg.gop_size = 10; | 448 | cfg.gop_size = 10; |
| 389 | cfg.transform_8x8 = t8x8; | 449 | cfg.transform_8x8 = t8x8; |
| 450 | + cfg.cabac = cabac; | ||
| 390 | let mut enc = Encoder::new(cfg).expect("encoder"); | 451 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 391 | let mut clip = Clip::new(w, h); | 452 | let mut clip = Clip::new(w, h); |
| 392 | let (mut bits, mut sum_psnr) = (0usize, 0.0); | 453 | let (mut bits, mut sum_psnr) = (0usize, 0.0); |
| @@ -404,31 +465,23 @@ fn eight_by_eight_gains_on_flat_and_text() { | |||
| 404 | } | 465 | } |
| 405 | (bits as f64, sum_psnr / 10.0, share) | 466 | (bits as f64, sum_psnr / 10.0, share) |
| 406 | }; | 467 | }; |
| 407 | - // Interpolate the off curve at the on point's bits / PSNR. | 468 | + let qps = [22, 26, 30, 34]; |
| 408 | - let qp = 26; | 469 | + let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); |
| 409 | - let (bits_on, psnr_on, share) = run(true, qp); | 470 | + let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); |
| 410 | - let off: Vec<_> = [qp - 2, qp, qp + 2] | 471 | + let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 411 | - .iter() | 472 | + let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 412 | - .map(|&q| run(false, q)) | 473 | + let bd = bd_psnr_delta(&on_curve, &off_curve); |
| 413 | - .collect(); | 474 | + let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64; |
| 414 | - let (bits_off, psnr_off, _) = off[1]; | 475 | + const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.255_347; |
| 415 | - // Local slopes of the off curve, from the neighbouring QPs. | ||
| 416 | - let dpsnr_dbits = (off[0].1 - off[2].1) / (off[0].0 - off[2].0); | ||
| 417 | - let psnr_off_at_on_bits = psnr_off + (bits_on - bits_off) * dpsnr_dbits; | ||
| 418 | - let bits_off_at_on_psnr = bits_off + (psnr_on - psnr_off) / dpsnr_dbits; | ||
| 419 | - let gain_db = psnr_on - psnr_off_at_on_bits; | ||
| 420 | - let saving = 1.0 - bits_on / bits_off_at_on_psnr; | ||
| 421 | eprintln!( | 476 | eprintln!( |
| 422 | - "8x8 qp {qp}: on {bits_on:.0} bits {psnr_on:.2} dB, off {bits_off:.0} bits {psnr_off:.2} dB; \ | 477 | + "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", |
| 423 | - gain at equal bits {gain_db:+.2} dB, saving at equal PSNR {:.1}%, 8x8 MB share {:.1}%", | ||
| 424 | - saving * 100.0, | ||
| 425 | share * 100.0 | 478 | share * 100.0 |
| 426 | ); | 479 | ); |
| 427 | assert!(share > 0.0, "no 8x8 macroblocks were coded"); | 480 | assert!(share > 0.0, "no 8x8 macroblocks were coded"); |
| 481 | + assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); | ||
| 428 | assert!( | 482 | assert!( |
| 429 | - gain_db >= 0.3 || saving >= 0.05, | 483 | + bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, |
| 430 | - "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar", | 484 | + "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" |
| 431 | - saving * 100.0 | ||
| 432 | ); | 485 | ); |
| 433 | } | 486 | } |
| 434 | 487 | ||