pixon 0.8.0

SIMD-dispatched color conversion for the FFmpeg AVPixelFormat space: one-call decode of validated source frames to RGB / RGBA / Luma / HSV, fused resampling while converting, colorimetry-honest matrices and chroma siting, no_std-friendly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use super::*;

// ---- NV21 MixedSinker ---------------------------------------------------

pub(super) fn solid_nv21_frame(width: u32, height: u32, y: u8, u: u8, v: u8) -> (Vec<u8>, Vec<u8>) {
  let w = width as usize;
  let h = height as usize;
  let ch = h / 2;
  // VU row payload = `width` bytes = `width/2` interleaved V/U pairs
  // (V first).
  let mut vu = std::vec![0u8; w * ch];
  for row in 0..ch {
    for i in 0..w / 2 {
      vu[row * w + i * 2] = v;
      vu[row * w + i * 2 + 1] = u;
    }
  }
  (std::vec![y; w * h], vu)
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_luma_only_copies_y_plane() {
  let (yp, vup) = solid_nv21_frame(16, 8, 42, 128, 128);
  let src = Nv21Frame::new(&yp, &vup, 16, 8, 16, 16);

  let mut luma = std::vec![0u8; 16 * 8];
  let mut sink = MixedSinker::<Nv21>::new(16, 8)
    .with_luma(&mut luma)
    .unwrap();
  nv21_to(&src, true, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap();

  assert!(luma.iter().all(|&y| y == 42));
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_rgb_only_converts_gray_to_gray() {
  let (yp, vup) = solid_nv21_frame(16, 8, 128, 128, 128);
  let src = Nv21Frame::new(&yp, &vup, 16, 8, 16, 16);

  let mut rgb = std::vec![0u8; 16 * 8 * 3];
  let mut sink = MixedSinker::<Nv21>::new(16, 8).with_rgb(&mut rgb).unwrap();
  nv21_to(&src, true, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap();

  for px in rgb.chunks(3) {
    assert!(px[0].abs_diff(128) <= 1);
    assert_eq!(px[0], px[1]);
    assert_eq!(px[1], px[2]);
  }
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_mixed_all_three_outputs_populated() {
  let (yp, vup) = solid_nv21_frame(16, 8, 200, 128, 128);
  let src = Nv21Frame::new(&yp, &vup, 16, 8, 16, 16);

  let mut rgb = std::vec![0u8; 16 * 8 * 3];
  let mut luma = std::vec![0u8; 16 * 8];
  let mut h = std::vec![0u8; 16 * 8];
  let mut s = std::vec![0u8; 16 * 8];
  let mut v = std::vec![0u8; 16 * 8];
  let mut sink = MixedSinker::<Nv21>::new(16, 8)
    .with_rgb(&mut rgb)
    .unwrap()
    .with_luma(&mut luma)
    .unwrap()
    .with_hsv(&mut h, &mut s, &mut v)
    .unwrap();
  nv21_to(&src, true, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap();

  assert!(luma.iter().all(|&y| y == 200));
  for px in rgb.chunks(3) {
    assert!(px[0].abs_diff(200) <= 1);
  }
  assert!(h.iter().all(|&b| b == 0));
  assert!(s.iter().all(|&b| b == 0));
  assert!(v.iter().all(|&b| b.abs_diff(200) <= 1));
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_matches_nv12_mixed_sinker_with_swapped_chroma() {
  // Cross-format guarantee: an NV21 frame built from the same U / V
  // bytes as an NV12 frame (just byte-swapped in the chroma plane)
  // must produce identical RGB output via MixedSinker.
  let w = 32u32;
  let h = 16u32;
  let ws = w as usize;
  let hs = h as usize;

  let yp: Vec<u8> = (0..ws * hs).map(|i| ((i * 37 + 11) & 0xFF) as u8).collect();
  let mut uvp: Vec<u8> = std::vec![0u8; ws * (hs / 2)];
  for r in 0..hs / 2 {
    for c in 0..ws / 2 {
      uvp[r * ws + 2 * c] = ((c + r * 53) & 0xFF) as u8; // U
      uvp[r * ws + 2 * c + 1] = ((c + r * 71) & 0xFF) as u8; // V
    }
  }
  // Byte-swap each chroma pair to get the VU-ordered stream.
  let mut vup: Vec<u8> = uvp.clone();
  for r in 0..hs / 2 {
    for c in 0..ws / 2 {
      vup[r * ws + 2 * c] = uvp[r * ws + 2 * c + 1];
      vup[r * ws + 2 * c + 1] = uvp[r * ws + 2 * c];
    }
  }

  let nv12_src = Nv12Frame::new(&yp, &uvp, w, h, w, w);
  let nv21_src = Nv21Frame::new(&yp, &vup, w, h, w, w);

  let mut rgb_nv12 = std::vec![0u8; ws * hs * 3];
  let mut rgb_nv21 = std::vec![0u8; ws * hs * 3];
  let mut s_nv12 = MixedSinker::<Nv12>::new(ws, hs)
    .with_rgb(&mut rgb_nv12)
    .unwrap();
  let mut s_nv21 = MixedSinker::<Nv21>::new(ws, hs)
    .with_rgb(&mut rgb_nv21)
    .unwrap();
  nv12_to(
    &nv12_src,
    false,
    s_nv12.set_kernel_matrix(KernelMatrix::Bt709),
  )
  .unwrap();
  nv21_to(
    &nv21_src,
    false,
    s_nv21.set_kernel_matrix(KernelMatrix::Bt709),
  )
  .unwrap();

  assert_eq!(rgb_nv12, rgb_nv21);
}

// NV21 RGBA tests.
//
// Mirrors the NV12 RGBA tests. The cross-format invariant against
// NV12 RGBA (with byte-swapped chroma) catches the case where
// SWAP_UV is wired through correctly for the RGB path but not the
// RGBA path.

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_rgba_only_converts_gray_to_gray_with_opaque_alpha() {
  let (yp, vup) = solid_nv21_frame(16, 8, 128, 128, 128);
  let src = Nv21Frame::new(&yp, &vup, 16, 8, 16, 16);

  let mut rgba = std::vec![0u8; 16 * 8 * 4];
  let mut sink = MixedSinker::<Nv21>::new(16, 8)
    .with_rgba(&mut rgba)
    .unwrap();
  nv21_to(&src, true, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap();

  for px in rgba.chunks(4) {
    assert!(px[0].abs_diff(128) <= 1, "R");
    assert_eq!(px[0], px[1], "RGB monochromatic");
    assert_eq!(px[1], px[2], "RGB monochromatic");
    assert_eq!(px[3], 0xFF, "alpha must default to opaque");
  }
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_with_rgb_and_with_rgba_produce_byte_identical_rgb_bytes() {
  let w = 32usize;
  let h = 16usize;
  let (yp, vup) = solid_nv21_frame(w as u32, h as u32, 180, 60, 200);
  let src = Nv21Frame::new(&yp, &vup, w as u32, h as u32, w as u32, w as u32);

  let mut rgb = std::vec![0u8; w * h * 3];
  let mut rgba = std::vec![0u8; w * h * 4];
  let mut sink = MixedSinker::<Nv21>::new(w, h)
    .with_rgb(&mut rgb)
    .unwrap()
    .with_rgba(&mut rgba)
    .unwrap();
  nv21_to(&src, true, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap();

  for i in 0..(w * h) {
    assert_eq!(rgba[i * 4], rgb[i * 3], "R differs at pixel {i}");
    assert_eq!(rgba[i * 4 + 1], rgb[i * 3 + 1], "G differs at pixel {i}");
    assert_eq!(rgba[i * 4 + 2], rgb[i * 3 + 2], "B differs at pixel {i}");
    assert_eq!(rgba[i * 4 + 3], 0xFF, "A not opaque at pixel {i}");
  }
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_rgba_simd_matches_scalar_with_random_yuv() {
  let w = 1922usize;
  let h = 4usize;
  let mut yp = std::vec![0u8; w * h];
  let mut vup = std::vec![0u8; w * (h / 2)];
  pseudo_random_u8(&mut yp, 0xC001_C0DE);
  pseudo_random_u8(&mut vup, 0xCAFE_F00D);
  let src = Nv21Frame::new(&yp, &vup, w as u32, h as u32, w as u32, w as u32);

  for &matrix in &[
    KernelMatrix::Bt601,
    KernelMatrix::Bt709,
    KernelMatrix::Bt2020Ncl,
    KernelMatrix::YCgCo,
  ] {
    for &full_range in &[true, false] {
      let mut rgba_simd = std::vec![0u8; w * h * 4];
      let mut rgba_scalar = std::vec![0u8; w * h * 4];

      let mut s_simd = MixedSinker::<Nv21>::new(w, h)
        .with_rgba(&mut rgba_simd)
        .unwrap();
      nv21_to(&src, full_range, s_simd.set_kernel_matrix(matrix)).unwrap();

      let mut s_scalar = MixedSinker::<Nv21>::new(w, h)
        .with_rgba(&mut rgba_scalar)
        .unwrap();
      s_scalar.set_simd(false);
      nv21_to(&src, full_range, s_scalar.set_kernel_matrix(matrix)).unwrap();

      if rgba_simd != rgba_scalar {
        let mismatch = rgba_simd
          .iter()
          .zip(rgba_scalar.iter())
          .position(|(a, b)| a != b)
          .unwrap();
        let pixel = mismatch / 4;
        let channel = ["R", "G", "B", "A"][mismatch % 4];
        panic!(
          "NV21 RGBA SIMD ≠ scalar at byte {mismatch} (px {pixel} {channel}) for matrix={matrix:?} full_range={full_range}: simd={} scalar={}",
          rgba_simd[mismatch], rgba_scalar[mismatch]
        );
      }
    }
  }
}

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_rgba_matches_nv12_rgba_with_swapped_chroma() {
  // Cross-format invariant on the RGBA path. Same shape as
  // `nv21_matches_nv12_mixed_sinker_with_swapped_chroma` for RGB:
  // building NV21 from NV12's bytes with the chroma pairs swapped
  // must produce byte-identical RGBA. Catches cases where SWAP_UV
  // is honored for RGB but not RGBA.
  let w = 32u32;
  let h = 16u32;
  let ws = w as usize;
  let hs = h as usize;

  let yp: Vec<u8> = (0..ws * hs).map(|i| ((i * 37 + 11) & 0xFF) as u8).collect();
  let mut uvp: Vec<u8> = std::vec![0u8; ws * (hs / 2)];
  for r in 0..hs / 2 {
    for c in 0..ws / 2 {
      uvp[r * ws + 2 * c] = ((c + r * 53) & 0xFF) as u8;
      uvp[r * ws + 2 * c + 1] = ((c + r * 71) & 0xFF) as u8;
    }
  }
  let mut vup: Vec<u8> = uvp.clone();
  for r in 0..hs / 2 {
    for c in 0..ws / 2 {
      vup[r * ws + 2 * c] = uvp[r * ws + 2 * c + 1];
      vup[r * ws + 2 * c + 1] = uvp[r * ws + 2 * c];
    }
  }

  let nv12_src = Nv12Frame::new(&yp, &uvp, w, h, w, w);
  let nv21_src = Nv21Frame::new(&yp, &vup, w, h, w, w);

  let mut rgba_nv12 = std::vec![0u8; ws * hs * 4];
  let mut rgba_nv21 = std::vec![0u8; ws * hs * 4];
  let mut s_nv12 = MixedSinker::<Nv12>::new(ws, hs)
    .with_rgba(&mut rgba_nv12)
    .unwrap();
  let mut s_nv21 = MixedSinker::<Nv21>::new(ws, hs)
    .with_rgba(&mut rgba_nv21)
    .unwrap();
  nv12_to(
    &nv12_src,
    false,
    s_nv12.set_kernel_matrix(KernelMatrix::Bt709),
  )
  .unwrap();
  nv21_to(
    &nv21_src,
    false,
    s_nv21.set_kernel_matrix(KernelMatrix::Bt709),
  )
  .unwrap();

  assert_eq!(rgba_nv12, rgba_nv21);
}

// ---- with_luma_u16 (Task 2) -----------------------------------------------

#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_with_luma_u16_extracts_y_zero_extended() {
  let width = 64usize;
  let height = 4usize;
  let n = width * height;
  let ch = height / 2;

  let mut yp = std::vec![0u8; n];
  let mut vup = std::vec![0u8; width * ch];
  pseudo_random_u8(&mut yp, 0xC0FFEE);
  pseudo_random_u8(&mut vup, 0xBADF00D);

  let src = Nv21Frame::new(
    &yp,
    &vup,
    width as u32,
    height as u32,
    width as u32,
    width as u32,
  );

  let mut luma_out = std::vec![0u16; n];
  let mut sink = MixedSinker::<Nv21>::new(width, height)
    .with_luma_u16(&mut luma_out)
    .unwrap();
  nv21_to(&src, false, sink.set_kernel_matrix(KernelMatrix::Bt709)).unwrap();

  let expected: std::vec::Vec<u16> = yp.iter().map(|&y| y as u16).collect();
  assert_eq!(luma_out, expected, "Nv21 luma_u16 mismatch");
}

#[test]
fn nv21_luma_u16_buffer_too_short_returns_err() {
  let mut buf = std::vec![0u16; 16 * 8 - 1];
  let err = MixedSinker::<Nv21>::new(16, 8)
    .with_luma_u16(&mut buf)
    .err()
    .unwrap();
  assert_eq!(
    err,
    MixedSinkerError::InsufficientLumaU16Buffer(InsufficientBuffer::new(128, 127))
  );
}

// Atomicity (#308): the up-front RGB-scratch preflight must return
// `AllocationFailed` BEFORE any output row is written, so an allocator refusal
// leaves the output frame untouched. Mirrors the planar_8bit / Yuv420p
// siblings. Reuses the crate's RGB-scratch failpoint (`yuva`-gated, so this
// test is too; under `--all-features` both `yuv-semi-planar` and `yuva` are
// on).
#[cfg(feature = "yuva")]
#[test]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn nv21_rgb_scratch_alloc_failure_leaves_outputs_untouched() {
  use crate::resample::ResampleError;

  // luma + RGBA + HSV with NO rgb output: `want_hsv && want_rgba && !want_rgb`
  // needs an RGB row but has no caller RGB buffer, so the decode grows the RGB
  // row scratch (`rgb_row_buf_or_scratch`'s scratch arm). With that allocation
  // armed to fail, the preflight returns AllocationFailed BEFORE any output
  // row — luma included — is written.
  let (yp, vup) = solid_nv21_frame(16, 8, 42, 128, 128);
  let src = Nv21Frame::new(&yp, &vup, 16, 8, 16, 16);
  let mut luma = std::vec![0xABu8; 16 * 8];
  let mut rgba = std::vec![0xCDu8; 16 * 8 * 4];
  let (mut hh, mut ss, mut vv) = (
    std::vec![0xCDu8; 16 * 8],
    std::vec![0xCDu8; 16 * 8],
    std::vec![0xCDu8; 16 * 8],
  );
  let mut sink = MixedSinker::<Nv21>::new(16, 8)
    .with_luma(&mut luma)
    .unwrap()
    .with_rgba(&mut rgba)
    .unwrap()
    .with_hsv(&mut hh, &mut ss, &mut vv)
    .unwrap();

  super::super::super::arm_rgb_scratch_alloc_failure();
  let err = nv21_to(&src, false, sink.set_kernel_matrix(KernelMatrix::Bt601)).unwrap_err();
  drop(sink);

  assert!(
    matches!(
      err,
      MixedSinkerError::Resample(ResampleError::AllocationFailed(_))
    ),
    "RGB-scratch refusal must surface as a recoverable AllocationFailed, got {err:?}"
  );
  assert!(
    luma.iter().all(|&b| b == 0xAB),
    "luma must be untouched on the rgb-scratch alloc-failure path"
  );
}