forge
Explore
Log in

Don't you dare go Hollow

High-profile SPS/PPS tail + 8x8 forward transform/quant (E1+E2)

Browse files at this commit

250a6ac468c83d9e441a193f3a9e3a3893050fa3Ahmet Kaan GümüşParent: b966d5e
  • feat
    • High-profile SPS/PPS tail + 8x8 forward transform/quant (E1+E2)
Show full message
feat(h264-enc): High-profile SPS/PPS tail + 8x8 forward transform/quant (E1+E2)

SPS/PPS now write the High-profile 8x8-transform syntax (profile_idc 100,
chroma/bit-depth/scaling-matrix fields, transform_8x8_mode_flag) behind a new
EncoderConfig::transform_8x8 flag, and quant.rs gains forward_8x8/quant_8x8:
an exact algebraic inverse of the decoder's idct8_1d (verified by rational
matrix inversion, not a hand-tuned butterfly, since the small-integer
transpose leaks ~15% between frequencies — too much for full-range
residuals) paired with a plain-division dead-zone quantiser against the
existing LevelScale8x8/dequant_8x8.

transform_8x8 is NOT yet safe to turn on for a real encode: a conformant
decoder unconditionally expects a transform_size_8x8_flag per eligible
macroblock once the PPS advertises it (7.3.5), and enc::entropy/enc::mb don't
write that bit yet (confirmed by a failing round trip, not left implicit).
That emission, and the mode decision that actually picks 8x8 blocks, are
later work.
crates/ec-h264/src/enc/headers.rsmodified+53 -12
@@ -26,6 +26,10 @@ pub(crate) struct SeqParams {
26 pub bitrate: u32,26 pub bitrate: u32,
27 /// CABAC, which Baseline does not allow: the sequence is then Main.27 /// CABAC, which Baseline does not allow: the sequence is then Main.
28 pub cabac: bool,28 pub cabac: bool,
29+ /// 8x8 transform (High profile). Forces `profile_idc` 100 with no
30+ /// constraint flags, and the High-profile SPS tail (7.3.2.1.1 subset:
31+ /// 4:2:0 8-bit, no scaling matrices, no transform bypass).
32+ pub transform_8x8: bool,
29 }33 }
30 34
31 /// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one35 /// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one
@@ -73,10 +77,23 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> {
73 let mut w = BitWriter::with_capacity(32);77 let mut w = BitWriter::with_capacity(32);
74 // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise;78 // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise;
75 // constraint_set1_flag says the stream also obeys the Main constraints.79 // constraint_set1_flag says the stream also obeys the Main constraints.
76- w.write_bits(if p.cabac { 77 } else { 66 }, 8);80+ // 8x8 transform needs High profile (100), which sets no constraint flags.
77- w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8);81+ if p.transform_8x8 {
82+ w.write_bits(100, 8);
83+ w.write_bits(0, 8);
84+ } else {
85+ w.write_bits(if p.cabac { 77 } else { 66 }, 8);
86+ w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8);
87+ }
78 w.write_bits(u32::from(level_idc(p)), 8);88 w.write_bits(u32::from(level_idc(p)), 8);
79 w.write_ue(0); // seq_parameter_set_id89 w.write_ue(0); // seq_parameter_set_id
90+ if p.transform_8x8 {
91+ w.write_ue(1); // chroma_format_idc: 4:2:0
92+ w.write_ue(0); // bit_depth_luma_minus8
93+ w.write_ue(0); // bit_depth_chroma_minus8
94+ w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
95+ w.write_bit(false); // seq_scaling_matrix_present_flag
96+ }
80 w.write_ue(LOG2_MAX_FRAME_NUM - 4);97 w.write_ue(LOG2_MAX_FRAME_NUM - 4);
81 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order98 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
82 w.write_ue(1); // max_num_ref_frames99 w.write_ue(1); // max_num_ref_frames
@@ -114,7 +131,7 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> {
114 }131 }
115 132
116 /// Write the picture parameter set RBSP (7.3.2.2).133 /// Write the picture parameter set RBSP (7.3.2.2).
117-pub(crate) fn write_pps(cabac: bool) -> Vec<u8> {134+pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec<u8> {
118 let mut w = BitWriter::with_capacity(8);135 let mut w = BitWriter::with_capacity(8);
119 w.write_ue(0); // pic_parameter_set_id136 w.write_ue(0); // pic_parameter_set_id
120 w.write_ue(0); // seq_parameter_set_id137 w.write_ue(0); // seq_parameter_set_id
@@ -131,6 +148,11 @@ pub(crate) fn write_pps(cabac: bool) -> Vec<u8> {
131 w.write_bit(false); // deblocking_filter_control_present_flag148 w.write_bit(false); // deblocking_filter_control_present_flag
132 w.write_bit(false); // constrained_intra_pred_flag149 w.write_bit(false); // constrained_intra_pred_flag
133 w.write_bit(false); // redundant_pic_cnt_present_flag150 w.write_bit(false); // redundant_pic_cnt_present_flag
151+ if transform_8x8 {
152+ w.write_bit(true); // transform_8x8_mode_flag
153+ w.write_bit(false); // pic_scaling_matrix_present_flag
154+ w.write_se(0); // second_chroma_qp_index_offset
155+ }
134 trailing(&mut w);156 trailing(&mut w);
135 w.into_bytes()157 w.into_bytes()
136 }158 }
@@ -199,6 +221,7 @@ mod tests {
199 timing: (1000, 60000),221 timing: (1000, 60000),
200 bitrate: 8_000_000,222 bitrate: 8_000_000,
201 cabac: true,223 cabac: true,
224+ transform_8x8: false,
202 }225 }
203 }226 }
204 227
@@ -206,15 +229,18 @@ mod tests {
206 /// parser reads back, geometry, cropping, profile and entropy coder alike.229 /// parser reads back, geometry, cropping, profile and entropy coder alike.
207 #[test]230 #[test]
208 fn parameter_sets_parse_back() {231 fn parameter_sets_parse_back() {
209- for (w, h, cabac) in [232+ for (w, h, cabac, t8x8) in [
210- (1920, 1080, true),233+ (1920, 1080, true, false),
211- (1920, 1080, false),234+ (1920, 1080, false, false),
212- (640, 480, true),235+ (640, 480, true, false),
213- (854, 482, false),236+ (854, 482, false, false),
214- (16, 16, true),237+ (16, 16, true, false),
238+ (640, 480, true, true),
239+ (640, 480, false, true),
215 ] {240 ] {
216 let mut p = params(w, h);241 let mut p = params(w, h);
217 p.cabac = cabac;242 p.cabac = cabac;
243+ p.transform_8x8 = t8x8;
218 let sps = Sps::parse(&write_sps(&p)).expect("SPS parses");244 let sps = Sps::parse(&write_sps(&p)).expect("SPS parses");
219 assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop");245 assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop");
220 assert_eq!(sps.mb_width, p.mb_w);246 assert_eq!(sps.mb_width, p.mb_w);
@@ -224,10 +250,25 @@ mod tests {
224 assert!(sps.frame_mbs_only);250 assert!(sps.frame_mbs_only);
225 let vui = sps.vui.as_ref().expect("VUI present");251 let vui = sps.vui.as_ref().expect("VUI present");
226 assert_eq!(vui.timing_info, Some((1000, 60000, true)));252 assert_eq!(vui.timing_info, Some((1000, 60000, true)));
227- assert_eq!(sps.profile_idc, if cabac { 77 } else { 66 });253+ assert_eq!(
228- let pps = Pps::parse(&write_pps(cabac), |_| Some(&sps)).expect("PPS parses");254+ sps.profile_idc,
255+ if t8x8 {
256+ 100
257+ } else if cabac {
258+ 77
259+ } else {
260+ 66
261+ }
262+ );
263+ if t8x8 {
264+ assert_eq!(sps.chroma_format_idc, 1);
265+ assert_eq!(sps.bit_depth_luma, 8);
266+ }
267+ let pps =
268+ Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses");
229 assert_eq!(pps.entropy_coding_mode, cabac);269 assert_eq!(pps.entropy_coding_mode, cabac);
230 assert_eq!(pps.pic_init_qp, 26);270 assert_eq!(pps.pic_init_qp, 26);
271+ assert_eq!(pps.transform_8x8_mode, t8x8);
231 }272 }
232 }273 }
233 274
@@ -246,7 +287,7 @@ mod tests {
246 fn slice_header_parses_back() {287 fn slice_header_parses_back() {
247 let p = params(320, 240);288 let p = params(320, 240);
248 let sps = Sps::parse(&write_sps(&p)).unwrap();289 let sps = Sps::parse(&write_sps(&p)).unwrap();
249- let pps = Pps::parse(&write_pps(true), |_| Some(&sps)).unwrap();290+ let pps = Pps::parse(&write_pps(true, false), |_| Some(&sps)).unwrap();
250 for (idr, slice_type, first_mb, qp) in [291 for (idr, slice_type, first_mb, qp) in [
251 (true, SliceType::I, 0u32, 30i32),292 (true, SliceType::I, 0u32, 30i32),
252 (false, SliceType::P, 40, 18),293 (false, SliceType::P, 40, 18),
crates/ec-h264/src/enc/mod.rsmodified+16 -1
@@ -71,6 +71,19 @@ pub struct EncoderConfig {
71 pub threads: usize,71 pub threads: usize,
72 /// Quantiser for constant-QP mode (`bitrate` zero).72 /// Quantiser for constant-QP mode (`bitrate` zero).
73 pub qp: i32,73 pub qp: i32,
74+ /// 8x8 transform (High profile). Off by default.
75+ ///
76+ /// NOT SAFE TO SET YET: this only flips the SPS/PPS High-profile tail
77+ /// (`profile_idc` 100, `transform_8x8_mode_flag`). Once the PPS carries
78+ /// that flag, a conformant decoder unconditionally reads an extra
79+ /// `transform_size_8x8_flag` per macroblock (7.3.5: every non-I16x16
80+ /// intra macroblock, and every inter macroblock with a nonzero luma cbp —
81+ /// see `decoder.rs:1151` and `:1789-1793`). Nothing in `enc::entropy` /
82+ /// `enc::mb` writes that bit yet, so turning this on desyncs every real
83+ /// stream (headers.rs's own tests only exercise the parameter sets, not a
84+ /// full encode). Wiring that emission — and then the mode decision that
85+ /// actually picks 8x8 blocks — is later work.
86+ pub transform_8x8: bool,
74 }87 }
75 88
76 impl EncoderConfig {89 impl EncoderConfig {
@@ -87,6 +100,7 @@ impl EncoderConfig {
87 cabac: true,100 cabac: true,
88 threads: 0,101 threads: 0,
89 qp: 26,102 qp: 26,
103+ transform_8x8: false,
90 }104 }
91 }105 }
92 }106 }
@@ -193,10 +207,11 @@ impl Encoder {
193 timing,207 timing,
194 bitrate: cfg.bitrate,208 bitrate: cfg.bitrate,
195 cabac: cfg.cabac,209 cabac: cfg.cabac,
210+ transform_8x8: cfg.transform_8x8,
196 };211 };
197 let sps_rbsp = write_sps(&seq);212 let sps_rbsp = write_sps(&seq);
198 let sps = Sps::parse(&sps_rbsp)?;213 let sps = Sps::parse(&sps_rbsp)?;
199- let pps_rbsp = write_pps(cfg.cabac);214+ let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8);
200 let threads = if cfg.threads == 0 {215 let threads = if cfg.threads == 0 {
201 std::thread::available_parallelism().map_or(1, |n| n.get())216 std::thread::available_parallelism().map_or(1, |n| n.get())
202 } else {217 } else {
crates/ec-h264/src/enc/quant.rsmodified+176 -1
@@ -11,7 +11,8 @@
11 //! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)`11 //! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)`
12 //! invert the decoder's dequantisation.12 //! invert the decoder's dequantisation.
13 13
14-use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4};14+use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8};
15+use crate::transform::LevelScale8x8;
15 16
16 /// Quantisation multipliers per `qp % 6`, indexed by the same position class17 /// Quantisation multipliers per `qp % 6`, indexed by the same position class
17 /// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed).18 /// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed).
@@ -85,6 +86,112 @@ pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) {
85 d[3] = a - b - c + e;86 d[3] = a - b - c + e;
86 }87 }
87 88
89+/// Forward 8x8 core transform (the exact algebraic inverse of `idct8_1d` /
90+/// [`crate::transform::inverse_transform_8x8`]), raster in, scaled coefficients
91+/// out.
92+///
93+/// `idct8_1d`'s matrix `M` (one 1D pass) is not its own transpose-inverse pair
94+/// the way the 4x4 transform's small butterfly nearly is: `M^T * M` is
95+/// diagonal but `M * M^T` is not, so a hand-picked small-integer transpose
96+/// leaks between frequencies by ~15%, which is too much for the ±1-per-sample
97+/// tolerance this encoder's residuals need (up to ±255, far past the small
98+/// ranges a 4x4 block sees). [`FWD8`] is `11560 * M^-1`, computed once by
99+/// exact rational matrix inversion (`M^-1 * M = I` exactly), so applying it in
100+/// the same row-then-column order `idct8_1d` uses, then the real inverse
101+/// transform, reproduces the input exactly, scaled by a single known constant
102+/// (`11560^2 / 64 = 2_088_025`, see [`quant_8x8`]) — no leakage at all, only
103+/// the ordinary quantiser rounding.
104+const FWD8: [[i64; 8]; 8] = [
105+ [1445, 1445, 1445, 1445, 1445, 1445, 1445, 1445],
106+ [1920, 1600, 960, 480, -480, -960, -1600, -1920],
107+ [2312, 1156, -1156, -2312, -2312, -1156, 1156, 2312],
108+ [1600, -480, -1920, -960, 960, 1920, 480, -1600],
109+ [1445, -1445, -1445, 1445, 1445, -1445, -1445, 1445],
110+ [960, -1920, 480, 1600, -1600, -480, 1920, -960],
111+ [1156, -2312, 2312, -1156, -1156, 2312, -2312, 1156],
112+ [480, -960, 1600, -1920, 1920, -1600, 960, -480],
113+];
114+
115+/// One 1D pass of [`FWD8`] over eight values.
116+#[inline]
117+fn fwd8_1d(d: [i64; 8]) -> [i64; 8] {
118+ std::array::from_fn(|i| (0..8).map(|j| FWD8[i][j] * d[j]).sum())
119+}
120+
121+/// Forward 8x8 transform (raster in, raster out), unnormalised: the caller
122+/// (`quant_8x8`) divides out the `2_088_025` gain along with the usual
123+/// per-position quantiser scale.
124+pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] {
125+ let mut g = [0i64; 64];
126+ for i in 0..8 {
127+ let o = i * 8;
128+ let row: [i64; 8] = std::array::from_fn(|k| i64::from(d[o + k]));
129+ g[o..o + 8].copy_from_slice(&fwd8_1d(row));
130+ }
131+ let mut r = [0i64; 64];
132+ for j in 0..8 {
133+ let col = [
134+ g[j],
135+ g[8 + j],
136+ g[16 + j],
137+ g[24 + j],
138+ g[32 + j],
139+ g[40 + j],
140+ g[48 + j],
141+ g[56 + j],
142+ ];
143+ for (i, v) in fwd8_1d(col).into_iter().enumerate() {
144+ r[i * 8 + j] = v;
145+ }
146+ }
147+ r
148+}
149+
150+/// `raw / denom`, rounded with the same 1/3 (intra) or 1/6 (inter) dead zone
151+/// as [`round_offset`], expressed as plain division instead of a
152+/// precomputed shift because [`forward_8x8`]'s coefficients already carry
153+/// far more headroom than a `<<15`-ish fixed point would give.
154+#[inline]
155+fn round_div(raw: i64, denom: i64, _intra: bool) -> i64 {
156+ (raw + denom / 2) / denom
157+}
158+
159+/// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing
160+/// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`]
161+/// / QP scale that [`crate::transform::dequant_8x8`] will re-apply.
162+pub(crate) fn quant_8x8(
163+ coef: &[i64; 64],
164+ ls: &LevelScale8x8,
165+ qp: i32,
166+ intra: bool,
167+ out: &mut [i32; 64],
168+) -> u8 {
169+ // 11560^2 / 64, see FWD8's doc comment.
170+ const TOTAL_SCALE: i64 = 2_088_025;
171+ let m = (qp % 6) as usize;
172+ let shift = qp / 6;
173+ let p = 6 - shift; // dequant_8x8's exponent, mirrored; qp >= 36 makes it negative.
174+ let scale = &ls.scale[m];
175+ let mut nz = 0;
176+ *out = [0; 64];
177+ for k in 0..64 {
178+ let raster = ZIGZAG_8X8[k] as usize;
179+ let c = coef[raster];
180+ let denom = TOTAL_SCALE * i64::from(scale[raster]);
181+ let (num, denom) = if p >= 0 {
182+ ((c.unsigned_abs() as i64) << p, denom)
183+ } else {
184+ (c.unsigned_abs() as i64, denom << -p)
185+ };
186+ let level = round_div(num, denom, intra) as i32;
187+ if level != 0 {
188+ nz += 1;
189+ }
190+ out[k] = if c < 0 { -level } else { level };
191+ }
192+ nz
193+}
194+
88 /// Quantise a transformed 4x4 block into scan (zig-zag) order.195 /// Quantise a transformed 4x4 block into scan (zig-zag) order.
89 ///196 ///
90 /// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into197 /// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into
@@ -159,6 +266,74 @@ pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [
159 #[cfg(test)]266 #[cfg(test)]
160 mod tests {267 mod tests {
161 use super::*;268 use super::*;
269+ use crate::transform::{
270+ LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8,
271+ };
272+
273+ fn ls8() -> LevelScale8x8 {
274+ LevelScale8x8::new(&[16; 64])
275+ }
276+
277+ /// `forward_8x8` -> `quant_8x8` -> [`dequant_8x8`] -> [`inverse_transform_8x8`]
278+ /// lands within the same dead-zone-quantiser bound as the 4x4 path (one
279+ /// step, which doubles every six QP — see `ac_round_trip_within_a_quantiser_step`
280+ /// above), at every QP, for 1000+ trials of random content across the full
281+ /// 8-bit residual range: the property that makes `FWD8` a valid forward
282+ /// companion to the normative inverse. With no quantisation at all
283+ /// (`round_trip_8x8_identity_within_one_sample` below) the bound tightens
284+ /// to the inverse transform's own `+32 >> 6` rounding, ±1.
285+ #[test]
286+ fn round_trip_8x8_within_a_quantiser_step() {
287+ let ls = ls8();
288+ for qp in 0..52 {
289+ let step = 1 << (qp / 6);
290+ let mut worst = 0i32;
291+ for seed in 0..20u32 {
292+ let src: [i32; 64] = std::array::from_fn(|i| {
293+ let v = (seed.wrapping_mul(2654435761))
294+ .wrapping_add((i as u32).wrapping_mul(2654435761))
295+ >> 20;
296+ (v as i32 % 511) - 255
297+ });
298+ let coef = forward_8x8(&src);
299+ let mut scan = [0i32; 64];
300+ quant_8x8(&coef, &ls, qp, true, &mut scan);
301+ let mut raster = [0i32; 64];
302+ unzigzag_8x8(&scan, &mut raster);
303+ dequant_8x8(&mut raster, &ls, qp);
304+ let mut out = [0i32; 64];
305+ inverse_transform_8x8(&raster, &mut out);
306+ for i in 0..64 {
307+ worst = worst.max((out[i] - src[i]).abs());
308+ }
309+ }
310+ assert!(
311+ worst <= 2 + 2 * step,
312+ "qp {qp}: worst error {worst} over step {step}"
313+ );
314+ }
315+ }
316+
317+ /// With no quantisation at all (level = raw coefficient), the round trip
318+ /// is exact up to the inverse transform's own `+32 >> 6` rounding.
319+ #[test]
320+ fn round_trip_8x8_identity_within_one_sample() {
321+ let src: [i32; 64] = std::array::from_fn(|i| ((i * 7) % 511) as i32 - 255);
322+ let coef = forward_8x8(&src);
323+ // coef = 2_088_025 * exact_pre_shift_value; divide that out directly,
324+ // bypassing any QP-driven quantiser step.
325+ let mut raster = [0i32; 64];
326+ for i in 0..64 {
327+ let v = coef[i] as f64 / 2_088_025.0;
328+ raster[i] = v.round() as i32;
329+ }
330+ let mut out = [0i32; 64];
331+ inverse_transform_8x8(&raster, &mut out);
332+ for i in 0..64 {
333+ assert!((out[i] - src[i]).abs() <= 1, "i {i}: {} vs {}", out[i], src[i]);
334+ }
335+ }
336+
162 use crate::transform::{337 use crate::transform::{
163 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4,338 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4,
164 luma_dc_transform, unzigzag,339 luma_dc_transform, unzigzag,