forge
Explore
Log in

Don't you dare go Hollow

Transform skip on 4x4 transform units

Browse files at this commit

f5dbd0bb24f093cad97928de8384a9ebfb4f795eAhmet Kaan GümüşParent: 3c7b63f
  • feat
    • transform skip on 4x4 transform units
Show full message
feat(h265): transform skip on 4x4 transform units

A 4x4 transform unit may now code its residual samples directly instead
of transforming them (transform_skip_flag, 7.3.8.11), which is what
screen content wants: sharp edges spread over every basis function, and
the transform costs bits to undo them.

The PPS carries transform_skip_enabled_flag, the flag itself is coded
per 4x4 TU on its own pair of contexts (luma and chroma, init value 139
in Table 9-25), and the residual path swaps the integer transform for a
pair of shifts. Those shifts are the whole feature: the decoder scales
what it reads by tsShift = 5 + Log2(nTbS) and takes the bit-depth shift
of 12 back off, so a coefficient carries the sample scaled by the
difference. Writing the encoder's own shift as tsShift instead was
caught by the decode: 3117 samples of a 64x64 picture differed.

Off by default, so every existing stream stays byte-identical; the BD
gate reaches it through EC_H265_TSKIP.

Gated by ffmpeg decoding three picture shapes sample for sample against
the encoder's reconstruction, and by a unit round trip over every 8-bit
residual value. Three mutations were checked to fail those: tsShift one
short, the flag never written, and one wrong context init value.
crates/ec-h265/src/cabac.rsmodified+5 -1
@@ -26,8 +26,10 @@ pub mod ctx {
2626 pub const CBF_LUMA: usize = SPLIT_TRANSFORM + 3;
2727 /// `cbf_cb` / `cbf_cr`, 4 contexts.
2828 pub const CBF_CHROMA: usize = CBF_LUMA + 2;
29+ /// `transform_skip_flag`, 2 contexts (luma, chroma).
30+ pub const TRANSFORM_SKIP: usize = CBF_CHROMA + 4;
2931 /// `last_sig_coeff_x_prefix`, 18 contexts.
30- pub const LAST_X: usize = CBF_CHROMA + 4;
32+ pub const LAST_X: usize = TRANSFORM_SKIP + 2;
3133 /// `last_sig_coeff_y_prefix`, 18 contexts.
3234 pub const LAST_Y: usize = LAST_X + 18;
3335 /// `coded_sub_block_flag`, 4 contexts.
@@ -59,6 +61,8 @@ const INIT_VALUES: [u8; ctx::TOTAL] = [
5961 111, 141,
6062 // cbf_cb / cbf_cr (Table 9-22)
6163 94, 138, 182, 154,
64+ // transform_skip_flag (Table 9-25)
65+ 139, 139,
6266 // last_sig_coeff_x_prefix (Table 9-26)
6367 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
6468 // last_sig_coeff_y_prefix (Table 9-27)
crates/ec-h265/src/ctu.rsmodified+93 -19
@@ -26,8 +26,8 @@ use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx};
2626 use crate::intra::{self, Availability, Refs};
2727 use crate::residual::{self, encode_residual};
2828 use crate::transform::{
29- chroma_qp, dequantize, forward_transform, inverse_transform, quantize, quantize_offset,
30- uses_dst,
29+ chroma_qp, dequantize, forward_transform, forward_transform_skip, inverse_transform,
30+ inverse_transform_skip, quantize, quantize_offset, uses_dst,
3131 };
3232 use std::sync::atomic::{AtomicU8, Ordering};
3333
@@ -171,6 +171,7 @@ pub struct CtuEncoder<'a> {
171171 sign_hiding: bool,
172172 /// Whether the levels get a rate-distortion search after quantisation.
173173 rdoq: bool,
174+ transform_skip: bool,
174175 /// The counting CABAC engine that search prices its trials with.
175176 rdoq_enc: CabacEncoder,
176177 /// `log2` of the smallest coding unit the search will produce.
@@ -206,6 +207,7 @@ impl<'a> CtuEncoder<'a> {
206207 intra_nxn: bool,
207208 sign_hiding: bool,
208209 rdoq: bool,
210+ transform_skip: bool,
209211 min_cb_log2: u32,
210212 ) -> CtuEncoder<'a> {
211213 let band_rows = (height - band_y0).min(ctb_size);
@@ -228,6 +230,7 @@ impl<'a> CtuEncoder<'a> {
228230 intra_nxn,
229231 sign_hiding,
230232 rdoq,
233+ transform_skip,
231234 rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),
232235 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
233236 modes: vec![255; (width / 4) * (ctb_size / 4)],
@@ -582,13 +585,17 @@ impl<'a> CtuEncoder<'a> {
582585 // The chroma mode belongs to the coding unit and derives from the
583586 // first partition's luma mode (8.4.3).
584587 let (chroma_mode, chroma_idx) = if self.chroma_rd {
585- self.choose_chroma_mode(x, y, 8, MIN_CB_LOG2, modes[0], enc)
588+ self.choose_chroma_mode(x, y, 8, MIN_CB_LOG2, modes[0], self.transform_skip, enc)
586589 } else {
587590 (modes[0], None)
588591 };
589592 self.write_chroma_mode_syntax(enc, chroma_idx);
590- let cb_cbf = self.code_chroma(x, y, 8, chroma_mode, 1).1;
591- let cr_cbf = self.code_chroma(x, y, 8, chroma_mode, 2).1;
593+ let cb_cbf = self
594+ .code_chroma(x, y, 8, chroma_mode, 1, self.transform_skip)
595+ .1;
596+ let cr_cbf = self
597+ .code_chroma(x, y, 8, chroma_mode, 2, self.transform_skip)
598+ .1;
592599
593600 // transform_tree: the split at depth 0 is inferred from the partition
594601 // mode, so only the chroma flags are written there; every luma flag and
@@ -600,18 +607,42 @@ impl<'a> CtuEncoder<'a> {
600607 enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part]));
601608 if cbfs[part] {
602609 let scan = intra::scan_index(modes[part], 2, true);
603- encode_residual(enc, &levels[part], 2, 0, scan, self.sign_hiding);
610+ encode_residual(
611+ enc,
612+ &levels[part],
613+ 2,
614+ 0,
615+ scan,
616+ self.sign_hiding,
617+ self.transform_skip,
618+ );
604619 }
605620 if part == 3 {
606621 let chroma_scan = intra::scan_index(chroma_mode, 2, false);
607622 if cb_cbf {
608623 let l = std::mem::take(&mut self.scratch.cb_levels);
609- encode_residual(enc, &l[..16], 2, 1, chroma_scan, self.sign_hiding);
624+ encode_residual(
625+ enc,
626+ &l[..16],
627+ 2,
628+ 1,
629+ chroma_scan,
630+ self.sign_hiding,
631+ self.transform_skip,
632+ );
610633 self.scratch.cb_levels = l;
611634 }
612635 if cr_cbf {
613636 let l = std::mem::take(&mut self.scratch.cr_levels);
614- encode_residual(enc, &l[..16], 2, 2, chroma_scan, self.sign_hiding);
637+ encode_residual(
638+ enc,
639+ &l[..16],
640+ 2,
641+ 2,
642+ chroma_scan,
643+ self.sign_hiding,
644+ self.transform_skip,
645+ );
615646 self.scratch.cr_levels = l;
616647 }
617648 }
@@ -631,6 +662,7 @@ impl<'a> CtuEncoder<'a> {
631662 enc: &mut CabacEncoder,
632663 ) -> f64 {
633664 let n = 1usize << log2;
665+ let chroma_tskip = self.transform_skip && n == 8;
634666 let before = enc.bit_count();
635667 if log2 == MIN_CB_LOG2 {
636668 // part_mode: PART_2Nx2N is the single bin 1.
@@ -640,7 +672,7 @@ impl<'a> CtuEncoder<'a> {
640672 let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc);
641673 self.write_mode_syntax(enc, mode, &mpm);
642674 let (chroma_mode, chroma_idx) = if self.chroma_rd {
643- self.choose_chroma_mode(x, y, n, log2, mode, enc)
675+ self.choose_chroma_mode(x, y, n, log2, mode, chroma_tskip, enc)
644676 } else {
645677 (mode, None)
646678 };
@@ -648,8 +680,8 @@ impl<'a> CtuEncoder<'a> {
648680
649681 // Luma was reconstructed by the mode search; chroma is coded now.
650682 let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0);
651- let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1).1;
652- let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2).1;
683+ let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1;
684+ let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1;
653685
654686 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
655687 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
@@ -657,7 +689,15 @@ impl<'a> CtuEncoder<'a> {
657689 if luma_cbf {
658690 let scan = intra::scan_index(mode, log2, true);
659691 let levels = std::mem::take(&mut self.scratch.luma_levels);
660- encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding);
692+ encode_residual(
693+ enc,
694+ &levels[..n * n],
695+ log2,
696+ 0,
697+ scan,
698+ self.sign_hiding,
699+ self.transform_skip,
700+ );
661701 self.scratch.luma_levels = levels;
662702 }
663703 let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);
@@ -670,6 +710,7 @@ impl<'a> CtuEncoder<'a> {
670710 1,
671711 chroma_scan,
672712 self.sign_hiding,
713+ chroma_tskip,
673714 );
674715 self.scratch.cb_levels = levels;
675716 }
@@ -682,6 +723,7 @@ impl<'a> CtuEncoder<'a> {
682723 2,
683724 chroma_scan,
684725 self.sign_hiding,
726+ chroma_tskip,
685727 );
686728 self.scratch.cr_levels = levels;
687729 }
@@ -867,7 +909,15 @@ impl<'a> CtuEncoder<'a> {
867909 if cbf {
868910 let scan = intra::scan_index(mode, log2, true);
869911 let levels = std::mem::take(&mut self.scratch.levels);
870- encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding);
912+ encode_residual(
913+ enc,
914+ &levels[..n * n],
915+ log2,
916+ 0,
917+ scan,
918+ self.sign_hiding,
919+ self.transform_skip,
920+ );
871921 self.scratch.levels = levels;
872922 }
873923 let bits = enc.bit_count() - bits_before;
@@ -906,8 +956,13 @@ impl<'a> CtuEncoder<'a> {
906956 for (i, &sample) in source[..n * n].iter().enumerate() {
907957 self.scratch.residual[i] = i32::from(sample) - i32::from(self.scratch.pred[i]);
908958 }
959+ let skip = self.transform_skip && n == 4;
909960 let dst = uses_dst(n, true);
910- forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
961+ if skip {
962+ forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, n);
963+ } else {
964+ forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
965+ }
911966 let mut nonzero = if self.rdoq {
912967 quantize_offset(
913968 &self.scratch.coeffs,
@@ -929,6 +984,7 @@ impl<'a> CtuEncoder<'a> {
929984 intra::scan_index(mode, n.trailing_zeros(), true),
930985 ctx::CBF_LUMA + 1,
931986 self.lambda,
987+ skip,
932988 &mut self.rdoq_enc,
933989 );
934990 }
@@ -944,7 +1000,11 @@ impl<'a> CtuEncoder<'a> {
9441000 let cbf = nonzero > 0;
9451001 if cbf {
9461002 dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp);
947- inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, n, dst);
1003+ if skip {
1004+ inverse_transform_skip(&self.scratch.scaled, &mut self.scratch.residual, n);
1005+ } else {
1006+ inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, n, dst);
1007+ }
9481008 } else {
9491009 self.scratch.residual[..n * n].fill(0);
9501010 }
@@ -968,6 +1028,7 @@ impl<'a> CtuEncoder<'a> {
9681028 n: usize,
9691029 pred_mode: u8,
9701030 plane: usize,
1031+ skip: bool,
9711032 ) -> (f64, bool) {
9721033 let cn = n / 2;
9731034 let (cx, cy) = (x / 2, y / 2);
@@ -989,7 +1050,11 @@ impl<'a> CtuEncoder<'a> {
9891050 s - i32::from(self.scratch.pred[row * cn + col]);
9901051 }
9911052 }
992- forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
1053+ if skip && cn == 4 {
1054+ forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, cn);
1055+ } else {
1056+ forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
1057+ }
9931058 let mut nonzero = if self.rdoq {
9941059 quantize_offset(
9951060 &self.scratch.coeffs,
@@ -1016,6 +1081,7 @@ impl<'a> CtuEncoder<'a> {
10161081 intra::scan_index(pred_mode, cn.trailing_zeros(), false),
10171082 ctx::CBF_CHROMA,
10181083 self.lambda,
1084+ skip && cn == 4,
10191085 &mut self.rdoq_enc,
10201086 );
10211087 }
@@ -1036,7 +1102,11 @@ impl<'a> CtuEncoder<'a> {
10361102 cn,
10371103 self.qp_c,
10381104 );
1039- inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, cn, false);
1105+ if skip && cn == 4 {
1106+ inverse_transform_skip(&self.scratch.scaled, &mut self.scratch.residual, cn);
1107+ } else {
1108+ inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, cn, false);
1109+ }
10401110 } else {
10411111 self.scratch.residual[..cn * cn].fill(0);
10421112 }
@@ -1082,6 +1152,7 @@ impl<'a> CtuEncoder<'a> {
10821152 /// Returns the mode and the index to code, `None` meaning derived. Neither
10831153 /// the winner's reconstruction nor its levels survive the trial: the caller
10841154 /// codes the winner again for real.
1155+ #[allow(clippy::too_many_arguments)]
10851156 fn choose_chroma_mode(
10861157 &mut self,
10871158 x: usize,
@@ -1089,6 +1160,7 @@ impl<'a> CtuEncoder<'a> {
10891160 n: usize,
10901161 log2: u32,
10911162 luma_mode: u8,
1163+ chroma_tskip: bool,
10921164 enc: &mut CabacEncoder,
10931165 ) -> (u8, Option<u32>) {
10941166 let mut explicit = [0u8, 26, 10, 1];
@@ -1109,8 +1181,8 @@ impl<'a> CtuEncoder<'a> {
11091181 {
11101182 let bits_before = enc.bit_count();
11111183 self.write_chroma_mode_syntax(enc, i);
1112- let (cb_ssd, cb_cbf) = self.code_chroma(x, y, n, mode, 1);
1113- let (cr_ssd, cr_cbf) = self.code_chroma(x, y, n, mode, 2);
1184+ let (cb_ssd, cb_cbf) = self.code_chroma(x, y, n, mode, 1, chroma_tskip);
1185+ let (cr_ssd, cr_cbf) = self.code_chroma(x, y, n, mode, 2, chroma_tskip);
11141186 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
11151187 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
11161188 let scan = intra::scan_index(mode, log2 - 1, false);
@@ -1123,6 +1195,7 @@ impl<'a> CtuEncoder<'a> {
11231195 1,
11241196 scan,
11251197 self.sign_hiding,
1198+ chroma_tskip,
11261199 );
11271200 self.scratch.cb_levels = levels;
11281201 }
@@ -1135,6 +1208,7 @@ impl<'a> CtuEncoder<'a> {
11351208 2,
11361209 scan,
11371210 self.sign_hiding,
1211+ chroma_tskip,
11381212 );
11391213 self.scratch.cr_levels = levels;
11401214 }
crates/ec-h265/src/encoder.rsmodified+15 -0
@@ -47,6 +47,16 @@ pub enum RateControl {
4747 TargetBits(u64),
4848 }
4949
50+/// Whether 4x4 transform units may skip the transform and code residual
51+/// samples directly (`transform_skip_enabled_flag`).
52+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53+pub enum TransformSkip {
54+ /// No transform skip; every default stream is byte-identical.
55+ Off,
56+ /// Skip the transform on every 4x4 TU that has non-zero residual.
57+ AlwaysFor4x4,
58+}
59+
5060 /// Encoder settings.
5161 #[derive(Debug, Clone)]
5262 pub struct EncoderConfig {
@@ -155,6 +165,8 @@ pub struct EncoderConfig {
155165 /// coder's own price for the whole block, so dropping a level is priced
156166 /// with the significance map and last position that follow from it.
157167 pub rdoq: bool,
168+ /// Whether 4x4 TUs may skip the integer transform.
169+ pub transform_skip: TransformSkip,
158170 /// What the samples mean, written into the VUI.
159171 pub video_signal_type: Option<VideoSignalType>,
160172 /// Sample aspect ratio.
@@ -186,6 +198,7 @@ impl EncoderConfig {
186198 intra_nxn: true,
187199 sign_hiding: false,
188200 rdoq: true,
201+ transform_skip: TransformSkip::Off,
189202 video_signal_type: None,
190203 sample_aspect_ratio: None,
191204 timing: None,
@@ -315,6 +328,7 @@ impl Encoder {
315328 // that identity (and the picture-hash check that rides on it)
316329 // rather than a fraction of a dB.
317330 sign_data_hiding_enabled: cfg.sign_hiding,
331+ transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,
318332 deblocking_filter_control_present: true,
319333 deblocking_filter_disabled: true,
320334 loop_filter_across_slices_enabled: false,
@@ -564,6 +578,7 @@ impl Encoder {
564578 self.cfg.intra_nxn,
565579 self.cfg.sign_hiding,
566580 self.cfg.rdoq,
581+ self.cfg.transform_skip != TransformSkip::Off,
567582 self.cfg.min_cu_size.max(8).trailing_zeros(),
568583 );
569584 for col in 0..cols {
crates/ec-h265/src/residual.rsmodified+47 -7
@@ -225,12 +225,21 @@ fn levels_bits(
225225 scan_idx: usize,
226226 cbf_ctx: usize,
227227 coded: bool,
228+ transform_skip: bool,
228229 ) -> u64 {
229230 enc.restore(base);
230231 let before = enc.bit_count();
231232 enc.encode_bin(cbf_ctx, u32::from(coded));
232233 if coded {
233- encode_residual(enc, levels, log2_size, c_idx, scan_idx, false);
234+ encode_residual(
235+ enc,
236+ levels,
237+ log2_size,
238+ c_idx,
239+ scan_idx,
240+ false,
241+ transform_skip,
242+ );
234243 }
235244 enc.bit_count() - before
236245 }
@@ -257,6 +266,7 @@ pub fn rdoq(
257266 scan_idx: usize,
258267 cbf_ctx: usize,
259268 lambda: f64,
269+ transform_skip: bool,
260270 enc: &mut CabacEncoder,
261271 ) -> usize {
262272 let log2_size = n.trailing_zeros();
@@ -270,7 +280,15 @@ pub fn rdoq(
270280
271281 let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum();
272282 let bits = levels_bits(
273- enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, true,
283+ enc,
284+ &base,
285+ levels,
286+ log2_size,
287+ c_idx,
288+ scan_idx,
289+ cbf_ctx,
290+ true,
291+ transform_skip,
274292 );
275293 let mut cost = scale * dist + lambda * bits as f64;
276294
@@ -302,8 +320,17 @@ pub fn rdoq(
302320 levels[i] = candidate * level.signum();
303321 let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
304322 let any = levels[..n * n].iter().any(|&l| l != 0);
305- let trial_bits =
306- levels_bits(enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, any);
323+ let trial_bits = levels_bits(
324+ enc,
325+ &base,
326+ levels,
327+ log2_size,
328+ c_idx,
329+ scan_idx,
330+ cbf_ctx,
331+ any,
332+ transform_skip,
333+ );
307334 let trial = scale * trial_dist + lambda * trial_bits as f64;
308335 if trial < cost {
309336 cost = trial;
@@ -317,7 +344,15 @@ pub fn rdoq(
317344 // as every level, which no single-coefficient step can see.
318345 let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum();
319346 let zero_bits = levels_bits(
320- enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, false,
347+ enc,
348+ &base,
349+ levels,
350+ log2_size,
351+ c_idx,
352+ scan_idx,
353+ cbf_ctx,
354+ false,
355+ transform_skip,
321356 );
322357 if scale * zero_dist + lambda * zero_bits as f64 <= cost {
323358 levels[..n * n].fill(0);
@@ -340,7 +375,12 @@ pub fn encode_residual(
340375 c_idx: usize,
341376 scan_idx: usize,
342377 sign_hiding: bool,
378+ transform_skip: bool,
343379 ) {
380+ if transform_skip && log2_size == 2 {
381+ let ctx_idx = ctx::TRANSFORM_SKIP + if c_idx == 0 { 0 } else { 1 };
382+ enc.encode_bin(ctx_idx, 1);
383+ }
344384 let n = 1usize << log2_size;
345385 let sub_wide = n >> 2;
346386 let sub_scan = scan(log2_size - 2, scan_idx);
@@ -698,7 +738,7 @@ mod tests {
698738 let mut costs = Vec::new();
699739 for levels in [&sparse, &dense] {
700740 let mut enc = CabacEncoder::counter(Contexts::new(30));
701- encode_residual(&mut enc, levels, 3, 0, 0, false);
741+ encode_residual(&mut enc, levels, 3, 0, 0, false, false);
702742 costs.push(enc.bit_count());
703743 }
704744 assert!(costs[0] < costs[1], "{costs:?}");
@@ -724,7 +764,7 @@ mod tests {
724764 };
725765 }
726766 let mut enc = CabacEncoder::counter(Contexts::new(27));
727- encode_residual(&mut enc, &levels, log2, c_idx, scan_idx, false);
767+ encode_residual(&mut enc, &levels, log2, c_idx, scan_idx, false, false);
728768 assert!(enc.bit_count() > 0);
729769 }
730770 }
crates/ec-h265/src/transform.rsmodified+46 -1
@@ -217,6 +217,9 @@ pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_typ
217217 }
218218 }
219219
220+/// `bdShift` (8-299) at 8-bit: 20 - BitDepth.
221+const BD_SHIFT: i32 = 12;
222+
220223 /// Inverse transform of scaled coefficients into residual samples, exactly as
221224 /// clause 8.6.4 specifies including its intermediate clipping.
222225 pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) {
@@ -252,7 +255,6 @@ pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_typ
252255 }
253256 }
254257 // Stage 2: every row, then the bit-depth shift (8-299).
255- const BD_SHIFT: i32 = 12; // 20 - bitDepth, 8-bit
256258 let round = 1 << (BD_SHIFT - 1);
257259 for y in 0..n {
258260 col[..n].copy_from_slice(&e[y * n..y * n + n]);
@@ -271,6 +273,32 @@ pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_typ
271273 }
272274 }
273275
276+/// Forward transform skip (8.6.2): no transform at all, the residual samples
277+/// standing in for coefficients.
278+///
279+/// The decoder scales what it reads by `tsShift = 5 + Log2(nTbS)` and then
280+/// takes the bit-depth shift of 20 - 8 off it again, so a coefficient has to
281+/// carry the residual scaled by the difference for the round trip to return
282+/// the sample it started from — a factor of 32 at 4x4, the same gain the
283+/// integer transform leaves behind.
284+pub fn forward_transform_skip(residual: &[i32], coeffs: &mut [i32], n: usize) {
285+ let shift = BD_SHIFT - (5 + n.trailing_zeros() as i32);
286+ for (i, &r) in residual[..n * n].iter().enumerate() {
287+ coeffs[i] = r << shift;
288+ }
289+}
290+
291+/// Inverse transform skip (8.6.2): the scaled coefficient shifted up by
292+/// `tsShift` and then down by the bit-depth shift, exactly as the decoder
293+/// does it, so the encoder reconstructs the samples the decoder will.
294+pub fn inverse_transform_skip(scaled: &[i32], residual: &mut [i32], n: usize) {
295+ let ts_shift = 5 + n.trailing_zeros() as i32;
296+ let round = 1i32 << (BD_SHIFT - 1);
297+ for (i, &d) in scaled[..n * n].iter().enumerate() {
298+ residual[i] = ((d.clamp(COEFF_MIN, COEFF_MAX) << ts_shift) + round) >> BD_SHIFT;
299+ }
300+}
301+
274302 /// Quantise coefficients in place, returning the number of non-zero levels.
275303 ///
276304 /// The rounding offset is a third of a step, which is the intra bias every
@@ -490,6 +518,23 @@ mod tests {
490518 }
491519 }
492520
521+ /// Transform skip is only a pair of shifts, so the pair has to be exact:
522+ /// what the encoder writes as a coefficient must come back as the residual
523+ /// sample it started from, for every sample an 8-bit residual can hold.
524+ #[test]
525+ fn transform_skip_round_trips_every_residual_sample() {
526+ let residual: Vec<i32> = (-255..=255).collect();
527+ for chunk in residual.chunks(16) {
528+ let mut block = [0i32; 16];
529+ block[..chunk.len()].copy_from_slice(chunk);
530+ let mut coeffs = [0i32; 16];
531+ forward_transform_skip(&block, &mut coeffs, 4);
532+ let mut back = [0i32; 16];
533+ inverse_transform_skip(&coeffs, &mut back, 4);
534+ assert_eq!(back, block, "transform skip is not its own inverse");
535+ }
536+ }
537+
493538 #[test]
494539 fn dc_only_coefficient_is_flat_after_inverse() {
495540 // The spec's inverse of a DC-only block is a constant; a transposed
crates/ec-h265/tests/conformance.rsmodified+52 -1
@@ -8,7 +8,7 @@ mod common;
88
99 use common::{natural_frame, test_frame};
1010 use ec_core::frame::VideoFrame;
11-use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl};
11+use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip};
1212 use std::io::Write;
1313 use std::path::{Path, PathBuf};
1414 use std::process::Command;
@@ -255,6 +255,57 @@ fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFram
255255 (frame, coded)
256256 }
257257
258+/// The natural frame coded with transform skip on or off, everything else
259+/// left at its default.
260+fn encode_tskip(
261+ width: u32,
262+ height: u32,
263+ qp: i32,
264+ tskip: TransformSkip,
265+) -> (VideoFrame, EncodedPicture) {
266+ let mut cfg = EncoderConfig::new(width, height);
267+ cfg.transform_skip = tskip;
268+ cfg.rate_control = RateControl::ConstantQp(qp);
269+ cfg.keep_recon = true;
270+ cfg.picture_hash = true;
271+ let encoder = Encoder::new(cfg).expect("encoder");
272+ let frame = natural_frame(width, height, 0);
273+ let coded = encoder.encode_idr(&frame).expect("encode");
274+ (frame, coded)
275+}
276+
277+/// Transform skip bypasses the integer transform on 4x4 TUs, coding residual
278+/// samples directly with a fixed shift. The encoder and decoder agree only if
279+/// the shift matches on both sides; the stream has to differ from the
280+/// skip-off one, and ffmpeg's decode has to match the encoder's reconstruction
281+/// sample for sample.
282+#[test]
283+fn transform_skip_decodes_bit_exactly() {
284+ if !have_ffmpeg() {
285+ eprintln!("skipping: ffmpeg not installed");
286+ return;
287+ }
288+ for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] {
289+ let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4);
290+ let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off);
291+ let name = format!("transform-skip-{w}x{h}");
292+ assert_ne!(
293+ coded.au, plain.au,
294+ "{name}: no TU ever skipped, so this decode proves nothing"
295+ );
296+ let path = write_au(&name, &coded);
297+ let decoded = match ffmpeg_decode(&path) {
298+ Ok(bytes) => bytes,
299+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
300+ };
301+ let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
302+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
303+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
304+ assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");
305+ let quality = psnr(&planes_of(&source), &recon);
306+ assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");
307+ }
308+}
258309 #[test]
259310 fn ffmpeg_decodes_bit_exactly_at_every_shape() {
260311 if !have_ffmpeg() {
crates/ec-h265/tests/encode.rsmodified+8 -1
@@ -7,7 +7,7 @@
77 //! the comparison is at matched features, not at matched marketing.
88
99 use ec_core::frame::VideoFrame;
10-use ec_h265::encoder::{Encoder, EncoderConfig, RateControl};
10+use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip};
1111
1212 /// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed.
1313 type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
@@ -441,6 +441,13 @@ fn bd_psnr_vs_x265() {
441441 if let Ok(v) = std::env::var("EC_H265_RDOQ") {
442442 cfg.rdoq = v != "0";
443443 }
444+ if let Ok(v) = std::env::var("EC_H265_TSKIP") {
445+ cfg.transform_skip = if v != "0" {
446+ TransformSkip::AlwaysFor4x4
447+ } else {
448+ TransformSkip::Off
449+ };
450+ }
444451 if let Ok(v) = std::env::var("EC_H265_NXN") {
445452 cfg.intra_nxn = v != "0";
446453 }