colconv 0.1.0

SIMD-dispatched color-conversion kernels covering the FFmpeg AVPixelFormat space, with a Sink-based API so consumers pick which derived outputs (RGB / Luma / HSV / custom) they want without paying for the ones they don't.
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
//! Sinker integration tests for `MixedSinker<Vuyx>` — Ship 12c.
//!
//! Coverage:
//! 1. `vuyx_with_rgb_smoke` — gray row → ~mid-gray RGB.
//! 2. `vuyx_with_rgba_forces_alpha_max_with_zero_source` — source X = 0x00,
//!    output α = 0xFF for every pixel.
//! 3. `vuyx_with_rgba_forces_alpha_max_with_random_source` — source X bytes
//!    are random non-zero values (0x42, 0x99, etc.), output α = 0xFF.
//! 4. `vuyx_with_luma_extracts_y_byte` — luma == source Y byte.
//! 5. `vuyx_with_hsv_smoke` — gray row → HSV S = 0.
//! 6. `vuyx_with_rgb_and_rgba_strategy_a_byte_identical` — both attached;
//!    RGB and RGBA's first 3 bytes match; RGBA α = 0xFF (Strategy A).
//! 7. `vuyx_simd_vs_scalar_parity_at_1922` — SIMD path == scalar.
//! 8. `vuyx_width_mismatch_returns_error` — wrong row width → error.
//! 9. `vuyx_row_index_oor_returns_error` — idx >= height → error.
//! 10. `vuyx_rgb_buffer_too_short_returns_error`.
//! 11. `vuyx_rgba_buffer_too_short_returns_error`.
//! 12. `vuyx_luma_buffer_too_short_returns_error`.
//! 13. `vuyx_hsv_buffer_too_short_returns_error`.
//! 14. `vuyx_force_alpha_max_independent_of_source` — headline VUYX
//!     invariant (spec § 8.3): source X bytes are all distinct per pixel
//!     (0x00, 0x42, 0x99, 0xFF, …); output α = 0xFF for every pixel.

#[cfg(all(test, feature = "std"))]
use super::*;

// ---- VUYX frame builder ---------------------------------------------------

/// Builds a solid-color VUYX plane. Each pixel is `[v_val, u_val, y_val,
/// x_val]`. Row stride equals `width x 4` bytes (no padding).
///
/// The `x_val` is the padding byte — it should be ignored by the sinker.
#[cfg(all(test, feature = "std"))]
pub(super) fn solid_vuyx_frame(width: u32, height: u32, v: u8, u: u8, y: u8, x: u8) -> Vec<u8> {
  let quad = [v, u, y, x];
  (0..(width as usize) * (height as usize))
    .flat_map(|_| quad)
    .collect()
}

// ---- 1: RGB smoke ---------------------------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_rgb_smoke() {
  // Gray input: Y=128, U=V=128 (neutral chroma), X=0 (padding ignored).
  // Full-range gray → expect each RGB channel ≈ 128 ± tolerance.
  let buf = solid_vuyx_frame(4, 1, 128, 128, 128, 0);
  let src = VuyxFrame::try_new(&buf, 4, 1, 16).unwrap();
  let mut rgb = std::vec![0u8; 4 * 3];
  let mut sink = MixedSinker::<Vuyx>::new(4, 1).with_rgb(&mut rgb).unwrap();
  vuyx_to(&src, true, ColorMatrix::Bt709, &mut sink).unwrap();
  for px in rgb.chunks(3) {
    assert!(
      px[0].abs_diff(128) <= 4,
      "expected ~128, got R={}, G={}, B={}",
      px[0],
      px[1],
      px[2],
    );
    // Gray → R == G == B.
    assert_eq!(px[0], px[1], "R ≠ G");
    assert_eq!(px[1], px[2], "G ≠ B");
  }
}

// ---- 2: RGBA forces α=0xFF when source X = 0x00 --------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_rgba_forces_alpha_max_with_zero_source() {
  // Source X bytes = 0x00. Output α must still be 0xFF (padding is ignored).
  let buf = solid_vuyx_frame(8, 1, 128, 128, 128, 0x00);
  let src = VuyxFrame::try_new(&buf, 8, 1, 32).unwrap();
  let mut rgba = std::vec![0u8; 8 * 4];
  let mut sink = MixedSinker::<Vuyx>::new(8, 1).with_rgba(&mut rgba).unwrap();
  vuyx_to(&src, true, ColorMatrix::Bt709, &mut sink).unwrap();
  for (i, px) in rgba.chunks(4).enumerate() {
    assert_eq!(
      px[3], 0xFF,
      "pixel {i}: α must be 0xFF regardless of source X=0x00, got {:#X}",
      px[3],
    );
  }
}

// ---- 3: RGBA forces α=0xFF when source X bytes are random non-zero --------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_rgba_forces_alpha_max_with_random_source() {
  // Source X bytes = 0x42 (arbitrary non-zero). Output α must be 0xFF.
  let buf = solid_vuyx_frame(6, 2, 128, 128, 128, 0x42);
  let src = VuyxFrame::try_new(&buf, 6, 2, 24).unwrap();
  let n = 6 * 2;
  let mut rgba = std::vec![0u8; n * 4];
  let mut sink = MixedSinker::<Vuyx>::new(6, 2).with_rgba(&mut rgba).unwrap();
  vuyx_to(&src, true, ColorMatrix::Bt709, &mut sink).unwrap();
  for (i, px) in rgba.chunks(4).enumerate() {
    assert_eq!(
      px[3], 0xFF,
      "pixel {i}: α must be 0xFF, source X=0x42 must be ignored, got {:#X}",
      px[3],
    );
  }
}

// ---- 4: Luma extracts Y byte directly ------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_luma_extracts_y_byte() {
  // Y=0xC0 (192). Luma path must copy the Y byte at offset 2 verbatim.
  let buf = solid_vuyx_frame(8, 2, 128, 128, 0xC0, 0xFF);
  let src = VuyxFrame::try_new(&buf, 8, 2, 32).unwrap();
  let mut luma = std::vec![0u8; 8 * 2];
  let mut sink = MixedSinker::<Vuyx>::new(8, 2).with_luma(&mut luma).unwrap();
  vuyx_to(&src, false, ColorMatrix::Bt709, &mut sink).unwrap();
  assert!(
    luma.iter().all(|&y| y == 0xC0),
    "luma expected 0xC0, got {:?}",
    &luma[..8]
  );
}

// ---- 5: HSV smoke (gray → S = 0) ----------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_hsv_smoke() {
  // Neutral gray → converted RGB R==G==B → HSV saturation S = 0.
  let buf = solid_vuyx_frame(6, 2, 128, 128, 128, 0);
  let src = VuyxFrame::try_new(&buf, 6, 2, 24).unwrap();
  let n = 6 * 2;
  let mut h = std::vec![0u8; n];
  let mut s = std::vec![0u8; n];
  let mut v = std::vec![0u8; n];
  let mut sink = MixedSinker::<Vuyx>::new(6, 2)
    .with_hsv(&mut h, &mut s, &mut v)
    .unwrap();
  vuyx_to(&src, true, ColorMatrix::Bt709, &mut sink).unwrap();
  for &sat in &s {
    assert_eq!(sat, 0, "gray must have S=0 in HSV");
  }
}

// ---- 6: RGB + RGBA Strategy A — byte-identical (α = 0xFF) ---------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_rgb_and_rgba_strategy_a_byte_identical() {
  // When BOTH with_rgb AND with_rgba are attached, VUYX uses Strategy A:
  // RGBA is derived from the RGB row via expand_rgb_to_rgba_row (α=0xFF).
  // Both paths produce α=0xFF — no semantic conflict (spec § 8.4).
  //
  // Verify: RGB and RGBA's first 3 bytes match; RGBA α = 0xFF.
  let width = 8usize;
  let height = 1usize;
  // Use varying X bytes (padding — must be ignored).
  let mut packed = std::vec![0u8; width * 4];
  for n in 0..width {
    packed[n * 4] = 128; // V (neutral chroma)
    packed[n * 4 + 1] = 128; // U (neutral chroma)
    packed[n * 4 + 2] = 200; // Y (bright luma)
    packed[n * 4 + 3] = (n as u8) * 30; // X: padding (0, 30, 60, 90, …)
  }
  let frame = VuyxFrame::try_new(&packed, width as u32, height as u32, (width * 4) as u32).unwrap();
  let mut rgb = std::vec![0u8; width * height * 3];
  let mut rgba = std::vec![0u8; width * height * 4];
  let mut sinker = MixedSinker::<Vuyx>::new(width, height)
    .with_rgb(&mut rgb)
    .unwrap()
    .with_rgba(&mut rgba)
    .unwrap();
  vuyx_to(&frame, true, ColorMatrix::Bt709, &mut sinker).unwrap();

  for n in 0..width {
    // RGB and RGBA RGB-channels must be byte-identical (Strategy A).
    assert_eq!(
      &rgb[n * 3..n * 3 + 3],
      &rgba[n * 4..n * 4 + 3],
      "pixel {n}: RGB and RGBA RGB-channels diverge"
    );
    // RGBA α byte = 0xFF (padding X byte must NOT bleed through).
    assert_eq!(
      rgba[n * 4 + 3],
      0xFF,
      "pixel {n}: RGBA α must be 0xFF, got {:#X}",
      rgba[n * 4 + 3],
    );
  }
}

// ---- 7: SIMD vs scalar parity at width 1922 ------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_simd_vs_scalar_parity_at_1922() {
  // Width 1922 enters and exits the main loop + scalar tail of every
  // backend block size (NEON 16, SSE4.1 16, AVX2 32, AVX-512 64, wasm 16).
  let w = 1922usize;
  let h = 2usize;
  let mut buf = std::vec![0u8; w * h * 4];
  pseudo_random_u8(&mut buf, 0xBEEF_DEAD);
  let src = VuyxFrame::try_new(&buf, w as u32, h as u32, (w * 4) as u32).unwrap();

  let mut rgb_simd = std::vec![0u8; w * h * 3];
  let mut rgb_scalar = std::vec![0u8; w * h * 3];

  let mut sink_simd = MixedSinker::<Vuyx>::new(w, h)
    .with_rgb(&mut rgb_simd)
    .unwrap();
  vuyx_to(&src, false, ColorMatrix::Bt709, &mut sink_simd).unwrap();

  let mut sink_scalar = MixedSinker::<Vuyx>::new(w, h)
    .with_rgb(&mut rgb_scalar)
    .unwrap()
    .with_simd(false);
  vuyx_to(&src, false, ColorMatrix::Bt709, &mut sink_scalar).unwrap();

  assert_eq!(rgb_simd, rgb_scalar, "VUYX SIMD ≠ scalar at width {w}");
}

// ---- 10: RGB buffer too short ---------------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
fn vuyx_rgb_buffer_too_short_returns_error() {
  // 8x4 frame needs 8 x 4 x 3 = 96 bytes; supply only 95.
  let mut rgb = std::vec![0u8; 95];
  let result = MixedSinker::<Vuyx>::new(8, 4).with_rgb(&mut rgb);
  let Err(err) = result else {
    panic!("expected InsufficientRgbBuffer");
  };
  assert_eq!(
    err,
    MixedSinkerError::InsufficientRgbBuffer(InsufficientBuffer::new(96, 95))
  );
}

// ---- 11: RGBA buffer too short -------------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
fn vuyx_rgba_buffer_too_short_returns_error() {
  // 6x4 frame needs 6 x 4 x 4 = 96 bytes; supply only 90.
  let mut rgba = std::vec![0u8; 90];
  let result = MixedSinker::<Vuyx>::new(6, 4).with_rgba(&mut rgba);
  let Err(err) = result else {
    panic!("expected InsufficientRgbaBuffer");
  };
  assert_eq!(
    err,
    MixedSinkerError::InsufficientRgbaBuffer(InsufficientBuffer::new(96, 90))
  );
}

// ---- 12: Luma buffer too short -------------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
fn vuyx_luma_buffer_too_short_returns_error() {
  // 8x3 frame needs 8 x 3 = 24 bytes; supply 20.
  let mut luma = std::vec![0u8; 20];
  let result = MixedSinker::<Vuyx>::new(8, 3).with_luma(&mut luma);
  let Err(err) = result else {
    panic!("expected InsufficientLumaBuffer");
  };
  assert_eq!(
    err,
    MixedSinkerError::InsufficientLumaBuffer(InsufficientBuffer::new(24, 20))
  );
}

// ---- 13: HSV buffer too short (H plane) ----------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
fn vuyx_hsv_buffer_too_short_returns_error() {
  // 4x4 frame needs 16 bytes per HSV plane; supply H with only 15.
  let mut h = std::vec![0u8; 15];
  let mut s = std::vec![0u8; 16];
  let mut v = std::vec![0u8; 16];
  let result = MixedSinker::<Vuyx>::new(4, 4).with_hsv(&mut h, &mut s, &mut v);
  let Err(err) = result else {
    panic!("expected InsufficientHsvPlane");
  };
  assert!(matches!(
    &err,
    MixedSinkerError::InsufficientHsvPlane(e)
      if matches!(e.which(), HsvPlane::H) && e.expected() == 16 && e.actual() == 15
  ));
}

// ---- with_luma_u16 tests -----------------------------------------------

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_with_luma_u16_extracts_y_zero_extended() {
  let width = 64usize;
  let height = 4usize;
  let n = width * height;

  let mut packed = std::vec![0u8; n * 4];
  pseudo_random_u8(&mut packed, 0xDEADBEEF);

  let frame = VuyxFrame::try_new(&packed, width as u32, height as u32, (width * 4) as u32).unwrap();

  let mut luma = std::vec![0u16; n];
  let mut sink = MixedSinker::<Vuyx>::new(width, height)
    .with_luma_u16(&mut luma)
    .unwrap();
  vuyx_to(&frame, false, ColorMatrix::Bt709, &mut sink).unwrap();

  // Reference: Y bytes at offset 2 of each 4-byte pixel quadruple.
  // The X byte at offset 3 must be completely ignored.
  let expected: std::vec::Vec<u16> = (0..n).map(|i| packed[i * 4 + 2] as u16).collect();
  assert_eq!(luma, expected);
}

#[test]
#[cfg(all(test, feature = "std"))]
fn vuyx_luma_u16_buffer_too_short_returns_err() {
  let mut luma = std::vec![0u16; 4 * 4 - 1];
  let result = MixedSinker::<Vuyx>::new(4, 4).with_luma_u16(&mut luma);
  let Err(err) = result else {
    panic!("expected InsufficientLumaU16Buffer");
  };
  assert_eq!(
    err,
    MixedSinkerError::InsufficientLumaU16Buffer(InsufficientBuffer::new(16, 15)),
    "unexpected error: {err:?}"
  );
}

// ---- 14: Force α=0xFF independent of source (headline VUYX invariant) ----

#[test]
#[cfg(all(test, feature = "std"))]
#[cfg_attr(
  miri,
  ignore = "SIMD-dispatched row kernels use intrinsics unsupported by Miri"
)]
fn vuyx_force_alpha_max_independent_of_source() {
  // Headline VUYX invariant (spec § 8.3): the X (padding) byte is
  // truly ignored — output α = 0xFF regardless of what is in the source.
  //
  // Fill source X bytes with all distinct values per pixel:
  // 0x00, 0x42, 0x99, 0xFF, 0x01, 0x7F, 0xAB, 0xCD, …
  // Every pixel has a different X byte. ALL output α must be 0xFF.
  let width = 16usize;
  let height = 4usize;
  let n = width * height;
  let x_pattern: [u8; 8] = [0x00, 0x42, 0x99, 0xFF, 0x01, 0x7F, 0xAB, 0xCD];

  let mut packed = std::vec![0u8; n * 4];
  for i in 0..n {
    packed[i * 4] = 128; // V
    packed[i * 4 + 1] = 128; // U
    packed[i * 4 + 2] = 128; // Y (neutral gray)
    packed[i * 4 + 3] = x_pattern[i % x_pattern.len()]; // X: distinct per pixel
  }
  let src = VuyxFrame::try_new(&packed, width as u32, height as u32, (width * 4) as u32).unwrap();
  let mut rgba = std::vec![0u8; n * 4];
  let mut sink = MixedSinker::<Vuyx>::new(width, height)
    .with_rgba(&mut rgba)
    .unwrap();
  vuyx_to(&src, true, ColorMatrix::Bt709, &mut sink).unwrap();

  for i in 0..n {
    let src_x = x_pattern[i % x_pattern.len()];
    let out_a = rgba[i * 4 + 3];
    assert_eq!(
      out_a, 0xFF,
      "pixel {i}: output α = {out_a:#X} but must be 0xFF (source X = {src_x:#X} must be ignored)"
    );
  }
}