rusty_esp_dsp 0.1.2

ESP-DSP remade for the Janus family: the scalar kernel home (pixel conversions and downscales, PCM reductions and sample-format conversion, the H.264 block costs, the work counters and ceiling probe) where every kernel is the oracle for a PIE twin. no_std, forbid(unsafe), no allocator, no drivers.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Pixel kernels — scalar, bounds-checked, and the oracle for every faster twin.
//!
//! These are the conversions a camera pipeline on an ESP32 actually needs:
//! what the sensor emits (YUYV, RGB565) into what an encoder, a model or an
//! LCD wants (RGB888, gray, a smaller frame). Every function takes borrowed
//! input and caller-owned output and returns the geometry it produced.
//!
//! Colour conversion is BT.601 full-range (the JFIF convention), fixed-point
//! with an 8-bit fraction — the same arithmetic on every platform.
//!
//! Moved verbatim from `rusty_esp_image-core::ops` (D0, 2026-09-02); the
//! oracle test in `tests/moved.rs` holds the copies this module replaced and
//! demands byte identity over a generated corpus.

use rusty_esp_core::error::{Error, Result};
use rusty_esp_core::frame::{Geometry, PixelFormat};
use rusty_esp_core::pcm::{as_u16, as_u16_mut};

use crate::expect_len;

/// Pack an RGB888 pixel as little-endian RGB565.
#[must_use]
pub const fn pack_rgb565(r: u8, g: u8, b: u8) -> u16 {
    ((r as u16 & 0xF8) << 8) | ((g as u16 & 0xFC) << 3) | (b as u16 >> 3)
}

/// Unpack a little-endian RGB565 pixel to RGB888, replicating the top bits
/// into the low bits so white stays white.
#[must_use]
pub const fn unpack_rgb565(p: u16) -> [u8; 3] {
    let r5 = ((p >> 11) & 0x1F) as u8;
    let g6 = ((p >> 5) & 0x3F) as u8;
    let b5 = (p & 0x1F) as u8;
    [
        (r5 << 3) | (r5 >> 2),
        (g6 << 2) | (g6 >> 4),
        (b5 << 3) | (b5 >> 2),
    ]
}

/// One RGB565 channel widened to 8 bits, top bits replicated into the low
/// bits — exactly the per-channel arithmetic of [`unpack_rgb565`], but taken
/// straight from the packed pixel and already widened, so a caller that wants
/// one channel of several pixels never materialises the `[u8; 3]`s.
#[inline]
const fn r5to8(p: u16) -> u32 {
    let v = ((p >> 11) & 0x1F) as u32;
    (v << 3) | (v >> 2)
}

#[inline]
const fn g6to8(p: u16) -> u32 {
    let v = ((p >> 5) & 0x3F) as u32;
    (v << 2) | (v >> 4)
}

#[inline]
const fn b5to8(p: u16) -> u32 {
    let v = (p & 0x1F) as u32;
    (v << 3) | (v >> 2)
}

/// BT.601 full-range YCbCr → RGB888, fixed-point.
#[must_use]
pub fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] {
    let y = i32::from(y);
    let cb = i32::from(u) - 128;
    let cr = i32::from(v) - 128;
    let r = y + ((359 * cr) >> 8);
    let g = y - ((88 * cb + 183 * cr) >> 8);
    let b = y + ((454 * cb) >> 8);
    [clamp(r), clamp(g), clamp(b)]
}

fn clamp(v: i32) -> u8 {
    v.clamp(0, 255) as u8
}

/// RGB565 (LE) → RGB888. `src` holds `pixels × 2` bytes, `dst` `pixels × 3`.
pub fn rgb565_to_rgb888(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    if src.len() % 2 != 0 {
        return Err(Error::InvalidGeometry);
    }
    let pixels = src.len() / 2;
    expect_len(dst, pixels * 3)?;
    // FAST ARM: the source IS u16. Each pixel costs one halfword load where
    // the byte path needs two loads, a shift and an or. The destination is
    // three bytes a pixel and cannot be viewed, so only the read side moves.
    if let Some(sv) = as_u16(src) {
        let dv = &mut dst[..pixels * 3];
        // EIGHT. Sixteen measured +39.6% against a 0.0% null arm on an
        // ESP32-S3 (2026-09-19): the three-byte destination store is what
        // limits this body, and widening only adds live values.
        let body = pixels / 8 * 8;
        let (svb, svt) = sv.split_at(body);
        let (dvb, dvt) = dv.split_at_mut(body * 3);
        for (s, d) in svb.chunks_exact(8).zip(dvb.chunks_exact_mut(24)) {
            for k in 0..8 {
                d[k * 3..k * 3 + 3].copy_from_slice(&unpack_rgb565(s[k]));
            }
        }
        for (s, d) in svt.iter().zip(dvt.chunks_exact_mut(3)) {
            d.copy_from_slice(&unpack_rgb565(*s));
        }
        return Ok(pixels);
    }

    // BYTE ARM: the oracle, and the misaligned fallback.
    // Four pixels per trip: one 2-byte load and one 3-byte store per trip is
    // mostly loop overhead and a dependent load-store pair. Same unpack.
    let body = pixels / 8 * 8;
    let (sb, st) = src.split_at(body * 2);
    let (db, dt) = dst[..pixels * 3].split_at_mut(body * 3);
    for (s, d) in sb.chunks_exact(16).zip(db.chunks_exact_mut(24)) {
        d[0..3].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[0], s[1]])));
        d[3..6].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[2], s[3]])));
        d[6..9].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[4], s[5]])));
        d[9..12].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[6], s[7]])));
        d[12..15].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[8], s[9]])));
        d[15..18].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[10], s[11]])));
        d[18..21].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[12], s[13]])));
        d[21..24].copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[14], s[15]])));
    }
    for (s, d) in st.chunks_exact(2).zip(dt.chunks_exact_mut(3)) {
        d.copy_from_slice(&unpack_rgb565(u16::from_le_bytes([s[0], s[1]])));
    }
    Ok(pixels)
}

/// RGB888 → RGB565 (LE).
pub fn rgb888_to_rgb565(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    if src.len() % 3 != 0 {
        return Err(Error::InvalidGeometry);
    }
    let pixels = src.len() / 3;
    expect_len(dst, pixels * 2)?;
    // FAST ARM: the destination IS u16 -- one halfword store a pixel where
    // the byte path needs two. The source is three bytes a pixel and cannot
    // be viewed, so only the write side moves.
    if let Some(dv) = as_u16_mut(&mut dst[..pixels * 2]) {
        let body = pixels / 16 * 16;
        let (sb, st) = src.split_at(body * 3);
        let (dvb, dvt) = dv.split_at_mut(body);
        for (s, d) in sb.chunks_exact(48).zip(dvb.chunks_exact_mut(16)) {
            for k in 0..16 {
                d[k] = pack_rgb565(s[k * 3], s[k * 3 + 1], s[k * 3 + 2]);
            }
        }
        for (s, d) in st.chunks_exact(3).zip(dvt.iter_mut()) {
            *d = pack_rgb565(s[0], s[1], s[2]);
        }
        return Ok(pixels);
    }

    // BYTE ARM: the oracle, and the misaligned fallback.
    // Four pixels per trip, as in rgb565_to_rgb888. Same pack.
    let body = pixels / 8 * 8;
    let (sb, st) = src.split_at(body * 3);
    let (db, dt) = dst[..pixels * 2].split_at_mut(body * 2);
    for (s, d) in sb.chunks_exact(24).zip(db.chunks_exact_mut(16)) {
        d[0..2].copy_from_slice(&pack_rgb565(s[0], s[1], s[2]).to_le_bytes());
        d[2..4].copy_from_slice(&pack_rgb565(s[3], s[4], s[5]).to_le_bytes());
        d[4..6].copy_from_slice(&pack_rgb565(s[6], s[7], s[8]).to_le_bytes());
        d[6..8].copy_from_slice(&pack_rgb565(s[9], s[10], s[11]).to_le_bytes());
        d[8..10].copy_from_slice(&pack_rgb565(s[12], s[13], s[14]).to_le_bytes());
        d[10..12].copy_from_slice(&pack_rgb565(s[15], s[16], s[17]).to_le_bytes());
        d[12..14].copy_from_slice(&pack_rgb565(s[18], s[19], s[20]).to_le_bytes());
        d[14..16].copy_from_slice(&pack_rgb565(s[21], s[22], s[23]).to_le_bytes());
    }
    for (s, d) in st.chunks_exact(3).zip(dt.chunks_exact_mut(2)) {
        d.copy_from_slice(&pack_rgb565(s[0], s[1], s[2]).to_le_bytes());
    }
    Ok(pixels)
}

/// YUYV (Y0 U Y1 V) → RGB888. `src` holds `pixels × 2` bytes (pixels even).
pub fn yuyv_to_rgb888(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    if src.len() % 4 != 0 {
        return Err(Error::InvalidGeometry);
    }
    let pixels = src.len() / 2;
    expect_len(dst, pixels * 3)?;
    // Four pixels (two macropixels) per trip. Same conversions.
    // Four pixels per trip. EIGHT measured +1.9% worse on the S3
    // (334,759 -> 340,999 ps/px, 2026-09-19): this body already carries two
    // full colour conversions, so it is not loop-overhead-bound.
    let body = pixels / 4 * 4;
    let (sb, st) = src.split_at(body * 2);
    let (db, dt) = dst[..pixels * 3].split_at_mut(body * 3);
    for (s, d) in sb.chunks_exact(8).zip(db.chunks_exact_mut(12)) {
        d[0..3].copy_from_slice(&yuv_to_rgb(s[0], s[1], s[3]));
        d[3..6].copy_from_slice(&yuv_to_rgb(s[2], s[1], s[3]));
        d[6..9].copy_from_slice(&yuv_to_rgb(s[4], s[5], s[7]));
        d[9..12].copy_from_slice(&yuv_to_rgb(s[6], s[5], s[7]));
    }
    for (s, d) in st.chunks_exact(4).zip(dt.chunks_exact_mut(6)) {
        d[..3].copy_from_slice(&yuv_to_rgb(s[0], s[1], s[3]));
        d[3..].copy_from_slice(&yuv_to_rgb(s[2], s[1], s[3]));
    }
    Ok(pixels)
}

/// YUYV → RGB565 (LE).
pub fn yuyv_to_rgb565(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    if src.len() % 4 != 0 {
        return Err(Error::InvalidGeometry);
    }
    let pixels = src.len() / 2;
    expect_len(dst, pixels * 2)?;
    // FAST ARM: the destination IS u16 -- one halfword store a pixel.
    if let Some(dv) = as_u16_mut(&mut dst[..pixels * 2]) {
        // FOUR macropixels. Eight measured +8.3% against a 0.0% null arm.
        let body = pixels / 8 * 8;
        let (sb, st) = src.split_at(body * 2);
        let (dvb, dvt) = dv.split_at_mut(body);
        for (s, d) in sb.chunks_exact(16).zip(dvb.chunks_exact_mut(8)) {
            for k in 0..4 {
                let (i, o) = (k * 4, k * 2);
                let [r0, g0, b0] = yuv_to_rgb(s[i], s[i + 1], s[i + 3]);
                let [r1, g1, b1] = yuv_to_rgb(s[i + 2], s[i + 1], s[i + 3]);
                d[o] = pack_rgb565(r0, g0, b0);
                d[o + 1] = pack_rgb565(r1, g1, b1);
            }
        }
        for (s, d) in st.chunks_exact(4).zip(dvt.chunks_exact_mut(2)) {
            let [r0, g0, b0] = yuv_to_rgb(s[0], s[1], s[3]);
            let [r1, g1, b1] = yuv_to_rgb(s[2], s[1], s[3]);
            d[0] = pack_rgb565(r0, g0, b0);
            d[1] = pack_rgb565(r1, g1, b1);
        }
        return Ok(pixels);
    }

    // BYTE ARM: the oracle, and the misaligned fallback.
    // Four pixels (two macropixels) per trip. Same conversions and pack.
    let body = pixels / 8 * 8;
    let (sb, st) = src.split_at(body * 2);
    let (db, dt) = dst[..pixels * 2].split_at_mut(body * 2);
    for (s, d) in sb.chunks_exact(16).zip(db.chunks_exact_mut(16)) {
        for (i, o) in [(0usize, 0usize), (4, 4), (8, 8), (12, 12)] {
            let [r0, g0, b0] = yuv_to_rgb(s[i], s[i + 1], s[i + 3]);
            let [r1, g1, b1] = yuv_to_rgb(s[i + 2], s[i + 1], s[i + 3]);
            d[o..o + 2].copy_from_slice(&pack_rgb565(r0, g0, b0).to_le_bytes());
            d[o + 2..o + 4].copy_from_slice(&pack_rgb565(r1, g1, b1).to_le_bytes());
        }
    }
    for (s, d) in st.chunks_exact(4).zip(dt.chunks_exact_mut(4)) {
        let [r0, g0, b0] = yuv_to_rgb(s[0], s[1], s[3]);
        let [r1, g1, b1] = yuv_to_rgb(s[2], s[1], s[3]);
        d[..2].copy_from_slice(&pack_rgb565(r0, g0, b0).to_le_bytes());
        d[2..].copy_from_slice(&pack_rgb565(r1, g1, b1).to_le_bytes());
    }
    Ok(pixels)
}

/// YUYV → Gray8: the luma bytes.
pub fn yuyv_to_gray8(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    if src.len() % 2 != 0 {
        return Err(Error::InvalidGeometry);
    }
    let pixels = src.len() / 2;
    expect_len(dst, pixels)?;
    // Four pixels (eight source bytes) per trip. One pixel per trip is a
    // single dependent load-store pair wrapped in loop overhead, which an
    // in-order core cannot overlap; four give the loads room to pipeline.
    // Same bytes selected, so the output is identical.
    let body = pixels / 16 * 16;
    let (sb, st) = src.split_at(body * 2);
    let (db, dt) = dst[..pixels].split_at_mut(body);
    for (s, d) in sb.chunks_exact(32).zip(db.chunks_exact_mut(16)) {
        for k in 0..16 {
            d[k] = s[k * 2];
        }
    }
    for (s, d) in st.chunks_exact(2).zip(dt.iter_mut()) {
        *d = s[0];
    }
    Ok(pixels)
}

/// 2× box downscale of a Gray8 image; odd trailing rows/columns are dropped.
/// Returns the output geometry.
pub fn downscale2x_gray8(src: &[u8], width: u32, height: u32, dst: &mut [u8]) -> Result<Geometry> {
    let (w, h) = (width as usize, height as usize);
    expect_len(src, w * h)?;
    let (ow, oh) = (w / 2, h / 2);
    let out = Geometry::new(ow as u32, oh as u32, PixelFormat::Gray8)?;
    expect_len(dst, ow * oh)?;
    // Slice both source rows to exactly the span this row reads and slice the
    // destination row too, then walk them as fixed 2-byte chunks. Indexing
    // `r0[2 * ox + 1]` and `dst[oy * ow + ox]` left the compiler unable to
    // prove either index in range, so each output pixel carried its own
    // bounds checks. Same arithmetic, same order, identical output bytes.
    let span = ow * 2;
    for oy in 0..oh {
        let r0 = &src[(2 * oy) * w..(2 * oy) * w + span];
        let r1 = &src[(2 * oy + 1) * w..(2 * oy + 1) * w + span];
        let drow = &mut dst[oy * ow..oy * ow + ow];
        // Two output pixels per trip: one 4-load/1-store body is mostly loop
        // overhead. Same sums, same rounding.
        // Two output pixels per trip. FOUR measured +2.8% WORSE on the S3
        // (234,060 -> 240,629 ps/px_out, 2026-09-19): past two, this body
        // stops being loop-overhead-bound and starts costing registers.
        let pairs = ow / 2 * 2;
        let (r0b, r0t) = r0.split_at(pairs * 2);
        let (r1b, r1t) = r1.split_at(pairs * 2);
        let (db, dt) = drow.split_at_mut(pairs);
        for ((a, b), d) in r0b
            .chunks_exact(4)
            .zip(r1b.chunks_exact(4))
            .zip(db.chunks_exact_mut(2))
        {
            let s0 = u32::from(a[0]) + u32::from(a[1]) + u32::from(b[0]) + u32::from(b[1]);
            let s1 = u32::from(a[2]) + u32::from(a[3]) + u32::from(b[2]) + u32::from(b[3]);
            d[0] = ((s0 + 2) / 4) as u8;
            d[1] = ((s1 + 2) / 4) as u8;
        }
        for ((a, b), d) in r0t
            .chunks_exact(2)
            .zip(r1t.chunks_exact(2))
            .zip(dt.iter_mut())
        {
            let sum = u32::from(a[0]) + u32::from(a[1]) + u32::from(b[0]) + u32::from(b[1]);
            *d = ((sum + 2) / 4) as u8;
        }
    }
    Ok(out)
}

/// 2× box downscale of an RGB565 (LE) image, per channel.
pub fn downscale2x_rgb565(src: &[u8], width: u32, height: u32, dst: &mut [u8]) -> Result<Geometry> {
    let (w, h) = (width as usize, height as usize);
    expect_len(src, w * h * 2)?;
    let (ow, oh) = (w / 2, h / 2);
    let out = Geometry::new(ow as u32, oh as u32, PixelFormat::Rgb565)?;
    expect_len(dst, ow * oh * 2)?;
    // Hoist the two source rows and the destination row per output row, then
    // walk them as fixed 4-byte (two-pixel) chunks. Indexing the whole `src`
    // through a closure that re-derived `(y * w + x) * 2` cost four
    // bounds-checked pairs of loads per output pixel; the gray8 twin has
    // always sliced its rows, which is why it ran ~6x faster for the same
    // shape of work. The arithmetic below is unchanged, so every output byte
    // is identical.
    // FAST ARM: both sides are u16, so a source pixel is one halfword load
    // and an output pixel one halfword store -- this kernel reads FOUR and
    // writes one, so it pays the marshalling five times per output pixel.
    if let (Some(sv), Some(dvv)) = (as_u16(src), as_u16_mut(&mut dst[..ow * oh * 2])) {
        for oy in 0..oh {
            let r0 = &sv[(2 * oy) * w..(2 * oy) * w + ow * 2];
            let r1 = &sv[(2 * oy + 1) * w..(2 * oy + 1) * w + ow * 2];
            let drow = &mut dvv[oy * ow..oy * ow + ow];
            // FOUR output pixels a trip. The byte arm's measured best width
            // was ONE, but that body carried eight byte loads plus the shifts
            // and ors to assemble them; this one carries four halfword loads,
            // so the stopping point is a different question and is measured
            // here rather than inherited.
            // FOUR. Eight measured +10.7% against a 0.0% null arm on an
            // ESP32-S3 (2026-09-19); one measured +14.9% worse than four.
            // The stop moved from 1 (the byte arm) to 4 when the loads became
            // halfwords, which is why it was re-measured rather than
            // inherited.
            let mut c0 = r0.chunks_exact(8);
            let mut c1 = r1.chunks_exact(8);
            let mut cd = drow.chunks_exact_mut(4);
            for ((s0, s1), d) in c0.by_ref().zip(c1.by_ref()).zip(cd.by_ref()) {
                for k in 0..4 {
                    let (q0, q1) = (s0[k * 2], s0[k * 2 + 1]);
                    let (q2, q3) = (s1[k * 2], s1[k * 2 + 1]);
                    let r = ((r5to8(q0) + r5to8(q1) + r5to8(q2) + r5to8(q3) + 2) / 4) as u8;
                    let g = ((g6to8(q0) + g6to8(q1) + g6to8(q2) + g6to8(q3) + 2) / 4) as u8;
                    let b = ((b5to8(q0) + b5to8(q1) + b5to8(q2) + b5to8(q3) + 2) / 4) as u8;
                    d[k] = pack_rgb565(r, g, b);
                }
            }
            for ((s0, s1), d) in c0
                .remainder()
                .chunks_exact(2)
                .zip(c1.remainder().chunks_exact(2))
                .zip(cd.into_remainder().iter_mut())
            {
                // Keep the four PACKED pixels live and widen one channel at a
                // time, exactly as the byte arm does -- unpacking all four
                // first spills the register window.
                let (q0, q1, q2, q3) = (s0[0], s0[1], s1[0], s1[1]);
                let r = ((r5to8(q0) + r5to8(q1) + r5to8(q2) + r5to8(q3) + 2) / 4) as u8;
                let g = ((g6to8(q0) + g6to8(q1) + g6to8(q2) + g6to8(q3) + 2) / 4) as u8;
                let b = ((b5to8(q0) + b5to8(q1) + b5to8(q2) + b5to8(q3) + 2) / 4) as u8;
                *d = pack_rgb565(r, g, b);
            }
        }
        return Ok(out);
    }

    // BYTE ARM: the oracle, and the misaligned fallback.
    let stride = w * 2;
    let span = ow * 4; // the two-pixel columns this row actually reads
    for oy in 0..oh {
        let r0 = &src[(2 * oy) * stride..(2 * oy) * stride + span];
        let r1 = &src[(2 * oy + 1) * stride..(2 * oy + 1) * stride + span];
        let drow = &mut dst[oy * ow * 2..oy * ow * 2 + ow * 2];
        for ((s0, s1), d) in r0
            .chunks_exact(4)
            .zip(r1.chunks_exact(4))
            .zip(drow.chunks_exact_mut(2))
        {
            // Keep the four PACKED pixels live and widen one channel at a
            // time. Unpacking all four into `[u8; 3]` first put twelve values
            // plus three iterators live at once, far past the usable Xtensa
            // register window, and the loop spilled: 30 stores per output
            // pixel where the algorithm needs two. Same per-channel
            // arithmetic and rounding, so the output bytes are identical.
            let q0 = u16::from_le_bytes([s0[0], s0[1]]);
            let q1 = u16::from_le_bytes([s0[2], s0[3]]);
            let q2 = u16::from_le_bytes([s1[0], s1[1]]);
            let q3 = u16::from_le_bytes([s1[2], s1[3]]);
            let r = ((r5to8(q0) + r5to8(q1) + r5to8(q2) + r5to8(q3) + 2) / 4) as u8;
            let g = ((g6to8(q0) + g6to8(q1) + g6to8(q2) + g6to8(q3) + 2) / 4) as u8;
            let b = ((b5to8(q0) + b5to8(q1) + b5to8(q2) + b5to8(q3) + 2) / 4) as u8;
            d.copy_from_slice(&pack_rgb565(r, g, b).to_le_bytes());
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rgb565_pack_unpack_extremes_and_round_trip() {
        assert_eq!(pack_rgb565(255, 255, 255), 0xFFFF);
        assert_eq!(pack_rgb565(0, 0, 0), 0);
        assert_eq!(unpack_rgb565(0xFFFF), [255, 255, 255]);
        assert_eq!(unpack_rgb565(0xF800), [255, 0, 0]);
        assert_eq!(unpack_rgb565(0x07E0), [0, 255, 0]);
        assert_eq!(unpack_rgb565(0x001F), [0, 0, 255]);
        // round trip within quantisation
        for &(r, g, b) in &[(10u8, 200u8, 77u8), (128, 128, 128), (1, 2, 3)] {
            let [r2, g2, b2] = unpack_rgb565(pack_rgb565(r, g, b));
            assert!((i32::from(r) - i32::from(r2)).abs() <= 7);
            assert!((i32::from(g) - i32::from(g2)).abs() <= 3);
            assert!((i32::from(b) - i32::from(b2)).abs() <= 7);
        }
    }

    #[test]
    fn yuv_known_points() {
        assert_eq!(yuv_to_rgb(128, 128, 128), [128, 128, 128]);
        assert_eq!(yuv_to_rgb(255, 128, 128), [255, 255, 255]);
        assert_eq!(yuv_to_rgb(0, 128, 128), [0, 0, 0]);
        // pure red in JFIF: Y=76, Cb=85, Cr=255
        let [r, g, b] = yuv_to_rgb(76, 85, 255);
        assert!(r >= 250 && g <= 3 && b <= 3, "{r} {g} {b}");
        // pure blue: Y=29, Cb=255, Cr=107
        let [r, g, b] = yuv_to_rgb(29, 255, 107);
        assert!(b >= 250 && r <= 3 && g <= 3, "{r} {g} {b}");
    }

    #[test]
    fn conversions_and_sizes() {
        let rgb = [255u8, 0, 0, 0, 255, 0];
        let mut p = [0u8; 4];
        assert_eq!(rgb888_to_rgb565(&rgb, &mut p).unwrap(), 2);
        assert_eq!(p, [0x00, 0xF8, 0xE0, 0x07]);
        let mut back = [0u8; 6];
        assert_eq!(rgb565_to_rgb888(&p, &mut back).unwrap(), 2);
        assert_eq!(back, rgb);
        let mut small = [0u8; 3];
        assert_eq!(
            rgb565_to_rgb888(&p, &mut small),
            Err(Error::BufferTooSmall { needed: 6 })
        );
        assert_eq!(
            rgb565_to_rgb888(&p[..3], &mut back),
            Err(Error::InvalidGeometry)
        );

        let yuyv = [128u8, 128, 255, 128];
        let mut rgb = [0u8; 6];
        assert_eq!(yuyv_to_rgb888(&yuyv, &mut rgb).unwrap(), 2);
        assert_eq!(rgb, [128, 128, 128, 255, 255, 255]);
        let mut g = [0u8; 2];
        yuyv_to_gray8(&yuyv, &mut g).unwrap();
        assert_eq!(g, [128, 255]);
        let mut p = [0u8; 4];
        yuyv_to_rgb565(&yuyv, &mut p).unwrap();
        assert_eq!(&p[2..], &[0xFF, 0xFF]);
    }

    #[test]
    fn downscale_drops_odd_edges_and_rounds_to_nearest() {
        // 4x2 gray
        let src = [0u8, 4, 8, 12, 4, 8, 12, 16];
        let mut dst = [0u8; 2];
        let g = downscale2x_gray8(&src, 4, 2, &mut dst).unwrap();
        assert_eq!((g.width, g.height), (2, 1));
        assert_eq!(dst, [4, 12]);
        // a 5x3 image loses its last column and row: 2x1 out of it
        let src = [10u8; 15];
        let mut dst = [0u8; 2];
        let g = downscale2x_gray8(&src, 5, 3, &mut dst).unwrap();
        assert_eq!((g.width, g.height), (2, 1));
        assert_eq!(dst, [10, 10]);
        // (1 + 2 + 3 + 4 + 2) / 4 = 3: nearest, not floor
        let src = [1u8, 2, 3, 4];
        let mut dst = [0u8; 1];
        downscale2x_gray8(&src, 2, 2, &mut dst).unwrap();
        assert_eq!(dst, [3]);

        // 2x2 rgb565 of one colour averages to itself
        let c = pack_rgb565(200, 100, 50).to_le_bytes();
        let src: std::vec::Vec<u8> = c.iter().copied().cycle().take(8).collect();
        let mut dst = [0u8; 2];
        downscale2x_rgb565(&src, 2, 2, &mut dst).unwrap();
        assert_eq!(dst, c);
        let mut tiny = [0u8; 1];
        assert_eq!(
            downscale2x_rgb565(&src, 2, 2, &mut tiny),
            Err(Error::BufferTooSmall { needed: 2 })
        );
    }
}