1use core::fmt;
21use whereat::At;
22use zenpixels::sample::{CodePlane, CodePlaneError, ExactDepth, SampleEncoding};
23use zenpixels::{ChannelOrder, PixelFormat, PixelViewMut, SampleType, SignalRange};
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum CodeRole {
29 Intensity,
31 Chroma,
33 Alpha,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum CodeMapError {
41 UnsupportedStorage,
43 UnsupportedRange(SignalRange),
45 NarrowBelowEightBits {
47 bits: u8,
49 },
50 FullRangeChromaDepth {
52 from_bits: u8,
54 to_bits: u8,
56 },
57 LengthMismatch {
59 source: usize,
61 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub struct CodeMap {
105 from: SampleEncoding,
106 to: SampleEncoding,
107 rule: Rule,
108}
109
110impl CodeMap {
111 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 #[inline]
160 #[must_use]
161 pub const fn input(&self) -> SampleEncoding {
162 self.from
163 }
164
165 #[inline]
167 #[must_use]
168 pub const fn output(&self) -> SampleEncoding {
169 self.to
170 }
171
172 #[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 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 #[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 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#[derive(Clone, Debug, PartialEq, Eq)]
217#[non_exhaustive]
218pub enum CodesError {
219 Destination {
221 actual: PixelFormat,
223 },
224 RangeMismatch {
226 source: SignalRange,
228 destination: SignalRange,
230 },
231 ComponentCount {
233 expected: usize,
235 actual: usize,
237 },
238 Narrowing {
240 component: usize,
242 bits: u8,
244 destination_bits: u8,
246 },
247 Map {
249 component: usize,
251 error: CodeMapError,
253 },
254 Extent {
256 component: usize,
258 origin: (usize, usize),
260 extent: (usize, usize),
262 plane: (usize, usize),
264 },
265 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
314const BATCH: usize = 256;
316
317pub 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}