Skip to main content

zenpixels_convert/
codes.rs

1//! Exact depth, placement, and range conversion of native integer codes.
2//!
3//! A *code* is the unsigned integer that a [`SampleEncoding`] extracts from a
4//! storage word. Canonical `U16` and `U8` image samples are codes of the full
5//! word width: a canonical `U16` white is `65535`, never a ten-bit `1023`.
6//! Native codecs keep their codes in [`CodePlane`] views; this module converts
7//! between those codes and canonical samples, or between two native encodings.
8//!
9//! | Role and range | Depth change from `N` to `M` bits | Inverse of a widening |
10//! |---|---|---|
11//! | Intensity (R′G′B′, gray, Y′), full range | Nearest `(q·max(M) + max(N)/2) / max(N)` | Exact: every code returns |
12//! | Intensity or chroma, narrow range | `q << (M−N)`; narrowing rounds half up, clamped to `max(M)` | Exact |
13//! | Alpha, any color range | Nearest full-scale, as full-range intensity | Exact |
14//! | Chroma, full range | Refused: neutral and span have no exact relation between depths | — |
15//!
16//! `max(N) = 2^N − 1`; odd denominators make nearest rounding tie-free.
17//! Narrow range needs at least 8 bits so its anchors (`16·2^(N−8)` black,
18//! `128·2^(N−8)` neutral) are integers.
19
20use core::fmt;
21use whereat::At;
22use zenpixels::sample::{CodePlane, CodePlaneError, ExactDepth, SampleEncoding};
23use zenpixels::{ChannelOrder, PixelFormat, PixelViewMut, SampleType, SignalRange};
24
25/// What a component's codes mean, which selects its depth-conversion rule.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum CodeRole {
29    /// R′G′B′, gray or Y′: zero is black; the signal range selects white.
30    Intensity,
31    /// Cb or Cr: a signed offset from a neutral code that scales with depth.
32    Chroma,
33    /// Coverage: always full scale, whatever the color signal range.
34    Alpha,
35}
36
37/// A code conversion cannot be performed exactly as requested.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum CodeMapError {
41    /// Numerical mapping requires unsigned `U8`/`U16` words.
42    UnsupportedStorage,
43    /// The signal range has no defined code rule here.
44    UnsupportedRange(SignalRange),
45    /// Narrow-range anchors are not integers below eight bits.
46    NarrowBelowEightBits {
47        /// The offending code depth.
48        bits: u8,
49    },
50    /// Full-range chroma has no exact neutral/span relation between depths.
51    FullRangeChromaDepth {
52        /// Source code depth.
53        from_bits: u8,
54        /// Destination code depth.
55        to_bits: u8,
56    },
57    /// Source and destination word slices differ in length.
58    LengthMismatch {
59        /// Source words.
60        source: usize,
61        /// Destination words.
62        destination: usize,
63    },
64}
65
66impl fmt::Display for CodeMapError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::UnsupportedStorage => f.write_str("code mapping requires unsigned U8/U16 words"),
70            Self::UnsupportedRange(range) => write!(f, "no code rule for signal range {range:?}"),
71            Self::NarrowBelowEightBits { bits } => {
72                write!(f, "narrow-range codes need at least 8 bits, got {bits}")
73            }
74            Self::FullRangeChromaDepth { from_bits, to_bits } => write!(
75                f,
76                "full-range chroma has no exact {from_bits}-bit to {to_bits}-bit rule"
77            ),
78            Self::LengthMismatch {
79                source,
80                destination,
81            } => write!(
82                f,
83                "code map source has {source} words, destination {destination}"
84            ),
85        }
86    }
87}
88
89impl core::error::Error for CodeMapError {}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92enum Rule {
93    Same,
94    Nearest { from_max: u32, to_max: u32 },
95    ShiftLeft(u32),
96    RoundShiftRight { shift: u32, max: u32 },
97}
98
99/// A checked conversion of one component from one [`SampleEncoding`] to another.
100///
101/// Construction selects the rule once from the role, signal range, and both
102/// encodings; mapping performs integer arithmetic only and never allocates.
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub struct CodeMap {
105    from: SampleEncoding,
106    to: SampleEncoding,
107    rule: Rule,
108}
109
110impl CodeMap {
111    /// Prepare the conversion of `role` codes from `from` to `to`.
112    pub const fn new(
113        from: SampleEncoding,
114        to: SampleEncoding,
115        role: CodeRole,
116        range: SignalRange,
117    ) -> Result<Self, CodeMapError> {
118        if !matches!(from.storage(), SampleType::U8 | SampleType::U16)
119            || !matches!(to.storage(), SampleType::U8 | SampleType::U16)
120        {
121            return Err(CodeMapError::UnsupportedStorage);
122        }
123        let (n, m) = (from.code_bits(), to.code_bits());
124        let full_scale = match (role, range) {
125            (CodeRole::Alpha, _) => true,
126            (_, SignalRange::Full) => true,
127            (_, SignalRange::Narrow) => false,
128            (_, other) => return Err(CodeMapError::UnsupportedRange(other)),
129        };
130        let rule = if n == m {
131            Rule::Same
132        } else if full_scale {
133            if matches!(role, CodeRole::Chroma) {
134                return Err(CodeMapError::FullRangeChromaDepth {
135                    from_bits: n,
136                    to_bits: m,
137                });
138            }
139            Rule::Nearest {
140                from_max: (1u32 << n) - 1,
141                to_max: (1u32 << m) - 1,
142            }
143        } else if n < 8 || m < 8 {
144            return Err(CodeMapError::NarrowBelowEightBits {
145                bits: if n < m { n } else { m },
146            });
147        } else if m > n {
148            Rule::ShiftLeft((m - n) as u32)
149        } else {
150            Rule::RoundShiftRight {
151                shift: (n - m) as u32,
152                max: (1u32 << m) - 1,
153            }
154        };
155        Ok(Self { from, to, rule })
156    }
157
158    /// Encoding of the words this map reads.
159    #[inline]
160    #[must_use]
161    pub const fn input(&self) -> SampleEncoding {
162        self.from
163    }
164
165    /// Encoding of the words this map writes.
166    #[inline]
167    #[must_use]
168    pub const fn output(&self) -> SampleEncoding {
169        self.to
170    }
171
172    /// Convert one source code (bits above its depth are ignored) to a destination code.
173    #[inline]
174    #[must_use]
175    pub const fn map_code(&self, code: u16) -> u16 {
176        let q = (code as u32) & ((1u32 << self.from.code_bits()) - 1);
177        (match self.rule {
178            Rule::Same => q,
179            // max <= 65535: q * to_max + from_max / 2 < 2^32.
180            Rule::Nearest { from_max, to_max } => (q * to_max + from_max / 2) / from_max,
181            Rule::ShiftLeft(s) => q << s,
182            Rule::RoundShiftRight { shift, max } => {
183                let r = (q + (1 << (shift - 1))) >> shift;
184                if r > max { max } else { r }
185            }
186        }) as u16
187    }
188
189    /// Extract the code from a source word, convert it, and place it in a destination word.
190    ///
191    /// Source padding is ignored; destination padding is zero.
192    #[inline]
193    #[must_use]
194    pub const fn map_word(&self, word: u16) -> u16 {
195        self.map_code(word >> self.from.bit_shift()) << self.to.bit_shift()
196    }
197
198    /// Map equal-length runs of source words to destination words.
199    ///
200    /// Lengths are checked before any write.
201    pub fn map_words(&self, source: &[u16], destination: &mut [u16]) -> Result<(), CodeMapError> {
202        if source.len() != destination.len() {
203            return Err(CodeMapError::LengthMismatch {
204                source: source.len(),
205                destination: destination.len(),
206            });
207        }
208        for (d, s) in destination.iter_mut().zip(source) {
209            *d = self.map_word(*s);
210        }
211        Ok(())
212    }
213}
214
215/// Native components cannot be widened into the requested canonical image.
216#[derive(Clone, Debug, PartialEq, Eq)]
217#[non_exhaustive]
218pub enum CodesError {
219    /// The destination is not canonical full-packing `U8`/`U16` Gray, GrayAlpha, RGB, or RGBA.
220    Destination {
221        /// The destination spec.
222        actual: PixelFormat,
223    },
224    /// The destination's signal range differs from the components' range.
225    RangeMismatch {
226        /// Range of the native components.
227        source: SignalRange,
228        /// Range declared by the destination.
229        destination: SignalRange,
230    },
231    /// The number of components differs from the destination's channels.
232    ComponentCount {
233        /// Destination channels.
234        expected: usize,
235        /// Supplied components.
236        actual: usize,
237    },
238    /// A component has more code bits than the destination; widening only.
239    Narrowing {
240        /// Component index.
241        component: usize,
242        /// Its code depth.
243        bits: u8,
244        /// The destination's storage depth.
245        destination_bits: u8,
246    },
247    /// A component's encoding has no exact rule for its role and range.
248    Map {
249        /// Component index.
250        component: usize,
251        /// The refusal.
252        error: CodeMapError,
253    },
254    /// The requested region extends beyond a component plane.
255    Extent {
256        /// Component index.
257        component: usize,
258        /// Region origin in plane coordinates.
259        origin: (usize, usize),
260        /// Region width and height.
261        extent: (usize, usize),
262        /// The plane's width and height.
263        plane: (usize, usize),
264    },
265    /// A plane read failed after validation; an internal consistency error.
266    Read(CodePlaneError),
267}
268
269impl fmt::Display for CodesError {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        match self {
272            Self::Destination { actual } => write!(
273                f,
274                "canonical destination must be full-packing U8/U16 Gray, GrayAlpha, RGB, or RGBA, got {actual:?}"
275            ),
276            Self::RangeMismatch {
277                source,
278                destination,
279            } => write!(
280                f,
281                "components are {source:?} range, destination is {destination:?}"
282            ),
283            Self::ComponentCount { expected, actual } => {
284                write!(
285                    f,
286                    "destination has {expected} channels, got {actual} components"
287                )
288            }
289            Self::Narrowing {
290                component,
291                bits,
292                destination_bits,
293            } => write!(
294                f,
295                "component {component} has {bits} code bits; a {destination_bits}-bit destination would quantize"
296            ),
297            Self::Map { component, error } => write!(f, "component {component}: {error}"),
298            Self::Extent {
299                component,
300                origin,
301                extent,
302                plane,
303            } => write!(
304                f,
305                "component {component}: region {extent:?} at {origin:?} exceeds plane {plane:?}"
306            ),
307            Self::Read(error) => write!(f, "code plane read failed: {error}"),
308        }
309    }
310}
311
312impl core::error::Error for CodesError {}
313
314/// Codes converted per bounded batch; the stack buffer is 512 bytes.
315const BATCH: usize = 256;
316
317/// Unpack and widen borrowed native component [`CodePlane`]s into a canonical strided
318/// [`PixelViewMut`] region starting at `source_origin = (x, y)` in each source plane.
319///
320/// `components` are in destination channel order (`Gray`; `Gray, Alpha`; `R, G, B`;
321/// or `R, G, B, A`); alpha is always full scale. Every check precedes the first write,
322/// row padding is untouched, and execution allocates nothing.
323///
324/// Returns the [`ExactDepth`] established by this exact widening.
325pub fn unpack_code_planes_into(
326    components: &[CodePlane<'_>],
327    range: SignalRange,
328    source_origin: (usize, usize),
329    destination: &mut PixelViewMut<'_>,
330) -> Result<ExactDepth, At<CodesError>> {
331    let (x, y) = source_origin;
332    let spec = destination.format().clone();
333    if !spec.layout().packing().is_full() {
334        return Err(whereat::at!(CodesError::Destination { actual: spec }));
335    }
336    let storage_bits: u8 = match spec.layout().sample() {
337        SampleType::U8 => 8,
338        SampleType::U16 => 16,
339        _ => return Err(whereat::at!(CodesError::Destination { actual: spec })),
340    };
341    let has_alpha = match spec.layout().order() {
342        ChannelOrder::Gray | ChannelOrder::Rgb => false,
343        ChannelOrder::GrayAlpha | ChannelOrder::Rgba => true,
344        _ => return Err(whereat::at!(CodesError::Destination { actual: spec })),
345    };
346    let dst_range = spec.color().range().unwrap_or(SignalRange::Full);
347    if dst_range != range {
348        return Err(whereat::at!(CodesError::RangeMismatch {
349            source: range,
350            destination: dst_range,
351        }));
352    }
353    let channels = spec.layout().channels();
354    if components.len() != channels {
355        return Err(whereat::at!(CodesError::ComponentCount {
356            expected: channels,
357            actual: components.len(),
358        }));
359    }
360    let canonical = match SampleEncoding::new(spec.layout().sample(), storage_bits, 0) {
361        Ok(encoding) => encoding,
362        Err(_) => return Err(whereat::at!(CodesError::Destination { actual: spec })),
363    };
364    let (width, height) = (destination.width() as usize, destination.height() as usize);
365    let mut maps = [None; 4];
366    for (component, plane) in components.iter().enumerate() {
367        let bits = plane.encoding().code_bits();
368        if bits > storage_bits {
369            return Err(whereat::at!(CodesError::Narrowing {
370                component,
371                bits,
372                destination_bits: storage_bits,
373            }));
374        }
375        let role = if has_alpha && component + 1 == channels {
376            CodeRole::Alpha
377        } else {
378            CodeRole::Intensity
379        };
380        maps[component] = Some(
381            CodeMap::new(plane.encoding(), canonical, role, range)
382                .map_err(|error| whereat::at!(CodesError::Map { component, error }))?,
383        );
384        if x.checked_add(width).is_none_or(|end| end > plane.width())
385            || y.checked_add(height).is_none_or(|end| end > plane.height())
386        {
387            return Err(whereat::at!(CodesError::Extent {
388                component,
389                origin: (x, y),
390                extent: (width, height),
391                plane: (plane.width(), plane.height()),
392            }));
393        }
394    }
395
396    let exact = established_depth(
397        components,
398        range,
399        has_alpha,
400        spec.layout().sample(),
401        storage_bits,
402    )
403    .ok_or_else(|| whereat::at!(CodesError::Destination { actual: spec }))?;
404
405    let mut codes = [0u16; BATCH];
406    for row in 0..height {
407        let out = destination.row_mut(row as u32);
408        for (component, (plane, map)) in components.iter().zip(maps).enumerate() {
409            let Some(map) = map else { continue };
410            let mut start = 0;
411            while start < width {
412                let count = (width - start).min(BATCH);
413                let batch = &mut codes[..count];
414                plane
415                    .read_codes(x + start, y + row, batch)
416                    .map_err(|e| whereat::at!(CodesError::Read(e)))?;
417                let first = start * channels + component;
418                if storage_bits == 8 {
419                    for (i, code) in batch.iter().enumerate() {
420                        out[first + i * channels] = map.map_code(*code) as u8;
421                    }
422                } else {
423                    for (i, code) in batch.iter().enumerate() {
424                        let at = (first + i * channels) * 2;
425                        out[at..at + 2].copy_from_slice(&map.map_code(*code).to_ne_bytes());
426                    }
427                }
428                start += count;
429            }
430        }
431    }
432    Ok(exact)
433}
434
435fn established_depth(
436    components: &[CodePlane<'_>],
437    range: SignalRange,
438    has_alpha: bool,
439    storage: SampleType,
440    storage_bits: u8,
441) -> Option<ExactDepth> {
442    let color_count = components.len() - usize::from(has_alpha);
443    let narrow = range == SignalRange::Narrow;
444    let mut color: u32 = 1;
445    for plane in &components[..color_count] {
446        let bits = u32::from(plane.encoding().code_bits());
447        color = if narrow {
448            color.max(bits)
449        } else {
450            lcm(color, bits)
451        };
452    }
453    let color = if color > u32::from(storage_bits) {
454        storage_bits
455    } else {
456        color as u8
457    };
458    let alpha = if has_alpha {
459        components[color_count].encoding().code_bits()
460    } else {
461        storage_bits
462    };
463    ExactDepth::new(storage, range, color, alpha).ok()
464}
465
466fn lcm(a: u32, b: u32) -> u32 {
467    let (mut x, mut y) = (a, b);
468    while y != 0 {
469        (x, y) = (y, x % y);
470    }
471    a / x * b
472}