Merge branch 'lane-h265-chroma'
Browse files at this commit4 changed files +228 -13
- crates/ec-h265/src/ctu.rs +133 -3
- crates/ec-h265/src/encoder.rs +7 -0
- crates/ec-h265/tests/conformance.rs +59 -3
- crates/ec-h265/tests/encode.rs +29 -7
crates/ec-h265/src/ctu.rsmodified+133 -3
| @@ -148,6 +148,8 @@ pub struct CtuEncoder<'a> { | ||
| 148 | 148 | chroma_rd: bool, |
| 149 | 149 | /// Weight on chroma SSD in that decision, against luma's lambda. |
| 150 | 150 | chroma_rd_weight: f64, |
| 151 | + /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. | |
| 152 | + intra_nxn: bool, | |
| 151 | 153 | /// `log2` of the smallest coding unit the search will produce. |
| 152 | 154 | min_cb_log2: u32, |
| 153 | 155 | /// Intra mode per 4x4 block of the band; 255 = not coded yet. |
| @@ -178,6 +180,7 @@ impl<'a> CtuEncoder<'a> { | ||
| 178 | 180 | candidates: usize, |
| 179 | 181 | chroma_rd: bool, |
| 180 | 182 | chroma_rd_weight: f64, |
| 183 | + intra_nxn: bool, | |
| 181 | 184 | min_cb_log2: u32, |
| 182 | 185 | ) -> CtuEncoder<'a> { |
| 183 | 186 | let band_rows = (height - band_y0).min(ctb_size); |
| @@ -197,6 +200,7 @@ impl<'a> CtuEncoder<'a> { | ||
| 197 | 200 | candidates: candidates.clamp(1, 35), |
| 198 | 201 | chroma_rd, |
| 199 | 202 | chroma_rd_weight, |
| 203 | + intra_nxn, | |
| 200 | 204 | min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), |
| 201 | 205 | modes: vec![255; (width / 4) * (ctb_size / 4)], |
| 202 | 206 | depths: vec![0; (width / 4) * (ctb_size / 4)], |
| @@ -482,8 +486,122 @@ impl<'a> CtuEncoder<'a> { | ||
| 482 | 486 | // ---- one coding unit ------------------------------------------------- |
| 483 | 487 | |
| 484 | 488 | /// Code one coding unit, returning `SSD + lambda * bits` for it. The split |
| 485 | - /// flag above it is the caller's to count. | |
| 489 | + /// flag above it is the caller's to count. At the smallest coding unit the | |
| 490 | + /// partition mode is a rate-distortion decision between one 8x8 block and | |
| 491 | + /// four 4x4 ones; everywhere else there is only PART_2Nx2N. | |
| 486 | 492 | fn code_cu(&mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder) -> f64 { |
| 493 | + if log2 != MIN_CB_LOG2 || !self.intra_nxn { | |
| 494 | + return self.code_cu_2nx2n(x, y, log2, depth, enc); | |
| 495 | + } | |
| 496 | + let start = enc.snapshot(); | |
| 497 | + let coded_before = self.coded; | |
| 498 | + let size = 1usize << log2; | |
| 499 | + | |
| 500 | + let square_cost = self.code_cu_2nx2n(x, y, log2, depth, enc); | |
| 501 | + let square_state = enc.snapshot_since(&start); | |
| 502 | + let square_rec = self.save_region(x, y, size); | |
| 503 | + let square_meta = self.save_meta(x, y, size); | |
| 504 | + let square_empty = self.last_cu_empty; | |
| 505 | + | |
| 506 | + enc.restore(&start); | |
| 507 | + self.coded = coded_before; | |
| 508 | + let nxn_cost = self.code_cu_nxn(x, y, depth, enc); | |
| 509 | + | |
| 510 | + if square_cost <= nxn_cost { | |
| 511 | + enc.restore(&square_state); | |
| 512 | + self.load_region(x, y, size, &square_rec); | |
| 513 | + self.load_meta(x, y, size, &square_meta); | |
| 514 | + self.last_cu_empty = square_empty; | |
| 515 | + square_cost | |
| 516 | + } else { | |
| 517 | + nxn_cost | |
| 518 | + } | |
| 519 | + } | |
| 520 | + | |
| 521 | + /// The four-4x4-partition form of the smallest coding unit: four luma | |
| 522 | + /// prediction units, each its own transform block, over one 4x4 chroma | |
| 523 | + /// block that keeps the coding unit's single chroma mode. | |
| 524 | + fn code_cu_nxn(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 { | |
| 525 | + let before = enc.bit_count(); | |
| 526 | + // The mode search reconstructs each partition as it goes, because the | |
| 527 | + // next one predicts from it; the syntax is written afterwards in the | |
| 528 | + // order the decoder reads it. | |
| 529 | + let offsets = [(0usize, 0usize), (4, 0), (0, 4), (4, 4)]; | |
| 530 | + let mut modes = [0u8; 4]; | |
| 531 | + let mut mpms = [[0u8; 3]; 4]; | |
| 532 | + let mut levels = [[0i32; 16]; 4]; | |
| 533 | + let mut cbfs = [false; 4]; | |
| 534 | + for (part, &(dx, dy)) in offsets.iter().enumerate() { | |
| 535 | + let (px, py) = (x + dx, y + dy); | |
| 536 | + let mpm = self.mpm_at(px, py); | |
| 537 | + let mode = self.choose_luma_mode(px, py, 4, 2, &mpm, enc); | |
| 538 | + levels[part].copy_from_slice(&self.scratch.luma_levels[..16]); | |
| 539 | + cbfs[part] = levels[part].iter().any(|&v| v != 0); | |
| 540 | + modes[part] = mode; | |
| 541 | + mpms[part] = mpm; | |
| 542 | + self.mark_coded(px, py, 4, mode, depth); | |
| 543 | + } | |
| 544 | + | |
| 545 | + // part_mode: PART_NxN is the single bin 0. | |
| 546 | + enc.encode_bin(ctx::PART_MODE, 0); | |
| 547 | + for part in 0..4 { | |
| 548 | + self.write_mode_prev_flag(enc, modes[part], &mpms[part]); | |
| 549 | + } | |
| 550 | + for part in 0..4 { | |
| 551 | + self.write_mode_remainder(enc, modes[part], &mpms[part]); | |
| 552 | + } | |
| 553 | + | |
| 554 | + // The chroma mode belongs to the coding unit and derives from the | |
| 555 | + // first partition's luma mode (8.4.3). | |
| 556 | + let (chroma_mode, chroma_idx) = if self.chroma_rd { | |
| 557 | + self.choose_chroma_mode(x, y, 8, MIN_CB_LOG2, modes[0], enc) | |
| 558 | + } else { | |
| 559 | + (modes[0], None) | |
| 560 | + }; | |
| 561 | + self.write_chroma_mode_syntax(enc, chroma_idx); | |
| 562 | + let cb_cbf = self.code_chroma(x, y, 8, chroma_mode, 1).1; | |
| 563 | + let cr_cbf = self.code_chroma(x, y, 8, chroma_mode, 2).1; | |
| 564 | + | |
| 565 | + // transform_tree: the split at depth 0 is inferred from the partition | |
| 566 | + // mode, so only the chroma flags are written there; every luma flag and | |
| 567 | + // residual belongs to a 4x4 child at depth 1, and the chroma residual | |
| 568 | + // rides along with the last of them (7.3.8.8, 7.3.8.10). | |
| 569 | + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); | |
| 570 | + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); | |
| 571 | + for part in 0..4 { | |
| 572 | + enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part])); | |
| 573 | + if cbfs[part] { | |
| 574 | + let scan = intra::scan_index(modes[part], 2, true); | |
| 575 | + encode_residual(enc, &levels[part], 2, 0, scan); | |
| 576 | + } | |
| 577 | + if part == 3 { | |
| 578 | + let chroma_scan = intra::scan_index(chroma_mode, 2, false); | |
| 579 | + if cb_cbf { | |
| 580 | + let l = std::mem::take(&mut self.scratch.cb_levels); | |
| 581 | + encode_residual(enc, &l[..16], 2, 1, chroma_scan); | |
| 582 | + self.scratch.cb_levels = l; | |
| 583 | + } | |
| 584 | + if cr_cbf { | |
| 585 | + let l = std::mem::take(&mut self.scratch.cr_levels); | |
| 586 | + encode_residual(enc, &l[..16], 2, 2, chroma_scan); | |
| 587 | + self.scratch.cr_levels = l; | |
| 588 | + } | |
| 589 | + } | |
| 590 | + } | |
| 591 | + | |
| 592 | + self.last_cu_empty = !(cbfs.iter().any(|&c| c) || cb_cbf || cr_cbf); | |
| 593 | + let bits = enc.bit_count() - before; | |
| 594 | + self.region_ssd(x, y, 8) + self.lambda * bits as f64 | |
| 595 | + } | |
| 596 | + | |
| 597 | + fn code_cu_2nx2n( | |
| 598 | + &mut self, | |
| 599 | + x: usize, | |
| 600 | + y: usize, | |
| 601 | + log2: u32, | |
| 602 | + depth: u8, | |
| 603 | + enc: &mut CabacEncoder, | |
| 604 | + ) -> f64 { | |
| 487 | 605 | let n = 1usize << log2; |
| 488 | 606 | let before = enc.bit_count(); |
| 489 | 607 | if log2 == MIN_CB_LOG2 { |
| @@ -533,9 +651,22 @@ impl<'a> CtuEncoder<'a> { | ||
| 533 | 651 | } |
| 534 | 652 | |
| 535 | 653 | fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { |
| 654 | + self.write_mode_prev_flag(enc, mode, mpm); | |
| 655 | + self.write_mode_remainder(enc, mode, mpm); | |
| 656 | + } | |
| 657 | + | |
| 658 | + /// `prev_intra_luma_pred_flag`. An NxN coding unit writes all four of these | |
| 659 | + /// before any of the remainders (7.3.8.5), which is why the two halves are | |
| 660 | + /// separate. | |
| 661 | + fn write_mode_prev_flag(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { | |
| 662 | + let is_mpm = mpm.contains(&mode); | |
| 663 | + enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, u32::from(is_mpm)); | |
| 664 | + } | |
| 665 | + | |
| 666 | + /// `mpm_idx` or `rem_intra_luma_pred_mode`, whichever the flag promised. | |
| 667 | + fn write_mode_remainder(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { | |
| 536 | 668 | match mpm.iter().position(|&m| m == mode) { |
| 537 | 669 | Some(idx) => { |
| 538 | - enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, 1); | |
| 539 | 670 | // mpm_idx: truncated rice, cMax 2, all bypass. |
| 540 | 671 | if idx == 0 { |
| 541 | 672 | enc.encode_bypass(0); |
| @@ -545,7 +676,6 @@ impl<'a> CtuEncoder<'a> { | ||
| 545 | 676 | } |
| 546 | 677 | } |
| 547 | 678 | None => { |
| 548 | - enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, 0); | |
| 549 | 679 | let mut sorted = *mpm; |
| 550 | 680 | sorted.sort_unstable(); |
| 551 | 681 | let mut rem = mode; |
crates/ec-h265/src/encoder.rsmodified+7 -0
| @@ -127,6 +127,11 @@ pub struct EncoderConfig { | ||
| 127 | 127 | /// +1.5 dB at QP 22 on a 1080p camera frame, at the same wall time), which |
| 128 | 128 | /// is why 8 is the default. |
| 129 | 129 | pub min_cu_size: usize, |
| 130 | + /// Whether an 8x8 coding unit may split into four 4x4 intra partitions | |
| 131 | + /// (PART_NxN). On: measured at +2.14 dB BD-PSNR on a 2560x1440 screen | |
| 132 | + /// capture (-2.619 dB against x265 without it, -0.479 dB with) and | |
| 133 | + /// +0.007 dB on 1080p film, so it never loses. | |
| 134 | + pub intra_nxn: bool, | |
| 130 | 135 | /// What the samples mean, written into the VUI. |
| 131 | 136 | pub video_signal_type: Option<VideoSignalType>, |
| 132 | 137 | /// Sample aspect ratio. |
| @@ -155,6 +160,7 @@ impl EncoderConfig { | ||
| 155 | 160 | chroma_mode_search: false, |
| 156 | 161 | chroma_rd_weight: 1.0, |
| 157 | 162 | min_cu_size: 8, |
| 163 | + intra_nxn: true, | |
| 158 | 164 | video_signal_type: None, |
| 159 | 165 | sample_aspect_ratio: None, |
| 160 | 166 | timing: None, |
| @@ -529,6 +535,7 @@ impl Encoder { | ||
| 529 | 535 | self.cfg.rdo_candidates, |
| 530 | 536 | self.cfg.chroma_mode_search, |
| 531 | 537 | self.cfg.chroma_rd_weight, |
| 538 | + self.cfg.intra_nxn, | |
| 532 | 539 | self.cfg.min_cu_size.max(8).trailing_zeros(), |
| 533 | 540 | ); |
| 534 | 541 | for col in 0..cols { |
crates/ec-h265/tests/conformance.rsmodified+59 -3
| @@ -90,7 +90,7 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 90 | 90 | |
| 91 | 91 | /// Encode one picture; `ctb` of `None` takes the configured default. |
| 92 | 92 | fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) { |
| 93 | - encode_with(width, height, qp, ctb, false) | |
| 93 | + encode_with(width, height, qp, ctb, false, false) | |
| 94 | 94 | } |
| 95 | 95 | |
| 96 | 96 | fn encode_with( |
| @@ -99,9 +99,11 @@ fn encode_with( | ||
| 99 | 99 | qp: i32, |
| 100 | 100 | ctb: Option<usize>, |
| 101 | 101 | chroma_mode_search: bool, |
| 102 | + intra_nxn: bool, | |
| 102 | 103 | ) -> (VideoFrame, EncodedPicture) { |
| 103 | 104 | let mut cfg = EncoderConfig::new(width, height); |
| 104 | 105 | cfg.chroma_mode_search = chroma_mode_search; |
| 106 | + cfg.intra_nxn = intra_nxn; | |
| 105 | 107 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 106 | 108 | if let Some(ctb) = ctb { |
| 107 | 109 | cfg.ctb_size = ctb; |
| @@ -114,6 +116,26 @@ fn encode_with( | ||
| 114 | 116 | (frame, coded) |
| 115 | 117 | } |
| 116 | 118 | |
| 119 | +/// Same as `encode_with`, but on the grainy natural frame and with no chroma | |
| 120 | +/// mode search — the synthetic test frame is flat enough that the quadtree | |
| 121 | +/// never keeps an 8x8 coding unit, which is the only size PART_NxN applies to. | |
| 122 | +fn encode_natural( | |
| 123 | + width: u32, | |
| 124 | + height: u32, | |
| 125 | + qp: i32, | |
| 126 | + intra_nxn: bool, | |
| 127 | +) -> (VideoFrame, EncodedPicture) { | |
| 128 | + let mut cfg = EncoderConfig::new(width, height); | |
| 129 | + cfg.intra_nxn = intra_nxn; | |
| 130 | + cfg.rate_control = RateControl::ConstantQp(qp); | |
| 131 | + cfg.keep_recon = true; | |
| 132 | + cfg.picture_hash = true; | |
| 133 | + let encoder = Encoder::new(cfg).expect("encoder"); | |
| 134 | + let frame = natural_frame(width, height, 0); | |
| 135 | + let coded = encoder.encode_idr(&frame).expect("encode"); | |
| 136 | + (frame, coded) | |
| 137 | +} | |
| 138 | + | |
| 117 | 139 | /// The chroma mode search is off by default (it loses on screen content, see |
| 118 | 140 | /// `EncoderConfig::chroma_mode_search`), so the shapes above never code an |
| 119 | 141 | /// `intra_chroma_pred_mode` other than the derived one. This exercises the four |
| @@ -126,8 +148,8 @@ fn chroma_mode_search_decodes_bit_exactly() { | ||
| 126 | 148 | return; |
| 127 | 149 | } |
| 128 | 150 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 129 | - let (source, coded) = encode_with(w, h, 27, None, true); | |
| 130 | - let (_, derived) = encode_with(w, h, 27, None, false); | |
| 151 | + let (source, coded) = encode_with(w, h, 27, None, true, false); | |
| 152 | + let (_, derived) = encode_with(w, h, 27, None, false, false); | |
| 131 | 153 | let name = format!("chroma-rd-{w}x{h}"); |
| 132 | 154 | assert_ne!( |
| 133 | 155 | coded.au, derived.au, |
| @@ -147,6 +169,40 @@ fn chroma_mode_search_decodes_bit_exactly() { | ||
| 147 | 169 | } |
| 148 | 170 | } |
| 149 | 171 | |
| 172 | +/// PART_NxN is off by default, so nothing else here codes a four-partition | |
| 173 | +/// coding unit. This does: the stream has to differ from the 2Nx2N-only one — | |
| 174 | +/// proving the partition actually fired — and still decode bit-exactly, which | |
| 175 | +/// is the only check that the inferred transform split, the four `cbf_luma` | |
| 176 | +/// flags at transform depth 1 and the chroma residual riding on the last | |
| 177 | +/// partition are all where the decoder looks for them. | |
| 178 | +#[test] | |
| 179 | +fn intra_nxn_decodes_bit_exactly() { | |
| 180 | + if !have_ffmpeg() { | |
| 181 | + eprintln!("skipping: ffmpeg not installed"); | |
| 182 | + return; | |
| 183 | + } | |
| 184 | + for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | |
| 185 | + let (source, coded) = encode_natural(w, h, 22, true); | |
| 186 | + let (_, square) = encode_natural(w, h, 22, false); | |
| 187 | + let name = format!("intra-nxn-{w}x{h}"); | |
| 188 | + assert_ne!( | |
| 189 | + coded.au, square.au, | |
| 190 | + "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" | |
| 191 | + ); | |
| 192 | + let path = write_au(&name, &coded); | |
| 193 | + let decoded = match ffmpeg_decode(&path) { | |
| 194 | + Ok(bytes) => bytes, | |
| 195 | + Err(e) => panic!("{name}: ffmpeg failed: {e}"), | |
| 196 | + }; | |
| 197 | + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | |
| 198 | + assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | |
| 199 | + let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | |
| 200 | + assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); | |
| 201 | + let quality = psnr(&planes_of(&source), &recon); | |
| 202 | + assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | |
| 203 | + } | |
| 204 | +} | |
| 205 | + | |
| 150 | 206 | #[test] |
| 151 | 207 | fn ffmpeg_decodes_bit_exactly_at_every_shape() { |
| 152 | 208 | if !have_ffmpeg() { |
crates/ec-h265/tests/encode.rsmodified+29 -7
| @@ -435,6 +435,9 @@ fn bd_psnr_vs_x265() { | ||
| 435 | 435 | if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { |
| 436 | 436 | cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); |
| 437 | 437 | } |
| 438 | + if let Ok(v) = std::env::var("EC_H265_NXN") { | |
| 439 | + cfg.intra_nxn = v != "0"; | |
| 440 | + } | |
| 438 | 441 | if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { |
| 439 | 442 | cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); |
| 440 | 443 | } |
| @@ -705,10 +708,34 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Plane | ||
| 705 | 708 | .split_once(',') |
| 706 | 709 | .and_then(|(w, h)| Some((w.parse::<usize>().ok()?, h.parse::<usize>().ok()?))) |
| 707 | 710 | .expect("ffprobe returned dimensions"); |
| 711 | + // Pictures to pass over before sampling: the head of a film is titles and | |
| 712 | + // fades, which are not what a codec is measured on. | |
| 713 | + let skip: usize = std::env::var("EC_H265_CLIP_SKIP") | |
| 714 | + .ok() | |
| 715 | + .and_then(|v| v.parse().ok()) | |
| 716 | + .unwrap_or(0); | |
| 717 | + // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing | |
| 718 | + // afterwards buffers the entire decoded clip in memory: a 1080p feature is | |
| 719 | + // hundreds of gigabytes of raw I420, which the kernel answers with the OOM | |
| 720 | + // killer. `select` drops the skipped pictures inside ffmpeg and | |
| 721 | + // `-frames:v` stops the decode once `want` have come out, so what reaches | |
| 722 | + // this process is exactly `want` frames. | |
| 708 | 723 | let raw = std::process::Command::new("ffmpeg") |
| 709 | 724 | .args(["-v", "error", "-i"]) |
| 710 | 725 | .arg(path) |
| 711 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) | |
| 726 | + .args([ | |
| 727 | + "-vf", | |
| 728 | + &format!("select=gte(n\\,{skip})"), | |
| 729 | + "-fps_mode", | |
| 730 | + "passthrough", | |
| 731 | + "-frames:v", | |
| 732 | + &want.to_string(), | |
| 733 | + "-f", | |
| 734 | + "rawvideo", | |
| 735 | + "-pix_fmt", | |
| 736 | + "yuv420p", | |
| 737 | + "pipe:1", | |
| 738 | + ]) | |
| 712 | 739 | .output() |
| 713 | 740 | .expect("ffmpeg raw extract"); |
| 714 | 741 | assert!( |
| @@ -719,18 +746,13 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Plane | ||
| 719 | 746 | let frame = w * h * 3 / 2; |
| 720 | 747 | assert!( |
| 721 | 748 | raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, |
| 722 | - "clip {} yielded {} bytes, need {want}x{frame}", | |
| 749 | + "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", | |
| 723 | 750 | path.to_string_lossy(), |
| 724 | 751 | raw.stdout.len() |
| 725 | 752 | ); |
| 726 | - let skip: usize = std::env::var("EC_H265_CLIP_SKIP") | |
| 727 | - .ok() | |
| 728 | - .and_then(|v| v.parse().ok()) | |
| 729 | - .unwrap_or(0); | |
| 730 | 753 | let sources: Vec<Planes> = raw |
| 731 | 754 | .stdout |
| 732 | 755 | .chunks(frame) |
| 733 | - .skip(skip) | |
| 734 | 756 | .take(want) |
| 735 | 757 | .map(|f| { |
| 736 | 758 | let (y, rest) = f.split_at(w * h); |