openjp2 0.7.2

Rust port of Openjpeg.
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
// The copyright in this software is being made available under the 2-clauses
// BSD License, included below. This software may be subject to other third
// party and contributor rights, including patent rights, and no such rights
// are granted under this license.
//
// Copyright (c) 2005, Herve Drolon, FreeImage Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//! The image data model: `CoreImage`/`CoreImageComp`, the C-ABI
//! compat accessors and the ICC-profile handling.

use super::math::*;
use super::openjpeg::*;

/// Borrowed component with the signed->unsigned adjustment precomputed
/// (used by the data iterators).
pub struct ImageCompRef<'a> {
  /// Component.
  pub comp: &'a CoreImageComp,
  /// Adjustment value to convert from signed to unsigned.
  pub adjust: i32,
  /// Component data.
  pub data: &'a [i32],
}

pub(crate) fn image_comp_header_update(p_image_header: &mut CoreImage, p_cp: &Cp) {
  let l_x0 = uint_max(p_cp.tx0, p_image_header.x0);
  let l_y0 = uint_max(p_cp.ty0, p_image_header.y0);
  let l_x1 = p_cp
    .tx0
    .wrapping_add(p_cp.tw.wrapping_sub(1u32).wrapping_mul(p_cp.tdx));
  let l_y1 = p_cp
    .ty0
    .wrapping_add(p_cp.th.wrapping_sub(1u32).wrapping_mul(p_cp.tdy));
  let l_x1 = uint_min(uint_adds(l_x1, p_cp.tdx), p_image_header.x1);
  let l_y1 = uint_min(uint_adds(l_y1, p_cp.tdy), p_image_header.y1);
  for comp in &mut p_image_header.comps {
    let l_comp_x0 = uint_ceildiv(l_x0, comp.dx);
    let l_comp_y0 = uint_ceildiv(l_y0, comp.dy);
    let l_comp_x1 = uint_ceildiv(l_x1, comp.dx);
    let l_comp_y1 = uint_ceildiv(l_y1, comp.dy);
    /* The C computes ceildivpow2(x1) - ceildivpow2(x0) (divide before the
    difference); doing ceildivpow2(x1 - x0) gives a different size when
    the origin is not aligned to 2^factor (e.g. b1_mono.j2c with
    x0=1, factor=1: 151 vs 152). */
    let l_width =
      uint_ceildivpow2(l_comp_x1, comp.factor) - uint_ceildivpow2(l_comp_x0, comp.factor);
    let l_height =
      uint_ceildivpow2(l_comp_y1, comp.factor) - uint_ceildivpow2(l_comp_y0, comp.factor);
    comp.w = l_width;
    comp.h = l_height;
    comp.x0 = l_comp_x0;
    comp.y0 = l_comp_y0;
  }
}

pub(crate) fn copy_image_header_to_core(p_image_src: &CoreImage, p_image_dest: &mut CoreImage) {
  *p_image_dest = p_image_src.clone_header_only();
}

/// A colour profile carried by a JP2 `colr` box: either a raw ICC
/// profile or a CIELab colour specification (36 bytes, see
/// [`CIE_LAB_BYTE_SIZE`]).
#[derive(Clone)]
pub enum ICCProfile {
  /// An ICC profile (the profile bytes, header included).
  ICC(Vec<u8>),
  /// A CIELab colour specification (the fixed 36-byte layout).
  CIELab(Vec<u8>),
}
/// The size in bytes of a CIELab colour specification inside the JP2
/// `colr` box.
pub const CIE_LAB_BYTE_SIZE: usize = 36;

impl ICCProfile {
  /// Wraps raw ICC profile bytes.
  pub fn new_icc(data: &[u8]) -> Self {
    ICCProfile::ICC(data.to_vec())
  }

  /// Wraps raw CIELab colour-specification bytes.
  pub fn new_cielab(data: &[u8]) -> Self {
    ICCProfile::CIELab(data.to_vec())
  }
}

/// Borrowed view of an [`ICCProfile`].
#[derive(Debug)]
pub enum ICCProfileRef<'a> {
  /// The ICC profile bytes.
  ICC(&'a [u8]),
  /// The CIELab colour-specification bytes.
  CIELab(&'a [u8]),
}

impl<'a> ICCProfileRef<'a> {
  /// The profile bytes (either kind).
  pub fn as_slice(&self) -> &[u8] {
    match self {
      ICCProfileRef::ICC(data) => data,
      ICCProfileRef::CIELab(data) => data,
    }
  }

  /// Whether this is a CIELab colour specification.
  pub fn is_cielab(&self) -> bool {
    matches!(self, ICCProfileRef::CIELab(_))
  }

  /// The profile length in bytes.
  pub fn len(&self) -> usize {
    match self {
      ICCProfileRef::ICC(data) => data.len(),
      ICCProfileRef::CIELab(data) => data.len(),
    }
  }

  /// Whether the profile is empty.
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

/// Mutable borrowed view of an [`ICCProfile`].
#[derive(Debug)]
pub enum ICCProfileMut<'a> {
  /// The ICC profile bytes.
  ICC(&'a mut [u8]),
  /// The CIELab colour-specification bytes.
  CIELab(&'a mut [u8]),
}

impl<'a> ICCProfileMut<'a> {
  /// The mutable profile bytes (either kind).
  pub fn as_mut_slice(&mut self) -> &mut [u8] {
    match self {
      ICCProfileMut::ICC(data) => data,
      ICCProfileMut::CIELab(data) => data,
    }
  }

  /// Whether this is a CIELab colour specification.
  pub fn is_cielab(&self) -> bool {
    matches!(self, ICCProfileMut::CIELab(_))
  }
}

impl ICCProfile {
  /// The profile bytes (either kind).
  pub fn as_slice(&self) -> &[u8] {
    match self {
      ICCProfile::ICC(data) => data,
      ICCProfile::CIELab(data) => data,
    }
  }
}

/// One image component: geometry, sample format, and the raw sample data.
#[derive(Clone, Default)]
pub struct CoreImageComp {
  /// Horizontal subsampling factor.
  pub dx: u32,
  /// Vertical subsampling factor.
  pub dy: u32,
  /// Component width in samples.
  pub w: u32,
  /// Component height in samples.
  pub h: u32,
  /// Component origin x.
  pub x0: u32,
  /// Component origin y.
  pub y0: u32,
  /// Sample precision in bits (1..=31 supported).
  pub prec: u32,
  /// Bits per sample as declared (JP2 `bpc`; may differ from `prec`).
  pub bpp: u32,
  /// `1` for signed samples.
  pub sgnd: u32,
  /// Resolution actually decoded (0-based decomposition index).
  pub resno_decoded: u32,
  /// Resolution reduction factor applied by the decode.
  pub factor: u32,
  /// `1` when this component is the alpha channel.
  pub alpha: u16,
  /// The sample values, row-major, `w * h` entries (i32 for 0.7; see
  /// `doc/component-data-types.md`).
  pub data: Vec<i32>,
}

/// A decoded (or to-be-encoded) image: geometry, colour space, components
/// and the ICC profile.
#[derive(Clone, Default)]
pub struct CoreImage {
  /// Image origin x.
  pub x0: u32,
  /// Image origin y.
  pub y0: u32,
  /// Image end x.
  pub x1: u32,
  /// Image end y.
  pub y1: u32,
  /// Number of components.
  pub numcomps: u32,
  /// Declared colour space.
  pub color_space: crate::api::ColorSpace,
  /// The components.
  pub comps: Vec<CoreImageComp>,
  /// Raw ICC profile bytes (JP2 `colr` box).
  pub icc_profile_buf: Vec<u8>,
  /// A non-empty profile buffer with this flag means the profile is CIELab
  /// (mirrors the C ABI convention of icc_profile_len == 0).
  pub icc_profile_is_cielab: bool,
}

impl CoreImageComp {
  /// Data accessor kept for compatibility with the C-ABI image API.
  pub fn data(&self) -> Option<&[i32]> {
    Some(&self.data)
  }

  /// Mutable data accessor (C-ABI image API compatibility).
  pub fn data_mut(&mut self) -> Option<&mut [i32]> {
    Some(&mut self.data)
  }

  /// Allocate (zeroed) data for w * h samples.
  pub fn alloc_data(&mut self) -> bool {
    let len = (self.w as usize).wrapping_mul(self.h as usize);
    let mut data = Vec::new();
    if data.try_reserve_exact(len).is_err() {
      return false;
    }
    data.resize(len, 0);
    self.data = data;
    true
  }

  /// Clears the sample data (keeping the geometry).
  pub fn clear_data(&mut self) {
    self.data.clear();
  }

  /// Updates the component dimensions, clearing the data when they change.
  pub fn set_dims(&mut self, w: u32, h: u32) {
    if self.w == w && self.h == h {
      return;
    }
    self.w = w;
    self.h = h;
    self.data.clear();
  }

  /// Replaces the sample data (returns `true` for C-ABI parity).
  pub fn set_data(&mut self, data: &[i32]) -> bool {
    self.data = data.to_vec();
    true
  }

  /// Copy component properties (not data).
  pub fn copy_props(&mut self, other: &CoreImageComp) {
    self.data.clear();
    self.dx = other.dx;
    self.dy = other.dy;
    self.w = other.w;
    self.h = other.h;
    self.x0 = other.x0;
    self.y0 = other.y0;
    self.prec = other.prec;
    self.bpp = other.bpp;
    self.sgnd = other.sgnd;
    self.resno_decoded = other.resno_decoded;
    self.factor = other.factor;
    self.alpha = other.alpha;
  }

  /// Copy properties and data from another core component.
  pub fn copy(&mut self, other: &CoreImageComp) -> bool {
    *self = other.clone();
    true
  }

  /// Clip component samples to `precision` bits.
  pub fn clip(&mut self, precision: u32) {
    let signed = self.sgnd != 0;
    let (min, max) = match (precision, signed) {
      (0..=31, false) => (0, (1i64 << precision) - 1),
      (1..=31, true) => {
        let max = (1i64 << (precision - 1)) - 1;
        let min = -max - 1;
        (min, max)
      }
      /* precision 0 (or > 31) has no representable range: clamp to
      non-negative, matching the comps_data_iter/scale guards. */
      _ => (0, i64::MAX),
    };
    for val in self.data.iter_mut() {
      *val = (*val as i64).clamp(min, max) as i32;
    }
    self.prec = precision;
  }

  /// Scale component samples to `precision` bits.
  pub fn scale(&mut self, precision: u32) {
    if self.prec == precision {
      return;
    }
    /* Guard the shifts below: precisions outside 1..=31 have no meaningful
    i32 sample representation (PCLR palettes can set prec up to 128, and
    caller-built components may carry 0). */
    if !crate::types::prec_valid(precision) || !crate::types::prec_valid(self.prec) {
      return;
    }
    if self.prec < precision {
      let signed = self.sgnd != 0;
      let old_prec = self.prec;
      if signed {
        let new_max = 1i64 << (precision - 1);
        let old_max = 1i64 << (old_prec - 1);
        for val in self.data.iter_mut() {
          *val = (((*val as i64) * new_max) / old_max) as i32;
        }
      } else {
        let new_max = (1u64 << precision) - 1;
        let old_max = (1u64 << old_prec) - 1;
        for val in self.data.iter_mut() {
          *val = (((*val as u64) * new_max) / old_max) as i32;
        }
      }
      self.prec = precision;
      return;
    }
    let sgnd = self.sgnd != 0;
    let shift = self.prec - precision;
    if sgnd {
      for val in self.data.iter_mut() {
        *val >>= shift;
      }
    } else {
      for val in self.data.iter_mut() {
        *val = ((*val as u32) >> shift) as i32;
      }
    }
    self.prec = precision;
  }
}

impl CoreImage {
  /// Creates an empty image.
  pub fn new() -> CoreImage {
    CoreImage::default()
  }

  /// Header-only image from component parameters (no data).
  pub fn tile_create(
    cmptparms: &[CoreImageComp],
    clrspc: crate::api::ColorSpace,
  ) -> Option<CoreImage> {
    let mut image = CoreImage {
      color_space: clrspc,
      ..Default::default()
    };
    if !image.alloc_comps(cmptparms.len() as u32) {
      return None;
    }
    image.comps.clone_from_slice(cmptparms);
    Some(image)
  }

  /// Compatibility accessors over the owned Vecs.
  pub fn comps(&self) -> Option<&[CoreImageComp]> {
    Some(&self.comps)
  }

  /// Mutable component slice (C-ABI image API compatibility).
  pub fn comps_mut(&mut self) -> Option<&mut [CoreImageComp]> {
    Some(&mut self.comps)
  }

  /// Iterates the components with their signed->unsigned adjustments.
  pub fn comps_data_iter(&self) -> Option<impl Iterator<Item = ImageCompRef<'_>>> {
    Some(self.comps.iter().map(|comp| ImageCompRef {
      comp,
      /* Guard the shift: PCLR palettes can legally set prec up to 128 and
      caller-built components may carry prec == 0; the adjustment is only
      meaningful for 1..=31. */
      adjust: if comp.sgnd != 0 && crate::types::prec_valid(comp.prec) {
        1 << (comp.prec - 1)
      } else {
        0
      },
      data: &comp.data,
    }))
  }

  /// Moves the components into a fresh image, emptying this one.
  pub fn take_comps(&mut self) -> CoreImage {
    let mut image = CoreImage {
      x0: self.x0,
      y0: self.y0,
      x1: self.x1,
      y1: self.y1,
      numcomps: self.numcomps,
      color_space: self.color_space,
      comps: core::mem::take(&mut self.comps),
      ..Default::default()
    };
    self.numcomps = 0;
    image
  }

  /// Sets three same-sized components from separate RGB planes.
  pub fn set_rgb(&mut self, w: usize, h: usize, r: &[i32], g: &[i32], b: &[i32]) -> bool {
    let Some(len) = w.checked_mul(h) else {
      return false;
    };
    if r.len() != len || g.len() != len || b.len() != len || self.comps.len() < 3 {
      return false;
    }
    let w = w as u32;
    let h = h as u32;
    self.comps[0].set_dims(w, h);
    self.comps[1].set_dims(w, h);
    self.comps[2].set_dims(w, h);
    /* Update component. */
    self.comps[1].dx = self.comps[0].dx;
    self.comps[2].dx = self.comps[0].dx;
    self.comps[1].dy = self.comps[0].dy;
    self.comps[2].dy = self.comps[0].dy;
    self.comps[0].set_data(r);
    self.comps[1].set_data(g);
    self.comps[2].set_data(b);
    self.color_space = crate::api::ColorSpace::Srgb;
    true
  }

  /// Iterates the components' sample data mutably.
  pub fn comps_data_mut_iter(&mut self) -> Option<impl Iterator<Item = &mut [i32]>> {
    Some(self.comps.iter_mut().map(|c| &mut c.data[..]))
  }

  /// Moves the ICC profile out of the image (either kind).
  pub fn take_icc_profile(&mut self) -> Option<ICCProfile> {
    if self.icc_profile_buf.is_empty() && !self.icc_profile_is_cielab {
      None
    } else {
      let buf = core::mem::take(&mut self.icc_profile_buf);
      let profile = if self.icc_profile_is_cielab {
        ICCProfile::new_cielab(&buf)
      } else {
        ICCProfile::new_icc(&buf)
      };
      self.icc_profile_is_cielab = false;
      Some(profile)
    }
  }

  /// Removes the ICC profile.
  pub fn clear_icc_profile(&mut self) {
    self.icc_profile_buf.clear();
    self.icc_profile_is_cielab = false;
  }

  /// Deep copy of a C-ABI image (header, component properties, data and ICC profile).
  /// Copy of the image header (component properties, empty data).
  pub(crate) fn clone_header_only(&self) -> CoreImage {
    CoreImage {
      x0: self.x0,
      y0: self.y0,
      x1: self.x1,
      y1: self.y1,
      numcomps: self.numcomps,
      color_space: self.color_space,
      comps: self
        .comps
        .iter()
        .map(|c| CoreImageComp {
          dx: c.dx,
          dy: c.dy,
          w: c.w,
          h: c.h,
          x0: c.x0,
          y0: c.y0,
          prec: c.prec,
          bpp: c.bpp,
          sgnd: c.sgnd,
          resno_decoded: c.resno_decoded,
          factor: c.factor,
          alpha: c.alpha,
          data: Vec::new(),
        })
        .collect(),
      icc_profile_buf: self.icc_profile_buf.clone(),
      icc_profile_is_cielab: self.icc_profile_is_cielab,
    }
  }

  /// Reallocates the component list to `numcomps` default components.
  pub fn alloc_comps(&mut self, numcomps: u32) -> bool {
    self.comps.clear();
    self.numcomps = numcomps;
    self
      .comps
      .resize(numcomps as usize, CoreImageComp::default());
    true
  }

  /// Component 0's width, height and precision.
  pub fn comp0_dims_prec(&self) -> (usize, usize, i32) {
    if let Some(comp) = self.comps.first() {
      return (comp.w as usize, comp.h as usize, comp.prec as i32);
    }
    (0, 0, 0)
  }

  /// Check if all components have the same dimensions.
  pub fn comps_same_dims(&self) -> bool {
    if let Some((c0, comps)) = self.comps.split_first() {
      for comp in comps {
        if comp.w != c0.w || comp.h != c0.h || comp.dx != c0.dx || comp.dy != c0.dy {
          return false;
        }
      }
      return true;
    }
    false
  }

  /// Check if all components have the same dimensions and precision.
  pub fn comps_match(&self) -> bool {
    if let Some((c0, comps)) = self.comps.split_first() {
      for comp in comps {
        if comp.w != c0.w
          || comp.h != c0.h
          || comp.dx != c0.dx
          || comp.dy != c0.dy
          || comp.prec != c0.prec
          || comp.sgnd != c0.sgnd
        {
          return false;
        }
      }
      return true;
    }
    false
  }
}

impl CoreImageComp {
  /// Component width in samples.
  pub fn width(&self) -> u32 {
    self.w
  }

  /// Component height in samples.
  pub fn height(&self) -> u32 {
    self.h
  }

  /// Sample precision in bits.
  pub fn precision(&self) -> u32 {
    self.prec
  }

  /// Bits per sample as declared.
  pub fn bpp(&self) -> u32 {
    self.bpp
  }

  /// Whether this component is the alpha channel.
  pub fn is_alpha(&self) -> bool {
    self.alpha != 0
  }

  /// Whether the sample data is signed.
  pub fn is_signed(&self) -> bool {
    self.sgnd != 0
  }

  /// Component data scaled to unsigned 8-bit values (precision-aware).
  #[cfg(feature = "image")]
  pub fn data_u8(&self) -> impl Iterator<Item = u8> + '_ {
    crate::api::image_conv::comp_u8(self)
  }

  /// Component data scaled to unsigned 16-bit values (precision-aware).
  #[cfg(feature = "image")]
  pub fn data_u16(&self) -> impl Iterator<Item = u16> + '_ {
    crate::api::image_conv::comp_u16(self)
  }
}