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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! [`PixelSink`] implementations for Monoblack and Monowhite sources.
//!
//! Both formats are 1-bit-per-pixel achromatic bilevel: each source bit
//! expands to a u8 luma of `0` or `255` (Monoblack: bit=1 → 255;
//! Monowhite: bit=0 → 255). Every output is a broadcast of that luma —
//! `with_rgb` / `with_rgba` / `with_rgb_u16` / `with_rgba_u16` replicate
//! Y to R=G=B (alpha forced opaque), `with_luma` copies it,
//! `with_luma_u16` zero-extends it, and `with_hsv` emits H=0, S=0, V=Y
//! (achromatic convention). There is no chroma matrix and no palette, so
//! a resampled path expands the bits to a source-width 0/255 luma plane
//! and resamples that single plane, deriving every attached output from
//! each finalized resampled luma row — identical to the direct path with
//! the resampled value standing in for the per-pixel expanded value.
//!
//! An **area** plan bins the expanded luma through a single-channel
//! [`AreaStream<u8>`](crate::resample::AreaStream); a **filter** plan
//! resamples it through the signed-coefficient single-channel
//! [`FilterStream<u8>`](crate::resample::FilterStream) (the filter twin of
//! the bin). Both feed the **same** emit, so the filter output matches the
//! area output up to the kernel weights. Filtering a bilevel image to
//! continuous grayscale *is* antialiasing it: a hard 0/255 edge resampled
//! with a Triangle/Catmull-Rom/Lanczos window becomes a smooth gray ramp.
//! The expanded luma spans the full `u8` range (0..=255), so no
//! native-depth clamp applies — the stream's `0..=255` clamp *is* the
//! native range.

use super::{
  InsufficientBuffer, MixedSinker, MixedSinkerError, RowIndexOutOfRange, RowShapeMismatch,
  RowSlice, check_dimensions_match, frozen_outputs_check, source_luma_scratch,
};
use crate::{
  PixelSink,
  resample::{AreaStream, FilterStream, ResamplePlan, RowResampler},
  row,
  source::{Monoblack, MonoblackRow, MonoblackSink, Monowhite, MonowhiteRow, MonowhiteSink},
};
use mediaframe::source::HsvFrameMut;

/// Fused resample tail shared by Monoblack and Monowhite, for both an
/// **area** and a **filter** plan. The closure `expand_luma` fills a
/// source-width `u8` scratch with the expanded 0/255 luma of the current
/// 1-bit source row (the same `mono*_to_luma_row` kernel the direct path
/// uses); that single luma plane is resampled — binned through the
/// single-channel [`AreaStream<u8>`] on an area plan, or filtered through
/// the single-channel [`FilterStream<u8>`] (the filter twin of the bin) on
/// a filter plan — and every attached output is derived from each
/// finalized resampled luma row: a copy for luma, a zero-extend for
/// luma_u16, a broadcast to R=G=B for the RGB outputs (alpha forced
/// opaque), and H=0/S=0/V=Y for HSV — mirroring the direct mono kernels
/// exactly. The expanded luma is full-range `u8` (0..=255), so no
/// native-depth clamp applies on either path.
///
/// The two plans differ only in the resampler kind built here; the
/// expand-then-resample staging and per-output emit are identical
/// (factored into [`mono_luma_feed_emit`] behind
/// [`RowResampler`](crate::resample::RowResampler), which both stream kinds
/// implement), so the filter output matches the area output up to the
/// kernel weights and the area path stays bit-identical.
///
/// Atomic preflight: the output set is frozen and stream sequencing
/// checked **before** any scratch allocation or stream feed, so a
/// failed call mutates no caller output and a no-output sink stays a
/// legal no-op.
#[allow(clippy::too_many_arguments)]
fn mono_luma_resample(
  luma_stream: &mut Option<std::boxed::Box<AreaStream<u8>>>,
  luma_filter_stream: &mut Option<std::boxed::Box<FilterStream<u8>>>,
  resample_outputs: &mut Option<super::FrozenOutputs>,
  rgb: &mut Option<&mut [u8]>,
  rgba: &mut Option<&mut [u8]>,
  rgb_u16: &mut Option<&mut [u16]>,
  rgba_u16: &mut Option<&mut [u16]>,
  luma: &mut Option<&mut [u8]>,
  luma_u16: &mut Option<&mut [u16]>,
  hsv: &mut Option<HsvFrameMut<'_>>,
  scratch: &mut std::vec::Vec<u8>,
  w: usize,
  plan: &ResamplePlan,
  idx: usize,
  use_simd: bool,
  expand_luma: impl FnOnce(&mut [u8]),
) -> Result<(), MixedSinkerError> {
  // Single-kernel filter tail — reject a BICUBLIN plan (its chroma windows are
  // read only by the `Yuv420p` per-plane route) before any state change. The
  // mono luma stream is single-kernel, so a bicublin plan would mis-filter.
  plan.ensure_single_kernel_filter()?;
  let is_filter = plan.kind().is_filter();
  let need_any = luma.is_some()
    || luma_u16.is_some()
    || rgb.is_some()
    || rgba.is_some()
    || rgb_u16.is_some()
    || rgba_u16.is_some()
    || hsv.is_some();
  // Sequence-counter row for the shared L1 preflight (the fed stream is the sole
  // per-row stream), or `None` when no output is attached so the preflight
  // short-circuits to a no-op. The plan kind is fixed per sink, so only one of the
  // two streams is ever fed.
  let expected = if need_any {
    Some(if is_filter {
      luma_filter_stream
        .as_ref()
        .map_or(0, |stream| stream.next_y())
    } else {
      luma_stream.as_ref().map_or(0, |stream| stream.next_y())
    })
  } else {
    None
  };
  // Compare-only preflight (NO commit): the output-set freeze commits only AFTER the
  // fallible stream alloc + scratch pregrow below succeed, so a first-row allocation
  // failure leaves `resample_outputs` uncommitted (retryable with a changed output
  // attachment). A no-output sink short-circuits to a no-op.
  if let core::ops::ControlFlow::Break(()) = super::resample_preflight_check_only(
    resample_outputs,
    luma,
    luma_u16,
    rgb,
    rgba,
    rgb_u16,
    rgba_u16,
    &None,
    &None,
    &None,
    &None,
    &None,
    hsv,
    &None,
    expected,
    idx,
  )? {
    return Ok(());
  }

  // Build the missing per-kind stream into a LOCAL and pregrow the source-luma
  // scratch, then insert the stream field and freeze the output set TOGETHER — so a
  // scratch OOM after a successful stream build leaves the field `None` AND
  // `resample_outputs` uncommitted (the #180 commit-together discipline). The
  // expanded luma spans the full `u8` range, so neither stream needs a native-depth
  // clamp. Stage + feed + emit is shared via [`mono_luma_feed_emit`], which re-runs
  // the (now no-op) source-luma grow before the feed.
  if is_filter {
    let (fh, fv) = (
      plan
        .filter_h()
        .expect("filter plan carries horizontal windows"),
      plan
        .filter_v()
        .expect("filter plan carries vertical windows"),
    );
    let new_stream = if luma_filter_stream.is_none() {
      let stream = FilterStream::new(fh, fv, plan.src_w(), plan.src_h(), 1)?;
      Some(crate::resample::try_box(stream).map_err(|_| {
        MixedSinkerError::Resample(crate::resample::ResampleError::AllocationFailed(
          crate::resample::PlanGeometry::new(
            plan.src_w(),
            plan.src_h(),
            plan.out_w(),
            plan.out_h(),
          ),
        ))
      })?)
    } else {
      None
    };
    source_luma_scratch(scratch, w, plan)?;
    if let Some(s) = new_stream {
      *luma_filter_stream = Some(s);
    }
    frozen_outputs_check(
      resample_outputs,
      luma,
      luma_u16,
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      &None,
      &None,
      &None,
      &None,
      &None,
      hsv,
      &None,
      idx,
    )?;
    let stream = luma_filter_stream.as_mut().expect("created above");
    mono_luma_feed_emit(
      stream,
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      luma,
      luma_u16,
      hsv,
      scratch,
      w,
      plan,
      idx,
      use_simd,
      expand_luma,
    )
  } else {
    let new_stream = if luma_stream.is_none() {
      let stream = AreaStream::new(plan.h(), plan.v(), plan.src_w(), plan.src_h(), 1)?;
      Some(crate::resample::try_box(stream).map_err(|_| {
        MixedSinkerError::Resample(crate::resample::ResampleError::AllocationFailed(
          crate::resample::PlanGeometry::new(
            plan.src_w(),
            plan.src_h(),
            plan.out_w(),
            plan.out_h(),
          ),
        ))
      })?)
    } else {
      None
    };
    source_luma_scratch(scratch, w, plan)?;
    if let Some(s) = new_stream {
      *luma_stream = Some(s);
    }
    frozen_outputs_check(
      resample_outputs,
      luma,
      luma_u16,
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      &None,
      &None,
      &None,
      &None,
      &None,
      hsv,
      &None,
      idx,
    )?;
    let stream = luma_stream.as_mut().expect("created above");
    mono_luma_feed_emit(
      stream,
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      luma,
      luma_u16,
      hsv,
      scratch,
      w,
      plan,
      idx,
      use_simd,
      expand_luma,
    )
  }
}

/// Shared stage-then-feed tail for the mono resample, used by both the area
/// and filter arms of [`mono_luma_resample`]. The two paths differ only in
/// the resampler kind (`stream`), so the expand-then-resample staging and
/// the per-output emit are identical and live here behind the
/// [`RowResampler`](crate::resample::RowResampler) trait — keeping the emit
/// byte-identical between the arms is what makes the filter output match the
/// area output up to the kernel weights, and the area path bit-identical to
/// before this routing.
///
/// Expands the 1-bit source row to source-width 0/255 luma in the shared
/// scratch (fallible growth runs before the feed, keeping the call atomic),
/// then resamples it through the single-channel `stream`, deriving every
/// attached output from each finalized resampled luma row.
#[allow(clippy::too_many_arguments)]
fn mono_luma_feed_emit<S: RowResampler<u8>>(
  stream: &mut S,
  rgb: &mut Option<&mut [u8]>,
  rgba: &mut Option<&mut [u8]>,
  rgb_u16: &mut Option<&mut [u16]>,
  rgba_u16: &mut Option<&mut [u16]>,
  luma: &mut Option<&mut [u8]>,
  luma_u16: &mut Option<&mut [u16]>,
  hsv: &mut Option<HsvFrameMut<'_>>,
  scratch: &mut std::vec::Vec<u8>,
  w: usize,
  plan: &ResamplePlan,
  idx: usize,
  use_simd: bool,
  expand_luma: impl FnOnce(&mut [u8]),
) -> Result<(), MixedSinkerError> {
  let ow = plan.out_w();
  let luma_row = source_luma_scratch(scratch, w, plan)?;
  expand_luma(luma_row);

  stream.feed_row(idx, luma_row, use_simd, |oy, out_row| {
    if let Some(buf) = luma.as_deref_mut() {
      buf[oy * ow..(oy + 1) * ow].copy_from_slice(out_row);
    }
    if let Some(buf) = luma_u16.as_deref_mut() {
      for (dst, &y) in buf[oy * ow..(oy + 1) * ow].iter_mut().zip(out_row) {
        *dst = y as u16;
      }
    }
    if let Some(buf) = rgb.as_deref_mut() {
      for (px, &y) in buf[oy * 3 * ow..(oy + 1) * 3 * ow]
        .as_chunks_mut::<3>()
        .0
        .iter_mut()
        .zip(out_row)
      {
        px[0] = y;
        px[1] = y;
        px[2] = y;
      }
    }
    if let Some(buf) = rgba.as_deref_mut() {
      for (px, &y) in buf[oy * 4 * ow..(oy + 1) * 4 * ow]
        .as_chunks_mut::<4>()
        .0
        .iter_mut()
        .zip(out_row)
      {
        px[0] = y;
        px[1] = y;
        px[2] = y;
        px[3] = 0xFF;
      }
    }
    if let Some(buf) = rgb_u16.as_deref_mut() {
      for (px, &y) in buf[oy * 3 * ow..(oy + 1) * 3 * ow]
        .as_chunks_mut::<3>()
        .0
        .iter_mut()
        .zip(out_row)
      {
        let y16 = y as u16;
        px[0] = y16;
        px[1] = y16;
        px[2] = y16;
      }
    }
    if let Some(buf) = rgba_u16.as_deref_mut() {
      for (px, &y) in buf[oy * 4 * ow..(oy + 1) * 4 * ow]
        .as_chunks_mut::<4>()
        .0
        .iter_mut()
        .zip(out_row)
      {
        let y16 = y as u16;
        px[0] = y16;
        px[1] = y16;
        px[2] = y16;
        px[3] = 0x00FF;
      }
    }
    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      let span = oy * ow..(oy + 1) * ow;
      v[span.clone()].copy_from_slice(out_row);
      for px in &mut h[span.clone()] {
        *px = 0;
      }
      for px in &mut s[span] {
        *px = 0;
      }
    }
  })?;

  Ok(())
}

// ---- Monoblack impl ---------------------------------------------------------

impl<'a, R> MixedSinker<'a, Monoblack, R> {
  /// Attaches a packed **`u8`** RGBA output buffer.
  ///
  /// Length is measured in `u8` **bytes**: minimum `width * height * 4`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba(mut self, buf: &'a mut [u8]) -> Result<Self, MixedSinkerError> {
    self.set_rgba(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgba`](Self::with_rgba).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba(&mut self, buf: &'a mut [u8]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaBuffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGB output buffer.
  ///
  /// Length is measured in `u16` **elements** (not bytes): minimum
  /// `width * height * 3`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgb_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgb_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgb_u16`](Self::with_rgb_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgb_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(3)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgb_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGBA output buffer.
  ///
  /// Length is measured in `u16` **elements** (not bytes): minimum
  /// `width * height * 4`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgba_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgba_u16`](Self::with_rgba_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a planar **`u16`** luma output buffer.
  ///
  /// Luma is derived from RGB via BT.709 weights (by default).
  /// Length: minimum `width * height`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_luma_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_luma_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_luma_u16`](Self::with_luma_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_luma_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_pixels()?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientLumaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.luma_u16 = Some(buf);
    Ok(self)
  }
}

impl<R> MonoblackSink for MixedSinker<'_, Monoblack, R> {}

impl<R> PixelSink for MixedSinker<'_, Monoblack, R> {
  type Input<'i> = MonoblackRow<'i>;
  type Error = MixedSinkerError;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn kernel_matrix(&self) -> crate::KernelMatrix {
    self.kernel_matrix
  }
  fn begin_frame(&mut self, width: u32, height: u32) -> Result<(), Self::Error> {
    check_dimensions_match(self.width, self.height, width, height)?;
    if let Some(stream) = self.luma_stream.as_mut() {
      stream.reset();
    }
    if let Some(stream) = self.luma_filter_stream.as_mut() {
      stream.reset();
    }
    self.resample_outputs = None;
    Ok(())
  }

  fn process(&mut self, row: Self::Input<'_>) -> Result<(), Self::Error> {
    let w = self.width;
    let h = self.height;
    let idx = row.row();
    let use_simd = self.simd;

    let min_bytes = w.div_ceil(8);
    if row.data().len() < min_bytes {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::Y,
        idx,
        min_bytes,
        row.data().len(),
      )));
    }

    if idx >= h {
      return Err(MixedSinkerError::RowIndexOutOfRange(
        RowIndexOutOfRange::new(idx, h),
      ));
    }

    let Self {
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      luma,
      luma_u16,
      hsv,
      plan,
      luma_stream,
      luma_filter_stream,
      resample_outputs,
      rgb_scratch,
      ..
    } = self;

    // Non-identity plan: expand the 1-bit source row to source-width
    // 0/255 luma (the same Monoblack→luma kernel the direct path uses),
    // resample that luma plane (area-bin or filter, per the plan kind), and
    // derive every output from each finalized resampled luma row. The
    // resample is of the EXPANDED luma — expand then resample, the resample
    // oracle for an achromatic source; a filter window over the 0/255 edge
    // is the desired antialiasing (a smooth gray ramp).
    if let Some(plan) = plan.as_ref() {
      let data = row.data();
      return mono_luma_resample(
        luma_stream,
        luma_filter_stream,
        resample_outputs,
        rgb,
        rgba,
        rgb_u16,
        rgba_u16,
        luma,
        luma_u16,
        hsv,
        rgb_scratch,
        w,
        plan,
        idx,
        use_simd,
        |scratch| row::monoblack_to_luma_row(data, scratch, w, use_simd),
      );
    }

    let one_plane_start = idx * w;
    let one_plane_end = one_plane_start + w;

    if let Some(buf) = rgb.as_deref_mut() {
      row::monoblack_to_rgb_or_rgba_row::<false>(
        row.data(),
        &mut buf[one_plane_start * 3..one_plane_end * 3],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba.as_deref_mut() {
      row::monoblack_to_rgb_or_rgba_row::<true>(
        row.data(),
        &mut buf[one_plane_start * 4..one_plane_end * 4],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgb_u16.as_deref_mut() {
      row::monoblack_to_rgb_u16_or_rgba_u16_row::<false>(
        row.data(),
        &mut buf[one_plane_start * 3..one_plane_end * 3],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba_u16.as_deref_mut() {
      row::monoblack_to_rgb_u16_or_rgba_u16_row::<true>(
        row.data(),
        &mut buf[one_plane_start * 4..one_plane_end * 4],
        w,
        use_simd,
      );
    }

    if let Some(buf) = luma.as_deref_mut() {
      row::monoblack_to_luma_row(
        row.data(),
        &mut buf[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(buf) = luma_u16.as_deref_mut() {
      row::monoblack_to_luma_u16_row(
        row.data(),
        &mut buf[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      row::monoblack_to_hsv_row(
        row.data(),
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    Ok(())
  }
}

// ---- Monowhite impl ---------------------------------------------------------

impl<'a, R> MixedSinker<'a, Monowhite, R> {
  /// Attaches a packed **`u8`** RGBA output buffer.
  ///
  /// Length is measured in `u8` **bytes**: minimum `width * height * 4`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba(mut self, buf: &'a mut [u8]) -> Result<Self, MixedSinkerError> {
    self.set_rgba(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgba`](Self::with_rgba).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba(&mut self, buf: &'a mut [u8]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaBuffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGB output buffer.
  ///
  /// Length is measured in `u16` **elements** (not bytes): minimum
  /// `width * height * 3`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgb_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgb_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgb_u16`](Self::with_rgb_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgb_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(3)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgb_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGBA output buffer.
  ///
  /// Length is measured in `u16` **elements** (not bytes): minimum
  /// `width * height * 4`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgba_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_rgba_u16`](Self::with_rgba_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a planar **`u16`** luma output buffer.
  ///
  /// Luma is derived from RGB via BT.709 weights (by default).
  /// Length: minimum `width * height`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_luma_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_luma_u16(buf)?;
    Ok(self)
  }

  /// In-place variant of [`with_luma_u16`](Self::with_luma_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_luma_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_pixels()?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientLumaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.luma_u16 = Some(buf);
    Ok(self)
  }
}

impl<R> MonowhiteSink for MixedSinker<'_, Monowhite, R> {}

impl<R> PixelSink for MixedSinker<'_, Monowhite, R> {
  type Input<'i> = MonowhiteRow<'i>;
  type Error = MixedSinkerError;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn kernel_matrix(&self) -> crate::KernelMatrix {
    self.kernel_matrix
  }
  fn begin_frame(&mut self, width: u32, height: u32) -> Result<(), Self::Error> {
    check_dimensions_match(self.width, self.height, width, height)?;
    if let Some(stream) = self.luma_stream.as_mut() {
      stream.reset();
    }
    if let Some(stream) = self.luma_filter_stream.as_mut() {
      stream.reset();
    }
    self.resample_outputs = None;
    Ok(())
  }

  fn process(&mut self, row: Self::Input<'_>) -> Result<(), Self::Error> {
    let w = self.width;
    let h = self.height;
    let idx = row.row();
    let use_simd = self.simd;

    let min_bytes = w.div_ceil(8);
    if row.data().len() < min_bytes {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::Y,
        idx,
        min_bytes,
        row.data().len(),
      )));
    }

    if idx >= h {
      return Err(MixedSinkerError::RowIndexOutOfRange(
        RowIndexOutOfRange::new(idx, h),
      ));
    }

    let Self {
      rgb,
      rgba,
      rgb_u16,
      rgba_u16,
      luma,
      luma_u16,
      hsv,
      plan,
      luma_stream,
      luma_filter_stream,
      resample_outputs,
      rgb_scratch,
      ..
    } = self;

    // Non-identity plan: same expand-then-resample oracle as Monoblack,
    // with Monowhite's inverted polarity baked into the luma kernel.
    if let Some(plan) = plan.as_ref() {
      let data = row.data();
      return mono_luma_resample(
        luma_stream,
        luma_filter_stream,
        resample_outputs,
        rgb,
        rgba,
        rgb_u16,
        rgba_u16,
        luma,
        luma_u16,
        hsv,
        rgb_scratch,
        w,
        plan,
        idx,
        use_simd,
        |scratch| row::monowhite_to_luma_row(data, scratch, w, use_simd),
      );
    }

    let one_plane_start = idx * w;
    let one_plane_end = one_plane_start + w;

    if let Some(buf) = rgb.as_deref_mut() {
      row::monowhite_to_rgb_or_rgba_row::<false>(
        row.data(),
        &mut buf[one_plane_start * 3..one_plane_end * 3],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba.as_deref_mut() {
      row::monowhite_to_rgb_or_rgba_row::<true>(
        row.data(),
        &mut buf[one_plane_start * 4..one_plane_end * 4],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgb_u16.as_deref_mut() {
      row::monowhite_to_rgb_u16_or_rgba_u16_row::<false>(
        row.data(),
        &mut buf[one_plane_start * 3..one_plane_end * 3],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba_u16.as_deref_mut() {
      row::monowhite_to_rgb_u16_or_rgba_u16_row::<true>(
        row.data(),
        &mut buf[one_plane_start * 4..one_plane_end * 4],
        w,
        use_simd,
      );
    }

    if let Some(buf) = luma.as_deref_mut() {
      row::monowhite_to_luma_row(
        row.data(),
        &mut buf[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(buf) = luma_u16.as_deref_mut() {
      row::monowhite_to_luma_u16_row(
        row.data(),
        &mut buf[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      row::monowhite_to_hsv_row(
        row.data(),
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    Ok(())
  }
}