forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

scaling.rs481 lines, 19.0 KiBHistoryRawDownload
1//! Scaling lists: `scaling_list_data()` (7.3.4), the default lists of Tables 7-5
2//! and 7-6, and the `ScalingFactor` each transform block is dequantised with (7.4.5).
3//!
4//! A list is stored as the coefficients a bitstream carries, `ScalingList[sizeId]
5//! [matrixId][i]` in up-right diagonal order, plus the DC value of the 16x16 and
6//! 32x32 lists. [`ScalingFactors`] turns those into a raster matrix per block size.
7//!
8//! The 32x32 chroma matrices (matrixId 1, 2, 4, 5) are not coded: they are only
9//! used for 4:4:4, which this family does not decode, so they hold the defaults.
10
11use ec_core::bitio::{BitReader, BitWriter};
12use ec_core::error::{Error, Result};
13
14use crate::ps::{Pps, Sps};
15
16/// Table 7-6, intra 8x8 default, in up-right diagonal scan order (`i` = 0..63).
17const DEFAULT_INTRA_8X8: [u8; 64] = [
18 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20,
19 21, 20, 19, 21, 24, 22, 22, 24, 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31,
20 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115,
21];
22
23/// Table 7-6, inter 8x8 default, in up-right diagonal scan order (`i` = 0..63).
24const DEFAULT_INTER_8X8: [u8; 64] = [
25 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20,
26 20, 20, 20, 20, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28,
27 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91,
28];
29
30/// The default list for `sizeId` (0 = 4x4 .. 3 = 32x32) and `matrixId`, as
31/// Table 7-5 and Table 7-6 give it: flat 16 for 4x4, and for the larger sizes
32/// the intra table for matrixId 0..2 (Y, Cb, Cr) and the inter table for 3..5.
33fn default_coefficients(size_id: usize, matrix_id: usize) -> [u8; 64] {
34 if size_id == 0 {
35 [16; 64]
36 } else if matrix_id < 3 {
37 DEFAULT_INTRA_8X8
38 } else {
39 DEFAULT_INTER_8X8
40 }
41}
42
43/// `matrixId` steps by 3 for 32x32 (only the luma and inter matrices are coded
44/// there), and by 1 otherwise.
45fn matrix_step(size_id: usize) -> usize {
46 if size_id == 3 { 3 } else { 1 }
47}
48
49/// Number of coefficients coded for a list of `sizeId`: 16 for 4x4, else 64.
50fn coded_count(size_id: usize) -> usize {
51 if size_id == 0 { 16 } else { 64 }
52}
53
54/// One set of scaling lists, as a `scaling_list_data()` structure carries them.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct ScalingList {
57 /// `ScalingList[sizeId][matrixId][i]`, in up-right diagonal scan order. For
58 /// sizeId 0 only the first 16 entries are meaningful.
59 pub coefficients: [[[u8; 64]; 6]; 4],
60 /// `scaling_list_dc_coef_minus8 + 8` for sizeId 2 and 3 (the DC of the
61 /// upsampled matrix); 16 for sizeId 0 and 1, where there is none.
62 pub dc: [[u8; 6]; 4],
63}
64
65impl Default for ScalingList {
66 fn default() -> ScalingList {
67 ScalingList::default_lists()
68 }
69}
70
71impl ScalingList {
72 /// The default lists of Tables 7-5 and 7-6, used when
73 /// `scaling_list_enabled_flag` is set and no list data is sent.
74 pub fn default_lists() -> ScalingList {
75 let mut coefficients = [[[16u8; 64]; 6]; 4];
76 for (size_id, sizes) in coefficients.iter_mut().enumerate() {
77 for (matrix_id, matrix) in sizes.iter_mut().enumerate() {
78 *matrix = default_coefficients(size_id, matrix_id);
79 }
80 }
81 ScalingList {
82 coefficients,
83 dc: [[16; 6]; 4],
84 }
85 }
86
87 /// Parse `scaling_list_data()` (7.3.4) into the lists it produces: a matrix
88 /// is either sent explicitly, copied from an earlier one (`pred_matrix_id_delta`),
89 /// or the default when that delta is 0.
90 pub fn parse(r: &mut BitReader) -> Result<ScalingList> {
91 let mut list = ScalingList::default_lists();
92 for size_id in 0..4 {
93 for matrix_id in (0..6).step_by(matrix_step(size_id)) {
94 if r.read_bit()? {
95 // scaling_list_pred_mode_flag = 1: the coefficients are sent.
96 let mut next: i32 = 8;
97 if size_id > 1 {
98 let dc = r.read_se()?.saturating_add(8);
99 if !(1..=255).contains(&dc) {
100 return Err(Error::corrupt(format!(
101 "HEVC scaling list: scaling_list_dc_coef_minus8 = {}",
102 dc - 8
103 )));
104 }
105 list.dc[size_id][matrix_id] = dc as u8;
106 next = dc;
107 }
108 for coef in list.coefficients[size_id][matrix_id]
109 .iter_mut()
110 .take(coded_count(size_id))
111 {
112 let delta = r.read_se()?;
113 if !(-128..=127).contains(&delta) {
114 return Err(Error::corrupt(format!(
115 "HEVC scaling list: scaling_list_delta_coef = {delta}"
116 )));
117 }
118 next = (next + delta + 256) % 256;
119 *coef = next as u8;
120 }
121 } else {
122 // scaling_list_pred_mode_flag = 0: copy from refMatrixId, or
123 // keep the default already in place when the delta is 0.
124 let delta = r.read_ue()? as usize;
125 let step = matrix_step(size_id);
126 if delta > matrix_id / step {
127 return Err(Error::corrupt(format!(
128 "HEVC scaling list: scaling_list_pred_matrix_id_delta = {delta} \
129 at sizeId {size_id}, matrixId {matrix_id}"
130 )));
131 }
132 if delta != 0 {
133 let ref_id = matrix_id - delta * step;
134 list.coefficients[size_id][matrix_id] = list.coefficients[size_id][ref_id];
135 list.dc[size_id][matrix_id] = list.dc[size_id][ref_id];
136 }
137 }
138 }
139 }
140 Ok(list)
141 }
142
143 /// Write `scaling_list_data()` with every coded matrix sent explicitly
144 /// (`scaling_list_pred_mode_flag` = 1). Parsing the result gives back `self`
145 /// (for the coded matrices; see the module note on 32x32 chroma).
146 pub fn write(&self, w: &mut BitWriter) {
147 for size_id in 0..4 {
148 for matrix_id in (0..6).step_by(matrix_step(size_id)) {
149 w.write_bit(true);
150 let mut next: i32 = 8;
151 if size_id > 1 {
152 let dc = i32::from(self.dc[size_id][matrix_id]);
153 w.write_se(dc - 8);
154 next = dc;
155 }
156 for &coef in self.coefficients[size_id][matrix_id]
157 .iter()
158 .take(coded_count(size_id))
159 {
160 let coef = i32::from(coef);
161 // The delta wraps modulo 256 into -128..=127, which the parser undoes.
162 let mut delta = (coef - next).rem_euclid(256);
163 if delta > 127 {
164 delta -= 256;
165 }
166 w.write_se(delta);
167 next = coef;
168 }
169 }
170 }
171 }
172}
173
174/// The up-right diagonal scan of a `blk` x `blk` block (6.5.3), as `(x, y)` pairs.
175fn diag_scan(blk: usize) -> Vec<(usize, usize)> {
176 let mut out = Vec::with_capacity(blk * blk);
177 let (mut x, mut y) = (0isize, 0isize);
178 while out.len() < blk * blk {
179 while y >= 0 {
180 if (x as usize) < blk && (y as usize) < blk {
181 out.push((x as usize, y as usize));
182 }
183 y -= 1;
184 x += 1;
185 }
186 y = x;
187 x = 0;
188 }
189 out
190}
191
192/// `ScalingFactor` for every block size and matrixId (7.4.5), each as a raster
193/// matrix: entry `y * size + x` is `m[x][y]`.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct ScalingFactors {
196 factors: [[Vec<u8>; 6]; 4],
197}
198
199impl ScalingFactors {
200 /// Expand a list set into the factor matrices.
201 pub fn new(list: &ScalingList) -> ScalingFactors {
202 ScalingFactors {
203 factors: std::array::from_fn(|size_id| {
204 std::array::from_fn(|matrix_id| derive(list, size_id, matrix_id))
205 }),
206 }
207 }
208
209 /// The factors a picture is dequantised with (7.4.2.2, 7.4.3.3): `None` when
210 /// `scaling_list_enabled_flag` is 0 (flat 16). Otherwise the PPS list when the
211 /// PPS sends one, else the SPS list, else the defaults.
212 pub fn for_picture(sps: &Sps, pps: &Pps) -> Option<ScalingFactors> {
213 ScalingFactors::for_lists(
214 sps.scaling_list_enabled,
215 sps.scaling_list.as_ref(),
216 pps.scaling_list.as_ref(),
217 )
218 }
219
220 /// [`ScalingFactors::for_picture`] over the bare fields: `enabled` is
221 /// `scaling_list_enabled_flag`, and the two lists are the explicit data of the
222 /// SPS and the PPS when each sends one.
223 pub fn for_lists(
224 enabled: bool,
225 sps_list: Option<&ScalingList>,
226 pps_list: Option<&ScalingList>,
227 ) -> Option<ScalingFactors> {
228 if !enabled {
229 return None;
230 }
231 Some(match pps_list.or(sps_list) {
232 Some(list) => ScalingFactors::new(list),
233 None => ScalingFactors::new(&ScalingList::default_lists()),
234 })
235 }
236
237 /// The raster factor matrix for a transform block of side `1 << log2_size`
238 /// (2..=5) and `matrix_id` (0..=2 intra, 3..=5 inter).
239 pub fn for_block(&self, log2_size: u32, matrix_id: usize) -> &[u8] {
240 let size_id = (log2_size as usize).saturating_sub(2).min(3);
241 &self.factors[size_id][matrix_id.min(5)]
242 }
243}
244
245/// Derive the raster `ScalingFactor` for one sizeId and matrixId (7.4.5).
246fn derive(list: &ScalingList, size_id: usize, matrix_id: usize) -> Vec<u8> {
247 let size = 4usize << size_id;
248 let mut m = vec![16u8; size * size];
249 // The coded block is 4x4 for sizeId 0 and 8x8 otherwise; for 16x16 and 32x32
250 // each coded entry covers a 2x2 or 4x4 run of the matrix.
251 let (blk, rep) = match size_id {
252 0 => (4, 1),
253 1 => (8, 1),
254 2 => (8, 2),
255 _ => (8, 4),
256 };
257 // 7-xx: with ChromaArrayType 3 the 32x32 chroma matrices (1, 2, 4, 5) are the 16x16 lists
258 // of those matrices, expanded by four, with the 16x16 DC.
259 let (src_size, coefs_id) = if size_id == 3 && !matrix_id.is_multiple_of(3) {
260 (2, matrix_id)
261 } else {
262 (size_id, matrix_id)
263 };
264 let coefs = &list.coefficients[src_size][coefs_id];
265 for (i, (sx, sy)) in diag_scan(blk).into_iter().enumerate() {
266 let value = coefs[i];
267 for j in 0..rep {
268 for k in 0..rep {
269 m[(sy * rep + j) * size + sx * rep + k] = value;
270 }
271 }
272 }
273 if size_id >= 2 {
274 m[0] = list.dc[src_size][coefs_id];
275 }
276 m
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 /// Table 7-6 as HM writes it: the same defaults in raster order (row = y).
284 const HM_INTRA_8X8: [u8; 64] = [
285 16, 16, 16, 16, 17, 18, 21, 24, 16, 16, 16, 16, 17, 19, 22, 25, 16, 16, 17, 18, 20, 22, 25,
286 29, 16, 16, 18, 21, 24, 27, 31, 36, 17, 17, 20, 24, 30, 35, 41, 47, 18, 19, 22, 27, 35, 44,
287 54, 65, 21, 22, 25, 31, 41, 54, 70, 88, 24, 25, 29, 36, 47, 65, 88, 115,
288 ];
289 const HM_INTER_8X8: [u8; 64] = [
290 16, 16, 16, 16, 17, 18, 20, 24, 16, 16, 16, 17, 18, 20, 24, 25, 16, 16, 17, 18, 20, 24, 25,
291 28, 16, 17, 18, 20, 24, 25, 28, 33, 17, 18, 20, 24, 25, 28, 33, 41, 18, 20, 24, 25, 28, 33,
292 41, 54, 20, 24, 25, 28, 33, 41, 54, 71, 24, 25, 28, 33, 41, 54, 71, 91,
293 ];
294
295 /// Write `scaling_list_data()` where each matrix is described by `entry`:
296 /// `Some((dc, coefs))` is sent explicitly, `None` is predicted with delta 0.
297 /// `Err(delta)` is a prediction from a reference matrix `delta` steps back.
298 enum Entry {
299 Explicit(Option<i32>, Vec<i32>),
300 Pred(usize),
301 }
302
303 fn write_data(w: &mut BitWriter, entry: impl Fn(usize, usize) -> Entry) {
304 for size_id in 0..4 {
305 for matrix_id in (0..6).step_by(matrix_step(size_id)) {
306 match entry(size_id, matrix_id) {
307 Entry::Explicit(dc, coefs) => {
308 w.write_bit(true);
309 let mut next = 8;
310 if size_id > 1 {
311 let dc = dc.expect("explicit 16x16/32x32 lists carry a DC");
312 w.write_se(dc - 8);
313 next = dc;
314 }
315 for coef in coefs {
316 w.write_se((coef - next + 128).rem_euclid(256) - 128);
317 next = coef;
318 }
319 }
320 Entry::Pred(delta) => {
321 w.write_bit(false);
322 w.write_ue(delta as u32);
323 }
324 }
325 }
326 }
327 }
328
329 fn parse_bits(w: BitWriter) -> Result<ScalingList> {
330 let bytes = w.into_bytes();
331 ScalingList::parse(&mut BitReader::new(&bytes))
332 }
333
334 #[test]
335 fn default_tables_are_table_7_6_in_diagonal_order() {
336 // The HM raster tables, read back along the diagonal scan, must give the
337 // spec's diagonal-order tables: that cross-checks both against each other.
338 for (raster, spec) in [
339 (HM_INTRA_8X8, DEFAULT_INTRA_8X8),
340 (HM_INTER_8X8, DEFAULT_INTER_8X8),
341 ] {
342 let scanned: Vec<u8> = diag_scan(8)
343 .into_iter()
344 .map(|(x, y)| raster[y * 8 + x])
345 .collect();
346 assert_eq!(scanned, spec.to_vec());
347 }
348 }
349
350 #[test]
351 fn default_lists_are_flat_at_4x4_and_table_7_6_above() {
352 let list = ScalingList::default_lists();
353 assert!(list.coefficients[0].iter().all(|m| m[..16] == [16; 16]));
354 assert_eq!(list.coefficients[1][0], DEFAULT_INTRA_8X8);
355 assert_eq!(list.coefficients[2][5], DEFAULT_INTER_8X8);
356 assert_eq!(list.coefficients[3][3], DEFAULT_INTER_8X8);
357 assert_eq!(list.dc, [[16; 6]; 4]);
358 }
359
360 #[test]
361 fn default_factors_match_the_hm_raster_matrices() {
362 let factors = ScalingFactors::new(&ScalingList::default_lists());
363 assert_eq!(factors.for_block(3, 0), &HM_INTRA_8X8[..]);
364 assert_eq!(factors.for_block(3, 4), &HM_INTER_8X8[..]);
365 assert!(factors.for_block(2, 1).iter().all(|&m| m == 16));
366 }
367
368 #[test]
369 fn default_list_round_trips_through_write_and_parse() {
370 let list = ScalingList::default_lists();
371 let mut w = BitWriter::with_capacity(64);
372 list.write(&mut w);
373 assert_eq!(parse_bits(w).unwrap(), list);
374 }
375
376 #[test]
377 fn custom_list_round_trips_through_write_and_parse() {
378 let mut list = ScalingList::default_lists();
379 for size_id in 0..4 {
380 for matrix_id in (0..6).step_by(matrix_step(size_id)) {
381 for (i, coef) in list.coefficients[size_id][matrix_id]
382 .iter_mut()
383 .take(coded_count(size_id))
384 .enumerate()
385 {
386 // Spread the values over the whole 1..=255 range, with wraps.
387 *coef = (1 + (i * 37 + size_id * 11 + matrix_id * 5) % 255) as u8;
388 }
389 if size_id > 1 {
390 list.dc[size_id][matrix_id] = (1 + (size_id * 50 + matrix_id) % 255) as u8;
391 }
392 }
393 }
394 let mut w = BitWriter::with_capacity(64);
395 list.write(&mut w);
396 assert_eq!(parse_bits(w).unwrap(), list);
397 }
398
399 #[test]
400 fn prediction_copies_the_named_reference_matrix() {
401 // sizeId 0: matrix 0 explicit (coefficient i = 10 + i), matrix 1 copies it
402 // (delta 1), matrix 2 takes the default (delta 0). Everything else defaults.
403 let explicit: Vec<i32> = (0..16).map(|i| 10 + i).collect();
404 let explicit_u8: Vec<u8> = explicit.iter().map(|&c| c as u8).collect();
405 let mut w = BitWriter::with_capacity(64);
406 write_data(&mut w, |size_id, matrix_id| match (size_id, matrix_id) {
407 (0, 0) => Entry::Explicit(None, explicit.clone()),
408 (0, 1) => Entry::Pred(1),
409 (0, 2) => Entry::Pred(0),
410 _ => Entry::Pred(0),
411 });
412 let list = parse_bits(w).unwrap();
413 assert_eq!(&list.coefficients[0][0][..16], &explicit_u8[..]);
414 assert_eq!(list.coefficients[0][1], list.coefficients[0][0]);
415 assert_eq!(&list.coefficients[0][2][..16], &[16u8; 16][..]);
416 }
417
418 #[test]
419 fn prediction_copies_the_dc_too_and_the_32x32_step_is_three() {
420 // sizeId 2 matrix 0 has DC 40; matrix 1 predicts from it and inherits the DC.
421 // sizeId 3 matrix 3 predicts from matrix 0 (delta 1 at step 3), so it inherits
422 // matrix 0's explicit list and DC.
423 let coefs: Vec<i32> = (0..64).map(|i| 20 + (i % 30)).collect();
424 let mut w = BitWriter::with_capacity(64);
425 write_data(&mut w, |size_id, matrix_id| match (size_id, matrix_id) {
426 (2, 0) => Entry::Explicit(Some(40), coefs.clone()),
427 (2, 1) => Entry::Pred(1),
428 (3, 0) => Entry::Explicit(Some(60), coefs.clone()),
429 (3, 3) => Entry::Pred(1),
430 _ => Entry::Pred(0),
431 });
432 let list = parse_bits(w).unwrap();
433 assert_eq!(list.dc[2][0], 40);
434 assert_eq!(list.dc[2][1], 40);
435 assert_eq!(list.coefficients[2][1], list.coefficients[2][0]);
436 assert_eq!(list.dc[3][0], 60);
437 assert_eq!(list.dc[3][3], 60);
438 assert_eq!(list.coefficients[3][3], list.coefficients[3][0]);
439 }
440
441 #[test]
442 fn a_prediction_reaching_before_matrix_zero_is_refused() {
443 // sizeId 0, matrixId 0 with delta 1: there is no matrix 0 - 1.
444 let mut w = BitWriter::with_capacity(16);
445 w.write_bit(false);
446 w.write_ue(1);
447 assert!(parse_bits(w).is_err());
448 }
449
450 #[test]
451 fn dc_upsamples_the_16x16_factor_at_the_origin_only() {
452 let mut list = ScalingList::default_lists();
453 list.coefficients[2][0][0] = 30;
454 list.dc[2][0] = 99;
455 let factors = ScalingFactors::new(&list);
456 let m = factors.for_block(4, 0);
457 assert_eq!(m[0], 99);
458 assert_eq!(m[1], 30);
459 assert_eq!(m[16], 30);
460 assert_eq!(m[17], 30);
461 }
462
463 #[test]
464 fn pps_list_overrides_sps_list_and_flat_when_disabled() {
465 assert!(ScalingFactors::for_lists(false, None, None).is_none());
466 let defaults = ScalingFactors::new(&ScalingList::default_lists());
467 assert_eq!(ScalingFactors::for_lists(true, None, None), Some(defaults));
468 let mut sps_list = ScalingList::default_lists();
469 sps_list.coefficients[1][0][0] = 50;
470 assert_eq!(
471 ScalingFactors::for_lists(true, Some(&sps_list), None),
472 Some(ScalingFactors::new(&sps_list))
473 );
474 let mut pps_list = ScalingList::default_lists();
475 pps_list.coefficients[1][0][0] = 70;
476 assert_eq!(
477 ScalingFactors::for_lists(true, Some(&sps_list), Some(&pps_list)),
478 Some(ScalingFactors::new(&pps_list))
479 );
480 }
481}