Skip to main content

zenpixels_convert/
compact.rs

1//! Spec-aware content analysis and bit-exact lossless format compaction.
2//!
3//! Answers: *"Which parts of this buffer's declared [`PixelFormat`] are actually
4//! required by its pixel values?"* — non-opaque alpha, chroma (`R != G` or `G != B`),
5//! and 16-bit precision beyond byte-replicated 8-bit (`(v >> 8) != (v & 0xFF)` on
6//! full-range `U16`) — and optionally compacts the pixel buffer either into a fresh
7//! [`PixelBuf`] ([`compact_to_buf`]) or **in place** with zero allocation
8//! ([`compact_in_place`]).
9//!
10//! Every reduction this module performs is **bit-exact invertible**:
11//! - Dropping an all-max alpha lane (or undefined `RGBX`/`BGRX` padding).
12//! - Collapsing `R == G == B` to `Gray`/`GrayAlpha` (respecting ICC class
13//!   authority: an RGB-class ICC requires a qualified GRAY-class replacement).
14//! - Narrowing bit-replicated full-range `U16` (`v * 257`) to `U8` (narrow-range
15//!   `U16` is kept at 16-bit because its anchors scale by 256, not 257).
16
17use alloc::sync::Arc;
18use how_far::{Complete, PhaseSpec, Pulse, Stages, Total};
19use whereat::At;
20use zenpixels::{
21    AlphaMode, ChannelOrder, ColorOrigin, ColorSpace, InPlaceTransformDecision,
22    InPlaceTransformOutput, PixelBuf, PixelFormat, PixelView, Primaries, SampleClaims,
23    SampleLayout, SampleType, SignalRange, Transfer,
24};
25
26use crate::error::{ConvertError, err_at};
27use crate::icc_profiles::{SynthesizedIcc, synthesize_gray_icc_for_cicp};
28use crate::pulse::{check_pulse, is_stop_at, live_pulse, step_pulse};
29use crate::scan::{self, FusedRequest};
30
31/// Which channels and precision of a buffer's declared [`PixelFormat`] are required
32/// to represent its current pixel values without loss.
33///
34/// Each field is `Option<bool>`:
35/// - `Some(false)` — measured redundant (safe to drop/narrow without loss).
36/// - `Some(true)` — measured required (keep).
37/// - `None` — predicate did not apply / was not assessed (keep conservatively).
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct CompactionReport {
41    /// `Some(true)` if any alpha sample is below channel-max; `Some(false)` if
42    /// all-max, `Opaque`, `Undefined` padding, or no alpha channel.
43    requires_alpha: Option<bool>,
44    /// `Some(true)` if any pixel has `R != G` or `G != B`; `Some(false)` if all
45    /// neutral or already grayscale.
46    requires_chroma: Option<bool>,
47    /// `Some(true)` if any active full-range `U16` sample is not byte-replicated
48    /// (`(v >> 8) != (v & 0xFF)`); `Some(false)` if bit-replicated (`v * 257`) or
49    /// already `U8`. Narrow-range `U16` reports `None` and stays 16-bit.
50    requires_u16_precision: Option<bool>,
51}
52
53impl CompactionReport {
54    /// Whether the measured image requires its alpha channel.
55    #[inline]
56    #[must_use]
57    pub const fn requires_alpha(&self) -> Option<bool> {
58        self.requires_alpha
59    }
60
61    /// Whether the measured image requires chroma.
62    #[inline]
63    #[must_use]
64    pub const fn requires_chroma(&self) -> Option<bool> {
65        self.requires_chroma
66    }
67
68    /// Whether the measured image requires 16-bit precision.
69    #[inline]
70    #[must_use]
71    pub const fn requires_u16_precision(&self) -> Option<bool> {
72        self.requires_u16_precision
73    }
74
75    /// Whether at least one predicate ran or answered structurally.
76    #[inline]
77    #[must_use]
78    pub const fn any_analyzed(&self) -> bool {
79        self.requires_alpha.is_some()
80            || self.requires_chroma.is_some()
81            || self.requires_u16_precision.is_some()
82    }
83
84    /// Compute the narrowest candidate [`PixelFormat`] justified by this report (metadata only;
85    /// does not inspect or transform pixels). Pass the format of the image used to produce
86    /// this report. The candidate describes that image only.
87    ///
88    /// Order of reduction:
89    /// 1. Full-range `U16 -> U8` when `requires_u16_precision == Some(false)`.
90    /// 2. Alpha/padding drop (`RGBA/BGRA/RGBX/BGRX -> RGB`, `GrayAlpha -> Gray`)
91    ///    when `requires_alpha == Some(false)`.
92    /// 3. Chroma drop (`RGB/BGR -> Gray`, `RGBA/BGRA/RGBX/BGRX -> GrayAlpha/Gray`)
93    ///    when `requires_chroma == Some(false)` (only on structured D65 `Rgb` / `Gray`;
94    ///    `ColorSpace::Icc` chroma collapse is gated separately by ICC class swapping).
95    #[must_use]
96    pub fn candidate_format(&self, src: &PixelFormat) -> PixelFormat {
97        if !src.layout().packing().is_full() {
98            return src.clone();
99        }
100        let mut sample = src.layout().sample();
101        let mut order = src.layout().order();
102        let mut color = src.color().clone();
103
104        // 1. Full-range U16 -> U8 narrowing.
105        if matches!(self.requires_u16_precision, Some(false))
106            && sample == SampleType::U16
107            && color.range().unwrap_or(SignalRange::Full) == SignalRange::Full
108        {
109            sample = SampleType::U8;
110        }
111
112        // 2. Alpha / padding drop.
113        if matches!(self.requires_alpha, Some(false)) {
114            let next_order = match order {
115                ChannelOrder::Rgba
116                | ChannelOrder::Bgra
117                | ChannelOrder::Rgbx
118                | ChannelOrder::Bgrx => ChannelOrder::Rgb,
119                ChannelOrder::GrayAlpha => ChannelOrder::Gray,
120                other => other,
121            };
122            if next_order != order {
123                order = next_order;
124                color = color.with_alpha(AlphaMode::None);
125            }
126        }
127
128        // 3. Chroma drop (for structured D65 ColorSpace::Rgb / RgbCustom; ColorSpace::Icc requires
129        // explicit swap, and non-D65 / Unknown RGB primaries cannot collapse to D65 Gray without shifting white point).
130        let d65_rgb_parts = match &color {
131            ColorSpace::Rgb {
132                primaries,
133                transfer,
134                range,
135                alpha,
136                diffuse_white,
137            } if primaries.white_point() == Some(Primaries::WHITE_D65) => {
138                Some((*transfer, *range, *alpha, *diffuse_white))
139            }
140            ColorSpace::RgbCustom {
141                primaries,
142                transfer,
143                range,
144                alpha,
145                diffuse_white,
146            } if is_d65_white(primaries.white_point().xy()) => {
147                Some((*transfer, *range, *alpha, *diffuse_white))
148            }
149            _ => None,
150        };
151        if matches!(self.requires_chroma, Some(false))
152            && let Some((transfer, range, alpha, diffuse_white)) = d65_rgb_parts
153        {
154            let (next_order, next_alpha) = match order {
155                ChannelOrder::Rgb | ChannelOrder::Bgr => (ChannelOrder::Gray, AlphaMode::None),
156                ChannelOrder::Rgbx | ChannelOrder::Bgrx => (ChannelOrder::Gray, AlphaMode::None),
157                ChannelOrder::Rgba | ChannelOrder::Bgra => (ChannelOrder::GrayAlpha, alpha),
158                other => (other, alpha),
159            };
160            if next_order != order {
161                order = next_order;
162                color = ColorSpace::Gray {
163                    transfer,
164                    range,
165                    alpha: next_alpha,
166                    diffuse_white,
167                };
168            }
169        }
170
171        PixelFormat::new(SampleLayout::new(sample, order), color).unwrap_or_else(|_| src.clone())
172    }
173}
174
175/// How [`compact_in_place`] handles redundant alpha or padding lanes.
176///
177/// Depth (`U16 → U8`) and chroma (`RGB → Gray`) compaction still run in both modes whenever
178/// justified by the scan.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180#[non_exhaustive]
181pub enum AlphaCompaction {
182    /// Upgrade provably opaque `Straight`/`Premultiplied` alpha to [`AlphaMode::Opaque`]
183    /// in metadata without restructuring alpha/padding lanes (0 byte movement when depth and
184    /// chroma are unchanged).
185    RetagOpaque,
186    /// Physically drop redundant alpha or undefined padding lanes in place
187    /// (`RGBA`/`BGRA`/`RGBX`/`BGRX` → `RGB`, `GrayAlpha` → `Gray`).
188    DropUnusedLanes,
189}
190
191enum GraySignalPlan {
192    Carry,
193    Swap { gray_icc: Option<Arc<[u8]>> },
194    Suppress,
195}
196
197fn is_d65_white(wp: (f32, f32)) -> bool {
198    const D65: (f32, f32) = Primaries::WHITE_D65;
199    (wp.0 - D65.0).abs() <= 1e-4 && (wp.1 - D65.1).abs() <= 1e-4
200}
201
202fn plan_chroma_collapse_for_icc(icc: &[u8]) -> GraySignalPlan {
203    let (cicp, wp) = if let Some(id) = zenpixels::icc::IccIdentification::from_icc(icc)
204        .filter(|id| id.valid_use() == zenpixels::icc::IdentificationUse::MatrixTrcSubstitution)
205    {
206        let Some(c) = id.to_cicp() else {
207            return GraySignalPlan::Suppress;
208        };
209        (c, id.primaries().white_point())
210    } else if let Some(tag) = zenpixels::CicpTag::from_icc(icc)
211        .filter(|t| t.cicp().matrix_coefficients == 0 && t.cicp().full_range)
212    {
213        let wp = tag
214            .custom_primaries()
215            .map(|cp| cp.white_point().xy())
216            .or_else(|| tag.primaries().and_then(Primaries::white_point));
217        (tag.cicp(), wp)
218    } else {
219        return GraySignalPlan::Suppress;
220    };
221    if !wp.is_some_and(is_d65_white) {
222        return GraySignalPlan::Suppress;
223    }
224    match synthesize_gray_icc_for_cicp(cicp) {
225        SynthesizedIcc::Profile(bytes) => GraySignalPlan::Swap {
226            gray_icc: Some(Arc::from(bytes.as_ref())),
227        },
228        SynthesizedIcc::NotNeeded => GraySignalPlan::Swap { gray_icc: None },
229        _ => GraySignalPlan::Suppress,
230    }
231}
232
233fn plan_chroma_collapse(spec: &PixelFormat) -> GraySignalPlan {
234    match &spec.color() {
235        ColorSpace::Icc {
236            profile,
237            color_channels: 3,
238            ..
239        } => plan_chroma_collapse_for_icc(profile),
240        ColorSpace::Rgb { primaries, .. } => {
241            if primaries.white_point() == Some(Primaries::WHITE_D65) {
242                GraySignalPlan::Carry
243            } else {
244                GraySignalPlan::Suppress
245            }
246        }
247        ColorSpace::RgbCustom { primaries, .. } => {
248            if is_d65_white(primaries.white_point().xy()) {
249                GraySignalPlan::Carry
250            } else {
251                GraySignalPlan::Suppress
252            }
253        }
254        ColorSpace::Gray { .. } => GraySignalPlan::Carry,
255        _ => GraySignalPlan::Suppress,
256    }
257}
258
259fn apply_icc_chroma_collapse(
260    src: &PixelFormat,
261    report: &CompactionReport,
262    plan: &GraySignalPlan,
263) -> PixelFormat {
264    let base = report.candidate_format(src);
265    if !matches!(report.requires_chroma, Some(false)) {
266        return base;
267    }
268    let ColorSpace::Icc {
269        color_channels: 3,
270        alpha,
271        intent,
272        ..
273    } = base.color()
274    else {
275        return base;
276    };
277    let GraySignalPlan::Swap { gray_icc, .. } = plan else {
278        return base;
279    };
280    let (next_order, next_alpha) = match base.layout().order() {
281        ChannelOrder::Rgb | ChannelOrder::Bgr | ChannelOrder::Rgbx | ChannelOrder::Bgrx => {
282            (ChannelOrder::Gray, AlphaMode::None)
283        }
284        ChannelOrder::Rgba | ChannelOrder::Bgra => (ChannelOrder::GrayAlpha, *alpha),
285        other => (other, *alpha),
286    };
287    let next_color = match gray_icc {
288        Some(bytes) => ColorSpace::Icc {
289            profile: Arc::clone(bytes),
290            color_channels: 1,
291            alpha: next_alpha,
292            intent: *intent,
293        },
294        None => ColorSpace::Gray {
295            transfer: Transfer::Srgb,
296            range: SignalRange::Full,
297            alpha: next_alpha,
298            diffuse_white: None,
299        },
300    };
301    PixelFormat::new(
302        SampleLayout::new(base.layout().sample(), next_order),
303        next_color,
304    )
305    .unwrap_or(base)
306}
307
308impl CompactionReport {
309    /// Measure which dimensions of `view`'s spec are actually required by its pixel values.
310    #[must_use]
311    pub fn measure(view: &PixelView<'_>) -> Self {
312        Self::measure_with_pulse(view, None).expect("measure without pulse is infallible")
313    }
314
315    /// Measure which dimensions of `view`'s spec are actually required by its pixel values,
316    /// observing optional cooperative cancellation and row progress via `pulse` (pass `None`
317    /// when not needed).
318    pub fn measure_with_pulse(
319        view: &PixelView<'_>,
320        pulse: Option<&dyn Pulse>,
321    ) -> Result<Self, At<ConvertError>> {
322        let pulse = live_pulse(pulse);
323        check_pulse(pulse)?;
324        let spec = view.format();
325        if !spec.layout().packing().is_full() {
326            return Ok(Self::default());
327        }
328        let order = spec.layout().order();
329        let sample = spec.layout().sample();
330
331        let alpha_structural: Option<Option<bool>> = if order.has_padding_slot() {
332            Some(Some(false))
333        } else if order.has_alpha_slot() {
334            match spec.color().alpha() {
335                AlphaMode::Undefined | AlphaMode::Opaque => Some(Some(false)),
336                _ => None,
337            }
338        } else {
339            None
340        };
341        let scan_alpha = alpha_structural.is_none();
342
343        // Fused U16 single-pass scan (opacity + chroma + bit-replication, ignoring RGBX padding).
344        if sample == SampleType::U16
345            && matches!(
346                order,
347                ChannelOrder::Rgba
348                    | ChannelOrder::Bgra
349                    | ChannelOrder::Rgbx
350                    | ChannelOrder::Bgrx
351                    | ChannelOrder::Rgb
352                    | ChannelOrder::Bgr
353                    | ChannelOrder::GrayAlpha
354                    | ChannelOrder::Gray
355            )
356        {
357            let has_alpha = order.has_alpha_slot();
358            let has_chroma = order.is_rgb_family();
359            let padding = order.has_padding_slot();
360            let is_narrow = spec.color().range() == Some(SignalRange::Narrow);
361            let ch = order.channels();
362            let mut flags = [false, false, is_narrow];
363            for y in 0..view.height() {
364                let row = view.row(y);
365                if let Ok(s16) = bytemuck::try_cast_slice::<u8, u16>(row) {
366                    flags = scan::fused_u16(
367                        s16,
368                        ch,
369                        has_alpha && scan_alpha,
370                        has_chroma,
371                        padding,
372                        flags,
373                    );
374                } else {
375                    for px in row.chunks_exact(ch * 2) {
376                        if has_alpha && scan_alpha && !flags[0] {
377                            let a = u16::from_ne_bytes([px[(ch - 1) * 2], px[(ch - 1) * 2 + 1]]);
378                            if a != u16::MAX {
379                                flags[0] = true;
380                            }
381                        }
382                        if has_chroma && !flags[1] {
383                            let s0 = u16::from_ne_bytes([px[0], px[1]]);
384                            let s1 = u16::from_ne_bytes([px[2], px[3]]);
385                            let s2 = u16::from_ne_bytes([px[4], px[5]]);
386                            if s0 != s1 || s1 != s2 {
387                                flags[1] = true;
388                            }
389                        }
390                        if !flags[2] {
391                            let data_ch = if padding { ch - 1 } else { ch };
392                            for c in 0..data_ch {
393                                let v = u16::from_ne_bytes([px[c * 2], px[c * 2 + 1]]);
394                                if (v >> 8) != (v & 0xFF) {
395                                    flags[2] = true;
396                                    break;
397                                }
398                            }
399                        }
400                    }
401                }
402                step_pulse(pulse, 1)?;
403                if (!has_alpha || !scan_alpha || flags[0]) && (!has_chroma || flags[1]) && flags[2]
404                {
405                    break;
406                }
407            }
408            return Ok(CompactionReport {
409                requires_alpha: Some(flags[0]),
410                requires_chroma: Some(flags[1]),
411                requires_u16_precision: if is_narrow { None } else { Some(flags[2]) },
412            });
413        }
414
415        let (mut requires_alpha, requires_chroma) = match (order, sample) {
416            (
417                ChannelOrder::Rgba | ChannelOrder::Bgra | ChannelOrder::Rgbx | ChannelOrder::Bgrx,
418                SampleType::U8,
419            ) => {
420                let fused = fused_rgba8_over_rows(
421                    view,
422                    FusedRequest {
423                        check_opaque: scan_alpha,
424                        check_grayscale: true,
425                    },
426                    pulse,
427                )?;
428                (Some(!fused.is_opaque), Some(!fused.is_grayscale))
429            }
430            (ChannelOrder::Rgb | ChannelOrder::Bgr, SampleType::U8) => {
431                let gray = rows_all_u8(view, scan::is_grayscale_rgb8, pulse)?;
432                (Some(false), Some(!gray))
433            }
434            (ChannelOrder::GrayAlpha, SampleType::U8) => {
435                let op = if !scan_alpha {
436                    true
437                } else {
438                    rows_all_u8(view, scan::is_opaque_ga8, pulse)?
439                };
440                (Some(!op), Some(false))
441            }
442            (ChannelOrder::Gray, _) => (Some(false), Some(false)),
443            (
444                ChannelOrder::Rgba | ChannelOrder::Bgra | ChannelOrder::Rgbx | ChannelOrder::Bgrx,
445                SampleType::F32,
446            ) => {
447                let op = if !scan_alpha {
448                    true
449                } else {
450                    rows_all_f32(view, scan::is_opaque_rgba_f32, pulse)?
451                };
452                let gr = rows_all_f32(view, scan::is_grayscale_rgba_f32, pulse)?;
453                (Some(!op), Some(!gr))
454            }
455            (ChannelOrder::Rgb | ChannelOrder::Bgr, SampleType::F32) => (
456                Some(false),
457                Some(!rows_all_f32(view, scan::is_grayscale_rgb_f32, pulse)?),
458            ),
459            (ChannelOrder::GrayAlpha, SampleType::F32) => {
460                let op = if !scan_alpha {
461                    true
462                } else {
463                    rows_all_f32(view, scan::is_opaque_ga_f32, pulse)?
464                };
465                (Some(!op), Some(false))
466            }
467            _ => (None, None),
468        };
469
470        if let Some(structural) = alpha_structural
471            && requires_alpha.is_some()
472        {
473            requires_alpha = structural;
474        }
475
476        let requires_u16_precision = match sample {
477            SampleType::U8 => Some(false),
478            SampleType::U16 => Some(!rows_all_u16(
479                view,
480                scan::bit_replication_lossless_u16,
481                pulse,
482            )?),
483            _ => None,
484        };
485
486        Ok(Self {
487            requires_alpha,
488            requires_chroma,
489            requires_u16_precision,
490        })
491    }
492}
493
494/// Analyze `view` and compact into a newly allocated [`PixelBuf`] if a narrower bit-exact
495/// representation exists (`Ok(None)` if already minimal), preserving allocation errors.
496#[doc(alias = "load_bearing")]
497#[doc(alias = "shrink")]
498pub fn compact_to_buf(view: &PixelView<'_>) -> Result<Option<PixelBuf>, At<ConvertError>> {
499    compact_to_buf_with_pulse(view, None)
500}
501
502/// Analyze `view` and compact into a newly allocated [`PixelBuf`] with optional cooperative
503/// cancellation and progress via `pulse` (pass `None` when not needed).
504pub fn compact_to_buf_with_pulse(
505    view: &PixelView<'_>,
506    pulse: Option<&dyn Pulse>,
507) -> Result<Option<PixelBuf>, At<ConvertError>> {
508    let pulse = live_pulse(pulse);
509    check_pulse(pulse)?;
510    let src = view.format().clone();
511    let plan = plan_chroma_collapse(&src);
512    if let Some(p) = pulse {
513        let rows = u64::from(view.height());
514        return Stages::new(
515            p,
516            &[
517                PhaseSpec::new("compact-measure", 1, Total::Exact(rows)).units("rows"),
518                PhaseSpec::new("compact-copy", 1, Total::Exact(rows)).units("rows"),
519            ],
520        )
521        .complete_with_classified(is_stop_at, |stages| {
522            let mut report = stages.run_classified(is_stop_at, |st| {
523                CompactionReport::measure_with_pulse(view, Some(st))
524            })?;
525            if matches!(plan, GraySignalPlan::Suppress) {
526                report.requires_chroma = None;
527            }
528            let target = apply_icc_chroma_collapse(&src, &report, &plan);
529            if target == src {
530                return Ok(None);
531            }
532            stages.run_classified(is_stop_at, |st| {
533                compact_copy_to_buf(view, &src, &target, Some(st))
534            })
535        });
536    }
537    let mut report = CompactionReport::measure(view);
538    if matches!(plan, GraySignalPlan::Suppress) {
539        report.requires_chroma = None;
540    }
541    let target = apply_icc_chroma_collapse(&src, &report, &plan);
542    if target == src {
543        return Ok(None);
544    }
545    compact_copy_to_buf(view, &src, &target, None)
546}
547
548fn compact_copy_to_buf(
549    view: &PixelView<'_>,
550    src: &PixelFormat,
551    target: &PixelFormat,
552    pulse: Option<&dyn Pulse>,
553) -> Result<Option<PixelBuf>, At<ConvertError>> {
554    check_pulse(pulse)?;
555    let mut out = PixelBuf::new(view.width(), view.height(), target.clone())
556        .map_err(|e| err_at((*e.error()).into()))?;
557    if !transform_into(view, src, target, &mut out, pulse)? {
558        return Ok(None);
559    }
560    let out_origin = view.origin().cloned().unwrap_or_else(ColorOrigin::assumed);
561    Ok(Some(
562        out.with_origin(out_origin)
563            .with_hdr(view.hdr())
564            .with_orientation(view.orientation()),
565    ))
566}
567
568/// Outcome of [`compact_in_place`].
569#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
570pub enum CompactOutcome {
571    /// At least one metadata retag or in-place layout compaction occurred.
572    Compacted,
573    /// The buffer was already minimal for the requested [`AlphaCompaction`] policy.
574    Unchanged,
575}
576
577impl CompactOutcome {
578    /// Returns `true` if `self == CompactOutcome::Compacted`.
579    #[inline]
580    #[must_use]
581    pub const fn is_compacted(self) -> bool {
582        matches!(self, Self::Compacted)
583    }
584}
585
586/// Analyze and compact `buf` **in place** without reallocating owned mutable storage
587/// (copy-on-write promotes immutable external storage, propagating allocation errors instead
588/// of swallowing them).
589///
590/// Depth (`U16 → U8`) and chroma (`RGB → Gray`) compaction run whenever justified;
591/// `alpha_strategy` controls whether redundant alpha/padding lanes are retagged in metadata
592/// ([`AlphaCompaction::RetagOpaque`]) or physically dropped in place
593/// ([`AlphaCompaction::DropUnusedLanes`]).
594///
595/// Returns `Ok(CompactOutcome::Compacted)` if any metadata or layout compaction occurred,
596/// `Ok(CompactOutcome::Unchanged)` if `buf` was already minimal, or
597/// `Err(ConvertError::Buffer(_))` on CoW allocation failure.
598#[doc(alias = "load_bearing")]
599#[doc(alias = "shrink")]
600pub fn compact_in_place(
601    buf: &mut PixelBuf,
602    alpha_strategy: AlphaCompaction,
603) -> Result<CompactOutcome, At<ConvertError>> {
604    compact_in_place_with_pulse(buf, alpha_strategy, None)
605}
606
607/// Analyze and compact `buf` **in place** with optional cooperative cancellation and progress
608/// via `pulse` (pass `None` when not needed).
609///
610/// Cooperative cancellation is checked throughout the read-only analysis scan before any
611/// in-place byte mutation begins, so a cancelled call leaves `buf` unmodified.
612pub fn compact_in_place_with_pulse(
613    buf: &mut PixelBuf,
614    alpha_strategy: AlphaCompaction,
615    pulse: Option<&dyn Pulse>,
616) -> Result<CompactOutcome, At<ConvertError>> {
617    let pulse = live_pulse(pulse);
618    check_pulse(pulse)?;
619    if buf.width() == 0 || buf.height() == 0 || !buf.format().layout().packing().is_full() {
620        return Ok(CompactOutcome::Unchanged);
621    }
622    let measured_report = CompactionReport::measure_with_pulse(&buf.as_view(), pulse)?;
623    check_pulse(pulse)?;
624    let drop_alpha_lanes = alpha_strategy == AlphaCompaction::DropUnusedLanes;
625    let mut outcome = CompactOutcome::Unchanged;
626    buf.transform_in_place(|bytes, input| {
627        let width = input.width;
628        let rows = input.height;
629        let in_stride = input.stride_bytes;
630        let src = input.format;
631        let orig = input.origin;
632        if width == 0 || rows == 0 || !src.layout().packing().is_full() {
633            return InPlaceTransformDecision::Unchanged;
634        }
635        let mut report = measured_report;
636        let plan = plan_chroma_collapse(src);
637        if matches!(plan, GraySignalPlan::Suppress) {
638            report.requires_chroma = None;
639        }
640
641        let alpha_droppable =
642            matches!(report.requires_alpha, Some(false)) && src.layout().order().has_alpha_slot();
643        if !drop_alpha_lanes {
644            report.requires_alpha = None;
645        }
646
647        let mut target = apply_icc_chroma_collapse(src, &report, &plan);
648        if !drop_alpha_lanes
649            && alpha_droppable
650            && target.layout().order().has_alpha_slot()
651            && !matches!(
652                src.color().alpha(),
653                AlphaMode::Undefined | AlphaMode::Opaque
654            )
655        {
656            let Ok(opaque) = target.with_alpha(AlphaMode::Opaque) else {
657                return InPlaceTransformDecision::Unchanged;
658            };
659            target = opaque;
660        }
661
662        if &target == src {
663            return InPlaceTransformDecision::Unchanged;
664        }
665
666        // Equal-bpp target: metadata-only alpha retag (0 data movement).
667        let in_bpp = src.layout().bytes_per_pixel();
668        let out_bpp = target.layout().bytes_per_pixel();
669        if out_bpp == in_bpp {
670            let Ok(retagged) = src.clone().with_alpha(target.color().alpha()) else {
671                return InPlaceTransformDecision::Unchanged;
672            };
673            let mut claims = SampleClaims::NONE;
674            if matches!(retagged.color().alpha(), AlphaMode::Opaque) {
675                claims.all_opaque = true;
676                claims.binary_alpha = true;
677            }
678            outcome = CompactOutcome::Compacted;
679            return InPlaceTransformDecision::Updated(InPlaceTransformOutput {
680                stride_bytes: in_stride,
681                format: retagged,
682                origin: orig.clone(),
683                claims,
684            });
685        }
686        if out_bpp > in_bpp {
687            return InPlaceTransformDecision::Unchanged;
688        }
689
690        let narrow16 =
691            src.layout().sample() == SampleType::U16 && target.layout().sample() == SampleType::U8;
692        let Some(map) = selection_map(src.layout().order(), target.layout().order()) else {
693            return InPlaceTransformDecision::Unchanged;
694        };
695        let out_stride = (width as usize) * out_bpp;
696
697        compact_rows_in_place(
698            bytes,
699            width as usize,
700            rows as usize,
701            in_stride,
702            in_bpp,
703            out_bpp,
704            src.layout().order(),
705            target.layout().order(),
706            map,
707            narrow16,
708        );
709
710        outcome = CompactOutcome::Compacted;
711        InPlaceTransformDecision::Updated(InPlaceTransformOutput {
712            stride_bytes: out_stride,
713            format: target,
714            origin: orig.clone(),
715            claims: SampleClaims::NONE,
716        })
717    })
718    .map_err(|e| err_at((*e.error()).into()))?;
719    Ok(outcome)
720}
721
722// ── Row helpers & byte-exact compaction kernels ────────────────────────
723
724fn fused_rgba8_over_rows(
725    view: &PixelView<'_>,
726    request: FusedRequest,
727    pulse: Option<&dyn Pulse>,
728) -> Result<scan::FusedResult, At<ConvertError>> {
729    if pulse.is_none()
730        && let Some(bytes) = view.as_contiguous_bytes()
731    {
732        return Ok(scan::fused_predicates_rgba8_cg(bytes, request));
733    }
734    let mut req = request;
735    let mut total = scan::FusedResult {
736        is_opaque: req.check_opaque,
737        is_grayscale: req.check_grayscale,
738    };
739    for y in 0..view.height() {
740        if !req.check_opaque && !req.check_grayscale {
741            break;
742        }
743        let r = scan::fused_predicates_rgba8_cg(view.row(y), req);
744        if req.check_opaque && !r.is_opaque {
745            total.is_opaque = false;
746            req.check_opaque = false;
747        }
748        if req.check_grayscale && !r.is_grayscale {
749            total.is_grayscale = false;
750            req.check_grayscale = false;
751        }
752        step_pulse(pulse, 1)?;
753    }
754    Ok(total)
755}
756
757fn rows_all_u8(
758    view: &PixelView<'_>,
759    pred: fn(&[u8]) -> bool,
760    pulse: Option<&dyn Pulse>,
761) -> Result<bool, At<ConvertError>> {
762    if pulse.is_none()
763        && let Some(bytes) = view.as_contiguous_bytes()
764    {
765        return Ok(pred(bytes));
766    }
767    for y in 0..view.height() {
768        if !pred(view.row(y)) {
769            step_pulse(pulse, 1)?;
770            return Ok(false);
771        }
772        step_pulse(pulse, 1)?;
773    }
774    Ok(true)
775}
776
777fn rows_all_u16(
778    view: &PixelView<'_>,
779    pred: fn(&[u16]) -> bool,
780    pulse: Option<&dyn Pulse>,
781) -> Result<bool, At<ConvertError>> {
782    if pulse.is_none()
783        && let Some(bytes) = view.as_contiguous_bytes()
784        && let Ok(s) = bytemuck::try_cast_slice::<u8, u16>(bytes)
785    {
786        return Ok(pred(s));
787    }
788    for y in 0..view.height() {
789        let row = view.row(y);
790        if let Ok(s) = bytemuck::try_cast_slice::<u8, u16>(row) {
791            if !pred(s) {
792                step_pulse(pulse, 1)?;
793                return Ok(false);
794            }
795        } else {
796            for chunk in row.as_chunks::<2>().0 {
797                let v = u16::from_ne_bytes(*chunk);
798                if (v >> 8) != (v & 0xFF) {
799                    step_pulse(pulse, 1)?;
800                    return Ok(false);
801                }
802            }
803        }
804        step_pulse(pulse, 1)?;
805    }
806    Ok(true)
807}
808
809fn rows_all_f32(
810    view: &PixelView<'_>,
811    pred: fn(&[f32]) -> bool,
812    pulse: Option<&dyn Pulse>,
813) -> Result<bool, At<ConvertError>> {
814    if pulse.is_none()
815        && let Some(bytes) = view.as_contiguous_bytes()
816        && let Ok(s) = bytemuck::try_cast_slice::<u8, f32>(bytes)
817    {
818        return Ok(pred(s));
819    }
820    for y in 0..view.height() {
821        let row = view.row(y);
822        if let Ok(s) = bytemuck::try_cast_slice::<u8, f32>(row) {
823            if !pred(s) {
824                step_pulse(pulse, 1)?;
825                return Ok(false);
826            }
827        } else {
828            step_pulse(pulse, 1)?;
829            return Ok(false);
830        }
831        step_pulse(pulse, 1)?;
832    }
833    Ok(true)
834}
835
836fn selection_map(src: ChannelOrder, dst: ChannelOrder) -> Option<&'static [usize]> {
837    static IDENTITY: [usize; 4] = [0, 1, 2, 3];
838    Some(match (src, dst) {
839        _ if src == dst => &IDENTITY[..src.channels()],
840        (ChannelOrder::Rgba | ChannelOrder::Rgbx, ChannelOrder::Rgb) => &[0, 1, 2],
841        (ChannelOrder::Bgra | ChannelOrder::Bgrx, ChannelOrder::Rgb) => &[2, 1, 0],
842        (ChannelOrder::Rgba | ChannelOrder::Bgra, ChannelOrder::GrayAlpha) => &[0, 3],
843        (
844            ChannelOrder::Rgba
845            | ChannelOrder::Bgra
846            | ChannelOrder::Rgbx
847            | ChannelOrder::Bgrx
848            | ChannelOrder::Rgb
849            | ChannelOrder::Bgr
850            | ChannelOrder::GrayAlpha,
851            ChannelOrder::Gray,
852        ) => &[0],
853        _ => return None,
854    })
855}
856
857fn transform_into(
858    view: &PixelView<'_>,
859    src: &PixelFormat,
860    dst: &PixelFormat,
861    out: &mut PixelBuf,
862    pulse: Option<&dyn Pulse>,
863) -> Result<bool, At<ConvertError>> {
864    let narrow16 =
865        src.layout().sample() == SampleType::U16 && dst.layout().sample() == SampleType::U8;
866    if !narrow16 && src.layout().sample() != dst.layout().sample() {
867        return Ok(false);
868    }
869    let in_ch = src.layout().channels();
870    let Some(map) = selection_map(src.layout().order(), dst.layout().order()) else {
871        return Ok(false);
872    };
873    let mut out_view = out.as_view_mut();
874    for y in 0..view.height() {
875        let row_in = view.row(y);
876        let row_out = out_view.row_mut(y);
877        if narrow16 {
878            select_row_u16_to_u8(row_in, row_out, in_ch, map);
879        } else {
880            match (
881                dst.layout().sample().byte_size(),
882                src.layout().order(),
883                dst.layout().order(),
884            ) {
885                (1, ChannelOrder::Rgba | ChannelOrder::Rgbx, ChannelOrder::Rgb) => {
886                    if garb::bytes::rgba_to_rgb(row_in, row_out).is_err() {
887                        return Ok(false);
888                    }
889                }
890                (1, ChannelOrder::Bgra | ChannelOrder::Bgrx, ChannelOrder::Rgb) => {
891                    if garb::bytes::bgra_to_rgb(row_in, row_out).is_err() {
892                        return Ok(false);
893                    }
894                }
895                (1, ..) => select_row::<1>(row_in, row_out, in_ch, map),
896                (2, ..) => select_row::<2>(row_in, row_out, in_ch, map),
897                (4, ..) => select_row::<4>(row_in, row_out, in_ch, map),
898                _ => return Ok(false),
899            }
900        }
901        step_pulse(pulse, 1)?;
902    }
903    Ok(true)
904}
905
906#[allow(clippy::too_many_arguments)]
907fn compact_rows_in_place(
908    data: &mut [u8],
909    width: usize,
910    rows: usize,
911    in_stride: usize,
912    in_bpp: usize,
913    out_bpp: usize,
914    src_order: ChannelOrder,
915    dst_order: ChannelOrder,
916    map: &[usize],
917    narrow16: bool,
918) {
919    let out_stride = width * out_bpp;
920    let in_ch = src_order.channels();
921    let elem = if narrow16 { 2 } else { in_bpp / in_ch };
922    let row_in_len = width * in_bpp;
923    for y in 0..rows {
924        let src_start = y * in_stride;
925        let dst_start = y * out_stride;
926        let dst_end = dst_start + out_stride;
927        if dst_end <= src_start {
928            let (head, tail) = data.split_at_mut(src_start);
929            let row_in = &tail[..row_in_len];
930            let row_out = &mut head[dst_start..dst_end];
931            if narrow16 {
932                select_row_u16_to_u8(row_in, row_out, in_ch, map);
933            } else {
934                match (elem, src_order, dst_order) {
935                    (1, ChannelOrder::Rgba | ChannelOrder::Rgbx, ChannelOrder::Rgb) => {
936                        if garb::bytes::rgba_to_rgb(row_in, row_out).is_err() {
937                            select_row::<1>(row_in, row_out, in_ch, map);
938                        }
939                    }
940                    (1, ChannelOrder::Bgra | ChannelOrder::Bgrx, ChannelOrder::Rgb) => {
941                        if garb::bytes::bgra_to_rgb(row_in, row_out).is_err() {
942                            select_row::<1>(row_in, row_out, in_ch, map);
943                        }
944                    }
945                    (1, ..) => select_row::<1>(row_in, row_out, in_ch, map),
946                    (2, ..) => select_row::<2>(row_in, row_out, in_ch, map),
947                    _ => select_row::<4>(row_in, row_out, in_ch, map),
948                }
949            }
950        } else {
951            for x in 0..width {
952                let s = src_start + x * in_bpp;
953                let mut tmp = [0u8; 16];
954                tmp[..in_bpp].copy_from_slice(&data[s..s + in_bpp]);
955                let d = dst_start + x * out_bpp;
956                if narrow16 {
957                    for (k, &c) in map.iter().enumerate() {
958                        data[d + k] = tmp[c * 2];
959                    }
960                } else {
961                    for (k, &c) in map.iter().enumerate() {
962                        data[d + k * elem..d + (k + 1) * elem]
963                            .copy_from_slice(&tmp[c * elem..(c + 1) * elem]);
964                    }
965                }
966            }
967        }
968    }
969}
970
971#[inline]
972fn select_row<const E: usize>(row_in: &[u8], row_out: &mut [u8], in_ch: usize, map: &[usize]) {
973    let out_px = map.len() * E;
974    let in_px = in_ch * E;
975    for (dst, src) in row_out
976        .chunks_exact_mut(out_px)
977        .zip(row_in.chunks_exact(in_px))
978    {
979        for (k, &c) in map.iter().enumerate() {
980            dst[k * E..(k + 1) * E].copy_from_slice(&src[c * E..c * E + E]);
981        }
982    }
983}
984
985#[inline]
986fn select_row_u16_to_u8(row_in: &[u8], row_out: &mut [u8], in_ch: usize, map: &[usize]) {
987    let in_px = in_ch * 2;
988    for (dst, src) in row_out
989        .chunks_exact_mut(map.len())
990        .zip(row_in.chunks_exact(in_px))
991    {
992        for (k, &c) in map.iter().enumerate() {
993            dst[k] = src[c * 2];
994        }
995    }
996}