forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

idct.rs456 lines, 17.7 KiBHistoryRawDownload
1//! ffmpeg's `ff_prores_idct_10` / `ff_prores_idct_12` (libavcodec/simple_idct.c, the
2//! `simple_idct_template.c` integer IDCT), reproduced with its 16-bit intermediates.
3//! `W4`-based rounding, the DC-only row shortcut and the `+8192` column bias all matter
4//! for byte-exactness.
5//!
6//! Blocks arrive dequantised and *transposed* (`block[col * 8 + row]`): the entropy decoder
7//! scatters coefficients straight into that layout, so the first (row) pass runs with one
8//! 8-lane vector per frequency column. [`idct_put`] is the 10-bit SIMD path built on
9//! `wide`'s `pmaddwd` (`i16x8::dot`); 12-bit data (4444) goes through the scalar
10//! [`reference`] code, which the unit tests also use to check the SIMD path.
11
12use wide::{i16x8, i32x4, i32x8};
13
14/// Scalar implementation in raster layout, a line-for-line port of ffmpeg's.
15pub mod reference {
16 #![allow(dead_code)]
17
18 pub struct K {
19 /// `a` (even part) coefficient rows for r2, r4, r6.
20 pub a2: [i32; 4],
21 pub a4: [i32; 4],
22 pub a6: [i32; 4],
23 /// `b` (odd part) coefficient rows for r1, r3, r5, r7.
24 pub b1: [i32; 4],
25 pub b3: [i32; 4],
26 pub b5: [i32; 4],
27 pub b7: [i32; 4],
28 pub w4: i32,
29 pub row_shift: u32,
30 pub col_shift: u32,
31 }
32
33 const fn k(w1: i32, w2: i32, w3: i32, w4: i32, w5: i32, w6: i32, w7: i32, row_shift: u32, col_shift: u32) -> K {
34 K {
35 a2: [w2, w6, -w6, -w2],
36 a4: [w4, -w4, -w4, w4],
37 a6: [w6, -w2, w2, -w6],
38 b1: [w1, w3, w5, w7],
39 b3: [w3, -w7, -w1, -w5],
40 b5: [w5, -w1, w7, w3],
41 b7: [w7, -w5, w3, -w1],
42 w4,
43 row_shift,
44 col_shift,
45 }
46 }
47
48 pub static K10: K = k(22725, 21407, 19265, 16384, 12873, 8867, 4520, 13 + 2, 18);
49 pub static K12: K = k(45451, 42813, 38531, 32767, 25746, 17734, 9041, 16, 17);
50
51 #[inline(always)]
52 fn row_pass(k: &K, row: &mut [i16; 8]) {
53 let r: [i32; 8] = [
54 row[0] as i32, row[1] as i32, row[2] as i32, row[3] as i32,
55 row[4] as i32, row[5] as i32, row[6] as i32, row[7] as i32,
56 ];
57 if (r[1] | r[2] | r[3] | r[4] | r[5] | r[6] | r[7]) == 0 {
58 // DC only: (dc + 1) >> 1 in both bit depths.
59 *row = [(r[0].wrapping_add(1) >> 1) as i16; 8];
60 return;
61 }
62 let base = k.w4.wrapping_mul(r[0]).wrapping_add(1 << (k.row_shift - 1));
63 let mut a = [base; 4];
64 let mut b = [0i32; 4];
65 for j in 0..4 {
66 a[j] = a[j]
67 .wrapping_add(k.a2[j].wrapping_mul(r[2]))
68 .wrapping_add(k.a4[j].wrapping_mul(r[4]))
69 .wrapping_add(k.a6[j].wrapping_mul(r[6]));
70 b[j] = k.b1[j]
71 .wrapping_mul(r[1])
72 .wrapping_add(k.b3[j].wrapping_mul(r[3]))
73 .wrapping_add(k.b5[j].wrapping_mul(r[5]))
74 .wrapping_add(k.b7[j].wrapping_mul(r[7]));
75 }
76 let s = k.row_shift;
77 for j in 0..4 {
78 row[j] = (a[j].wrapping_add(b[j]) >> s) as i16;
79 row[7 - j] = (a[j].wrapping_sub(b[j]) >> s) as i16;
80 }
81 }
82
83 /// Column pass over all eight columns; returns the eight output rows (pre-clip).
84 #[inline(always)]
85 fn col_pass(k: &K, blk: &[i16; 64]) -> [[i16; 8]; 8] {
86 let bias = (1i32 << (k.col_shift - 1)) / k.w4;
87 let mut c = [[0i32; 8]; 8];
88 for r in 0..8 {
89 for j in 0..8 {
90 c[r][j] = blk[r * 8 + j] as i32;
91 }
92 }
93 let mut a = [[0i32; 8]; 4];
94 let mut b = [[0i32; 8]; 4];
95 for j in 0..8 {
96 // The +8192 lands in the 16-bit first row before the multiply.
97 let c0 = (blk[j].wrapping_add(8192)) as i32;
98 let base = k.w4.wrapping_mul(c0.wrapping_add(bias));
99 for i in 0..4 {
100 a[i][j] = base
101 .wrapping_add(k.a2[i].wrapping_mul(c[2][j]))
102 .wrapping_add(k.a4[i].wrapping_mul(c[4][j]))
103 .wrapping_add(k.a6[i].wrapping_mul(c[6][j]));
104 b[i][j] = k.b1[i]
105 .wrapping_mul(c[1][j])
106 .wrapping_add(k.b3[i].wrapping_mul(c[3][j]))
107 .wrapping_add(k.b5[i].wrapping_mul(c[5][j]))
108 .wrapping_add(k.b7[i].wrapping_mul(c[7][j]));
109 }
110 }
111 let s = k.col_shift;
112 let mut out = [[0i16; 8]; 8];
113 for i in 0..4 {
114 for j in 0..8 {
115 out[i][j] = (a[i][j].wrapping_add(b[i][j]) >> s) as i16;
116 out[7 - i][j] = (a[i][j].wrapping_sub(b[i][j]) >> s) as i16;
117 }
118 }
119 out
120 }
121
122 /// Run the IDCT on an already dequantised `block` and store the clipped 8x8 result at
123 /// `dst[0]`, row pitch `stride`. With `dc_only` only `block[0]` is read (the block's other
124 /// coefficients are zero), which is exact: the shortcut rows and columns of the full
125 /// computation collapse to one value.
126 #[inline(always)]
127 pub fn idct_put_ref<const B12: bool>(dst: &mut [u8], stride: usize, block: &mut [i16; 64], dc_only: bool) {
128 let k = if B12 { &K12 } else { &K10 };
129 let (lo, hi): (i16, i16) = if B12 { (4, 4091) } else { (4, 1019) };
130 if dc_only {
131 let t = (i32::from(block[0]).wrapping_add(1) >> 1) as i16;
132 let c0 = t.wrapping_add(8192) as i32;
133 let bias = (1i32 << (k.col_shift - 1)) / k.w4;
134 let v = ((k.w4.wrapping_mul(c0.wrapping_add(bias)) >> k.col_shift) as i16).clamp(lo, hi) as u16;
135 for r in 0..8 {
136 for c in dst[r * stride * 2..r * stride * 2 + 16].as_chunks_mut::<2>().0.iter_mut() {
137 *c = v.to_le_bytes();
138 }
139 }
140 return;
141 }
142 for r in 0..8 {
143 let row: &mut [i16; 8] = (&mut block[r * 8..r * 8 + 8]).try_into().unwrap();
144 row_pass(k, row);
145 }
146 let out = col_pass(k, block);
147 for r in 0..8 {
148 let d = &mut dst[r * stride * 2..r * stride * 2 + 16];
149 for j in 0..8 {
150 d[2 * j..2 * j + 2].copy_from_slice(&(out[r][j].clamp(lo, hi) as u16).to_le_bytes());
151 }
152 }
153 }
154}
155
156use reference::{K10, K12};
157use archmage::{SimdToken, X64V1Token};
158use reference::K;
159
160#[inline(always)]
161fn pairs(a: i16x8, b: i16x8) -> (i16x8, i16x8) {
162 let (a, b) = (a.to_array(), b.to_array());
163 (
164 i16x8::new([a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3]]),
165 i16x8::new([a[4], b[4], a[5], b[5], a[6], b[6], a[7], b[7]]),
166 )
167}
168
169#[inline(always)]
170fn cpair(x: i32, y: i32) -> i16x8 {
171 let (x, y) = (x as i16, y as i16);
172 i16x8::new([x, y, x, y, x, y, x, y])
173}
174
175/// One 1-D butterfly across eight lanes. `v[k]` is input coefficient `k` for every lane; `base`
176/// is the pass constant added to the `W4*v0` term. Returns, per output position, the
177/// `(a + b, a - b)` sums in lane halves: `out[i]` = (a_i + b_i) and `out[7 - i]` = (a_i - b_i).
178#[inline(always)]
179fn butterfly(k: &K, v: [i16x8; 8], base: i32) -> [[i32x4; 2]; 8] {
180 let (p04l, p04h) = pairs(v[0], v[4]);
181 let (p26l, p26h) = pairs(v[2], v[6]);
182 let (p13l, p13h) = pairs(v[1], v[3]);
183 let (p57l, p57h) = pairs(v[5], v[7]);
184 let base = i32x4::splat(base);
185 let mut out = [[i32x4::splat(0); 2]; 8];
186 for i in 0..4 {
187 let c04 = cpair(k.w4, k.a4[i]);
188 let c26 = cpair(k.a2[i], k.a6[i]);
189 let c13 = cpair(k.b1[i], k.b3[i]);
190 let c57 = cpair(k.b5[i], k.b7[i]);
191 let al = p04l.dot(c04) + p26l.dot(c26) + base;
192 let ah = p04h.dot(c04) + p26h.dot(c26) + base;
193 let bl = p13l.dot(c13) + p57l.dot(c57);
194 let bh = p13h.dot(c13) + p57h.dot(c57);
195 out[i] = [al + bl, ah + bh];
196 out[7 - i] = [al - bl, ah - bh];
197 }
198 out
199}
200
201#[inline(always)]
202fn narrow(lo: i32x4, hi: i32x4, shift: u32) -> i16x8 {
203 let (l, h) = ((lo >> shift).to_array(), (hi >> shift).to_array());
204 i16x8::from_i32x8_truncate(i32x8::new([l[0], l[1], l[2], l[3], h[0], h[1], h[2], h[3]]))
205}
206
207#[inline(always)]
208fn transpose(m: [i16x8; 8]) -> [i16x8; 8] {
209 let a = m.map(|v| v.to_array());
210 let mut t = [[0i16; 8]; 8];
211 for r in 0..8 {
212 for c in 0..8 {
213 t[c][r] = a[r][c];
214 }
215 }
216 t.map(i16x8::new)
217}
218
219
220#[cfg(target_arch = "x86_64")]
221mod sse {
222 use super::reference::{K, K10};
223 use archmage::{X64V1Token, arcane};
224 use std::arch::x86_64::*;
225
226 #[target_feature(enable = "sse2")]
227 fn cpair(x: i32, y: i32) -> __m128i {
228 _mm_set1_epi32(((y as i16 as u16 as u32) << 16 | (x as i16 as u16 as u32)) as i32)
229 }
230
231 /// See `butterfly` in the portable path: `out[i]` = a_i + b_i, `out[7 - i]` = a_i - b_i,
232 /// each as (low, high) halves of the eight lanes.
233 #[target_feature(enable = "sse2")]
234 #[inline]
235 fn butterfly(k: &K, v: [__m128i; 8], base: i32) -> [[__m128i; 2]; 8] {
236 let p04l = _mm_unpacklo_epi16(v[0], v[4]);
237 let p04h = _mm_unpackhi_epi16(v[0], v[4]);
238 let p26l = _mm_unpacklo_epi16(v[2], v[6]);
239 let p26h = _mm_unpackhi_epi16(v[2], v[6]);
240 let p13l = _mm_unpacklo_epi16(v[1], v[3]);
241 let p13h = _mm_unpackhi_epi16(v[1], v[3]);
242 let p57l = _mm_unpacklo_epi16(v[5], v[7]);
243 let p57h = _mm_unpackhi_epi16(v[5], v[7]);
244 let base = _mm_set1_epi32(base);
245 let mut out = [[_mm_setzero_si128(); 2]; 8];
246 for i in 0..4 {
247 let c04 = cpair(k.w4, k.a4[i]);
248 let c26 = cpair(k.a2[i], k.a6[i]);
249 let c13 = cpair(k.b1[i], k.b3[i]);
250 let c57 = cpair(k.b5[i], k.b7[i]);
251 let al = _mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(p04l, c04), _mm_madd_epi16(p26l, c26)), base);
252 let ah = _mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(p04h, c04), _mm_madd_epi16(p26h, c26)), base);
253 let bl = _mm_add_epi32(_mm_madd_epi16(p13l, c13), _mm_madd_epi16(p57l, c57));
254 let bh = _mm_add_epi32(_mm_madd_epi16(p13h, c13), _mm_madd_epi16(p57h, c57));
255 out[i] = [_mm_add_epi32(al, bl), _mm_add_epi32(ah, bh)];
256 out[7 - i] = [_mm_sub_epi32(al, bl), _mm_sub_epi32(ah, bh)];
257 }
258 out
259 }
260
261 /// Arithmetic shift of both halves, truncated to 16 bits (matches `as i16`).
262 #[target_feature(enable = "sse2")]
263 #[inline]
264 fn narrow(lo: __m128i, hi: __m128i, shift: i32) -> __m128i {
265 let l = _mm_srai_epi32::<16>(_mm_slli_epi32::<16>(_mm_sra_epi32(lo, _mm_cvtsi32_si128(shift))));
266 let h = _mm_srai_epi32::<16>(_mm_slli_epi32::<16>(_mm_sra_epi32(hi, _mm_cvtsi32_si128(shift))));
267 _mm_packs_epi32(l, h)
268 }
269
270 #[target_feature(enable = "sse2")]
271 #[inline]
272 fn transpose(m: [__m128i; 8]) -> [__m128i; 8] {
273 let a0 = _mm_unpacklo_epi16(m[0], m[1]);
274 let a1 = _mm_unpackhi_epi16(m[0], m[1]);
275 let a2 = _mm_unpacklo_epi16(m[2], m[3]);
276 let a3 = _mm_unpackhi_epi16(m[2], m[3]);
277 let a4 = _mm_unpacklo_epi16(m[4], m[5]);
278 let a5 = _mm_unpackhi_epi16(m[4], m[5]);
279 let a6 = _mm_unpacklo_epi16(m[6], m[7]);
280 let a7 = _mm_unpackhi_epi16(m[6], m[7]);
281 let b0 = _mm_unpacklo_epi32(a0, a2);
282 let b1 = _mm_unpackhi_epi32(a0, a2);
283 let b2 = _mm_unpacklo_epi32(a1, a3);
284 let b3 = _mm_unpackhi_epi32(a1, a3);
285 let b4 = _mm_unpacklo_epi32(a4, a6);
286 let b5 = _mm_unpackhi_epi32(a4, a6);
287 let b6 = _mm_unpacklo_epi32(a5, a7);
288 let b7 = _mm_unpackhi_epi32(a5, a7);
289 [
290 _mm_unpacklo_epi64(b0, b4),
291 _mm_unpackhi_epi64(b0, b4),
292 _mm_unpacklo_epi64(b1, b5),
293 _mm_unpackhi_epi64(b1, b5),
294 _mm_unpacklo_epi64(b2, b6),
295 _mm_unpackhi_epi64(b2, b6),
296 _mm_unpacklo_epi64(b3, b7),
297 _mm_unpackhi_epi64(b3, b7),
298 ]
299 }
300
301 /// Safe entry: the `X64V1Token` (SSE2, the x86_64 baseline) is what makes the SSE2 body callable.
302 #[arcane]
303 pub fn idct_put_10(_t: X64V1Token, dst: &mut [u8], stride: usize, block: &[i16; 64]) {
304 assert!(dst.len() >= (7 * stride + 8) * 2);
305 {
306 let k = &K10;
307 let v: [__m128i; 8] = bytemuck::cast(*block);
308 let o = butterfly(k, v, 1 << (k.row_shift - 1));
309 let ac = _mm_or_si128(
310 _mm_or_si128(_mm_or_si128(v[1], v[2]), _mm_or_si128(v[3], v[4])),
311 _mm_or_si128(_mm_or_si128(v[5], v[6]), v[7]),
312 );
313 let dc_only = _mm_cmpeq_epi16(ac, _mm_setzero_si128());
314 let dc = _mm_add_epi16(_mm_srai_epi16::<1>(v[0]), _mm_and_si128(v[0], _mm_set1_epi16(1)));
315 let mut rows = [_mm_setzero_si128(); 8];
316 for q in 0..8 {
317 let full = narrow(o[q][0], o[q][1], k.row_shift as i32);
318 rows[q] = _mm_or_si128(_mm_and_si128(dc_only, dc), _mm_andnot_si128(dc_only, full));
319 }
320 let mut w = transpose(rows);
321 w[0] = _mm_add_epi16(w[0], _mm_set1_epi16(8192));
322 let bias = (1i32 << (k.col_shift - 1)) / k.w4;
323 let o = butterfly(k, w, k.w4.wrapping_mul(bias));
324 let (lo, hi) = (_mm_set1_epi16(4), _mm_set1_epi16(1019));
325 for r in 0..8 {
326 let px = _mm_min_epi16(_mm_max_epi16(narrow(o[r][0], o[r][1], k.col_shift as i32), lo), hi);
327 dst[r * stride * 2..r * stride * 2 + 16].copy_from_slice(&bytemuck::cast::<__m128i, [u8; 16]>(px));
328 }
329 }
330 }
331}
332
333/// 10-bit SIMD IDCT of a transposed, dequantised block, stored clipped at `dst`.
334#[inline(always)]
335fn idct_put_10(dst: &mut [u8], stride: usize, block: &[i16; 64]) {
336 let k = &K10;
337 let v: [i16x8; 8] = std::array::from_fn(|c| i16x8::new(block[c * 8..c * 8 + 8].try_into().unwrap()));
338 // Row pass: lanes are block rows.
339 let o = butterfly(k, v, 1 << (k.row_shift - 1));
340 let ac = v[1] | v[2] | v[3] | v[4] | v[5] | v[6] | v[7];
341 let dc_only = ac.simd_eq(i16x8::splat(0));
342 let dc = (v[0] >> 1) + (v[0] & i16x8::splat(1));
343 let mut rows = [i16x8::splat(0); 8];
344 for p in 0..8 {
345 let full = narrow(o[p][0], o[p][1], k.row_shift);
346 rows[p] = dc_only.select(dc, full);
347 }
348 // rows[p] lane i = block'[i][p]; the column pass wants one vector per image row.
349 let w = transpose(rows);
350 // Column pass: lanes are columns. The +8192 wraps in 16 bits before the multiply.
351 let mut w = w;
352 w[0] += i16x8::splat(8192);
353 let bias = (1i32 << (k.col_shift - 1)) / k.w4;
354 let o = butterfly(k, w, k.w4.wrapping_mul(bias));
355 let (lo, hi) = (i16x8::splat(4), i16x8::splat(1019));
356 for r in 0..8 {
357 let px = narrow(o[r][0], o[r][1], k.col_shift).max(lo).min(hi);
358 let a = px.to_array();
359 let d = &mut dst[r * stride * 2..r * stride * 2 + 16];
360 for j in 0..8 {
361 d[2 * j..2 * j + 2].copy_from_slice(&(a[j] as u16).to_le_bytes());
362 }
363 }
364}
365
366/// Run the IDCT on a dequantised `block` in transposed layout and store the clipped 8x8 result
367/// at `dst[0]`, row pitch `stride`. A block whose AC coefficients are all zero takes a shortcut that reads only `block[0]`, which is exact: the shortcut rows and columns of the full
368/// computation collapse to one value.
369#[inline(always)]
370pub fn idct_put<const B12: bool>(dst: &mut [u8], stride: usize, block: &mut [i16; 64]) {
371 let dc_only = block[1..].iter().fold(0, |a, &x| a | x) == 0;
372 let k = if B12 { &K12 } else { &K10 };
373 let (lo, hi): (i16, i16) = if B12 { (4, 4091) } else { (4, 1019) };
374 if dc_only {
375 let t = (i32::from(block[0]).wrapping_add(1) >> 1) as i16;
376 let c0 = t.wrapping_add(8192) as i32;
377 let bias = (1i32 << (k.col_shift - 1)) / k.w4;
378 let v = ((k.w4.wrapping_mul(c0.wrapping_add(bias)) >> k.col_shift) as i16).clamp(lo, hi) as u16;
379 for r in 0..8 {
380 for c in dst[r * stride * 2..r * stride * 2 + 16].as_chunks_mut::<2>().0.iter_mut() {
381 *c = v.to_le_bytes();
382 }
383 }
384 return;
385 }
386 if B12 {
387 let mut raster = [0i16; 64];
388 for c in 0..8 {
389 for r in 0..8 {
390 raster[r * 8 + c] = block[c * 8 + r];
391 }
392 }
393 reference::idct_put_ref::<true>(dst, stride, &mut raster, false);
394 } else {
395 match X64V1Token::summon() {
396 Some(t) => sse::idct_put_10(t, dst, stride, block),
397 None => idct_put_10(dst, stride, block),
398 }
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 fn rng(s: &mut u64) -> u64 {
407 *s ^= *s << 13;
408 *s ^= *s >> 7;
409 *s ^= *s << 17;
410 *s
411 }
412
413 fn check<const B12: bool>() {
414 let mut s = 0x1234_5678_9abc_def1u64;
415 for case in 0..200_000 {
416 // Mixed sparsity and amplitude, including values that overflow 16-bit intermediates.
417 let mut raster = [0i16; 64];
418 let n = (rng(&mut s) % 65) as usize;
419 let amp = match case % 4 {
420 0 => 40,
421 1 => 600,
422 2 => 8000,
423 _ => 32767,
424 };
425 for _ in 0..n {
426 let at = (rng(&mut s) % 64) as usize;
427 let at = if case % 3 == 0 { at % 12 } else { at };
428 raster[at] = ((rng(&mut s) % (2 * amp + 1)) as i64 - amp as i64) as i16;
429 }
430 if case % 11 == 0 {
431 raster[1..].fill(0);
432 }
433 let mut t = [0i16; 64];
434 for r in 0..8 {
435 for c in 0..8 {
436 t[c * 8 + r] = raster[r * 8 + c];
437 }
438 }
439 let (mut a, mut b) = ([0u8; 128], [0u8; 128]);
440 let mut r1 = raster;
441 reference::idct_put_ref::<B12>(&mut a, 8, &mut r1, false);
442 idct_put::<B12>(&mut b, 8, &mut t);
443 assert_eq!(a, b, "case {case} raster {raster:?}");
444 }
445 }
446
447 #[test]
448 fn simd_matches_reference_10() {
449 check::<false>();
450 }
451
452 #[test]
453 fn simd_matches_reference_12() {
454 check::<true>();
455 }
456}