Skip to main content

jixel/
iso_gain_map.rs

1/*
2 * // Copyright (c) Radzivon Bartoshyk 9/2026. All rights reserved.
3 * //
4 * // Redistribution and use in source and binary forms, with or without modification,
5 * // are permitted provided that the following conditions are met:
6 * //
7 * // 1.  Redistributions of source code must retain the above copyright notice, this
8 * // list of conditions and the following disclaimer.
9 * //
10 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
11 * // this list of conditions and the following disclaimer in the documentation
12 * // and/or other materials provided with the distribution.
13 * //
14 * // 3.  Neither the name of the copyright holder nor the names of its
15 * // contributors may be used to endorse or promote products derived from
16 * // this software without specific prior written permission.
17 * //
18 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29//! ISO 21496-1 gain map metadata ("the ISO bundle").
30//!
31//! This is the binary metadata blob that a JPEG XL `jhgm` box carries in its
32//! `gain_map_metadata` field (the same blob Ultra HDR JPEGs carry in an APP2
33//! segment). The struct and the parser are ported from
34//! [`gainforge`](https://github.com/awxkee/gainforge); the writer mirrors
35//! libultrahdr's `encodeGainmapMetadata`, so the output parses back with
36//! gainforge, libultrahdr and libjxl-based consumers.
37//!
38//! Every parameter is a rational number `numerator / denominator`, one per
39//! color channel where the standard allows it. Single-channel metadata is
40//! represented by three identical channels (the writer collapses them back
41//! into the single-channel form).
42
43use crate::EncodeError;
44
45/// Binary ISO 21496-1 gain map metadata.
46///
47/// Fields are rationals: `*_n` is the numerator, `*_d` the denominator. Per-
48/// channel arrays hold one value per RGB channel; when all three are equal
49/// the writer emits the compact single-channel form.
50///
51/// Build one with [`IsoGainMap::from_floats`] (from floating-point gain map
52/// parameters) or fill the fields directly; serialize with
53/// [`IsoGainMap::to_metadata`] and parse with [`IsoGainMap::from_metadata`].
54#[repr(C)]
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct IsoGainMap {
57    /// log2 of the minimum gain (per channel).
58    pub gain_map_min_n: [i32; 3],
59    pub gain_map_min_d: [u32; 3],
60    /// log2 of the maximum gain (per channel).
61    pub gain_map_max_n: [i32; 3],
62    pub gain_map_max_d: [u32; 3],
63    /// Gamma applied to the stored gain map samples (per channel).
64    pub gain_map_gamma_n: [u32; 3],
65    pub gain_map_gamma_d: [u32; 3],
66
67    /// Offset added to the base image before applying the gain (per channel).
68    pub base_offset_n: [i32; 3],
69    pub base_offset_d: [u32; 3],
70    /// Offset added to the alternate image before applying the gain (per channel).
71    pub alternate_offset_n: [i32; 3],
72    pub alternate_offset_d: [u32; 3],
73
74    /// log2 of the base image HDR headroom.
75    pub base_hdr_headroom_n: u32,
76    pub base_hdr_headroom_d: u32,
77    /// log2 of the alternate image HDR headroom.
78    pub alternate_hdr_headroom_n: u32,
79    pub alternate_hdr_headroom_d: u32,
80
81    /// True when the gain map maps from the alternate image back to the base.
82    pub backward_direction: bool,
83    /// True when the gain map is applied in the base image color space
84    /// (false: in the alternate image color space).
85    pub use_base_color_space: bool,
86}
87
88impl Default for IsoGainMap {
89    /// Identity gain map: gain 1 everywhere, gamma 1, no offsets, no headroom.
90    fn default() -> Self {
91        Self {
92            gain_map_min_n: [0; 3],
93            gain_map_min_d: [1; 3],
94            gain_map_max_n: [0; 3],
95            gain_map_max_d: [1; 3],
96            gain_map_gamma_n: [1; 3],
97            gain_map_gamma_d: [1; 3],
98            base_offset_n: [0; 3],
99            base_offset_d: [1; 3],
100            alternate_offset_n: [0; 3],
101            alternate_offset_d: [1; 3],
102            base_hdr_headroom_n: 0,
103            base_hdr_headroom_d: 1,
104            alternate_hdr_headroom_n: 0,
105            alternate_hdr_headroom_d: 1,
106            backward_direction: false,
107            use_base_color_space: true,
108        }
109    }
110}
111
112/// Floating-point gain map parameters, the convenient way to build an
113/// [`IsoGainMap`]. Per-channel arrays are `[R, G, B]`; pass three identical
114/// values for a single-channel (luminance) gain map.
115///
116/// The values follow the ISO 21496-1 / Ultra HDR conventions:
117/// `min`/`max` are `log2` of the smallest/largest gain in the map,
118/// `base_hdr_headroom`/`alternate_hdr_headroom` are `log2` of each rendition's
119/// headroom (`0.0` for an SDR base), offsets are in normalised `0..1` units.
120#[derive(Debug, Clone, Copy, PartialEq)]
121pub struct GainMapFloats {
122    pub min: [f32; 3],
123    pub max: [f32; 3],
124    pub gamma: [f32; 3],
125    pub base_offset: [f32; 3],
126    pub alternate_offset: [f32; 3],
127    pub base_hdr_headroom: f32,
128    pub alternate_hdr_headroom: f32,
129    pub backward_direction: bool,
130    pub use_base_color_space: bool,
131}
132
133impl Default for GainMapFloats {
134    /// Identity gain map, gamma 1, Ultra HDR default offsets (1/64).
135    fn default() -> Self {
136        Self {
137            min: [0.0; 3],
138            max: [0.0; 3],
139            gamma: [1.0; 3],
140            base_offset: [1.0 / 64.0; 3],
141            alternate_offset: [1.0 / 64.0; 3],
142            base_hdr_headroom: 0.0,
143            alternate_hdr_headroom: 0.0,
144            backward_direction: false,
145            use_base_color_space: true,
146        }
147    }
148}
149
150const IS_MULTICHANNEL_MASK: u8 = 1 << 7;
151const USE_BASE_COLORSPACE_MASK: u8 = 1 << 6;
152const BACKWARD_DIRECTION_MASK: u8 = 1 << 2;
153const USE_COMMON_DENOMINATOR_MASK: u8 = 1 << 3;
154
155fn bad(msg: &'static str) -> EncodeError {
156    EncodeError::InvalidGainMapMetadata(msg)
157}
158
159fn read_u32(arr: &[u8], pos: &mut usize) -> Result<u32, EncodeError> {
160    let s = arr
161        .get(*pos..*pos + 4)
162        .ok_or_else(|| bad("gain map metadata truncated"))?;
163    *pos += 4;
164    Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
165}
166
167fn read_s32(arr: &[u8], pos: &mut usize) -> Result<i32, EncodeError> {
168    read_u32(arr, pos).map(|v| v as i32)
169}
170
171/// Continued-fraction approximation of `v` as `n/d` with `n <= max_numerator`
172/// (ported from gainforge / libultrahdr).
173fn float_to_unsigned_fraction_impl(v: f32, max_numerator: u32) -> Option<(u32, u32)> {
174    if v.is_nan() || v < 0.0 || v > max_numerator as f32 {
175        return None;
176    }
177
178    let max_d = if v <= 1.0 {
179        u32::MAX as u64
180    } else {
181        (max_numerator as f64 / v.floor() as f64) as u64
182    };
183
184    let mut denominator: u32 = 1;
185    let mut previous_d: u32 = 0;
186    let mut current_v = v.fract() as f64;
187    let max_iter = 39;
188
189    for _ in 0..max_iter {
190        let numerator_double = (denominator as f64) * (v as f64);
191        if numerator_double > max_numerator as f64 {
192            return None;
193        }
194
195        let numerator = numerator_double.round() as u32;
196        if (numerator_double - numerator as f64).abs() == 0.0 {
197            return Some((numerator, denominator));
198        }
199
200        current_v = 1.0 / current_v;
201        let new_d = previous_d as u64 + (current_v.floor() as u64) * (denominator as u64);
202        if new_d > max_d {
203            return Some((numerator, denominator));
204        }
205
206        previous_d = denominator;
207        if new_d > u32::MAX as u64 {
208            return None;
209        }
210
211        denominator = new_d as u32;
212        current_v -= current_v.floor();
213    }
214
215    let numerator = ((denominator as f64) * (v as f64)).round() as u32;
216    Some((numerator, denominator))
217}
218
219/// Approximate `v` as a signed rational `n/d` (`|n| <= i32::MAX`).
220pub(crate) fn float_to_signed_fraction(v: f32) -> Option<(i32, u32)> {
221    let (numerator, denominator) = float_to_unsigned_fraction_impl(v.abs(), i32::MAX as u32)?;
222    let mut n = numerator as i32;
223    if v < 0.0 {
224        n = -n;
225    }
226    Some((n, denominator))
227}
228
229/// Approximate a non-negative `v` as an unsigned rational `n/d`.
230pub(crate) fn float_to_unsigned_fraction(v: f32) -> Option<(u32, u32)> {
231    float_to_unsigned_fraction_impl(v, i32::MAX as u32)
232}
233
234impl IsoGainMap {
235    /// Build the metadata from floating-point parameters, converting every
236    /// value to a rational. Fails when a value is NaN, negative where the
237    /// standard requires a non-negative number (gamma, headroom, offsets when
238    /// unsigned), or too large to represent.
239    pub fn from_floats(v: &GainMapFloats) -> Result<Self, EncodeError> {
240        let mut m = IsoGainMap {
241            backward_direction: v.backward_direction,
242            use_base_color_space: v.use_base_color_space,
243            ..IsoGainMap::default()
244        };
245        for c in 0..3 {
246            (m.gain_map_min_n[c], m.gain_map_min_d[c]) =
247                float_to_signed_fraction(v.min[c]).ok_or_else(|| bad("gain map min"))?;
248            (m.gain_map_max_n[c], m.gain_map_max_d[c]) =
249                float_to_signed_fraction(v.max[c]).ok_or_else(|| bad("gain map max"))?;
250            if v.gamma[c].is_nan() || v.gamma[c] <= 0.0 {
251                return Err(bad("gain map gamma must be positive"));
252            }
253            (m.gain_map_gamma_n[c], m.gain_map_gamma_d[c]) =
254                float_to_unsigned_fraction(v.gamma[c]).ok_or_else(|| bad("gain map gamma"))?;
255            (m.base_offset_n[c], m.base_offset_d[c]) =
256                float_to_signed_fraction(v.base_offset[c]).ok_or_else(|| bad("base offset"))?;
257            (m.alternate_offset_n[c], m.alternate_offset_d[c]) =
258                float_to_signed_fraction(v.alternate_offset[c])
259                    .ok_or_else(|| bad("alternate offset"))?;
260        }
261        (m.base_hdr_headroom_n, m.base_hdr_headroom_d) =
262            float_to_unsigned_fraction(v.base_hdr_headroom)
263                .ok_or_else(|| bad("base HDR headroom must be a finite non-negative number"))?;
264        (m.alternate_hdr_headroom_n, m.alternate_hdr_headroom_d) =
265            float_to_unsigned_fraction(v.alternate_hdr_headroom).ok_or_else(|| {
266                bad("alternate HDR headroom must be a finite non-negative number")
267            })?;
268        Ok(m)
269    }
270
271    /// Floating-point view of the parameters.
272    pub fn to_floats(&self) -> GainMapFloats {
273        let f = |n: i32, d: u32| n as f32 / d as f32;
274        let u = |n: u32, d: u32| n as f32 / d as f32;
275        let arr = |n: &[i32; 3], d: &[u32; 3]| [f(n[0], d[0]), f(n[1], d[1]), f(n[2], d[2])];
276        GainMapFloats {
277            min: arr(&self.gain_map_min_n, &self.gain_map_min_d),
278            max: arr(&self.gain_map_max_n, &self.gain_map_max_d),
279            gamma: [
280                u(self.gain_map_gamma_n[0], self.gain_map_gamma_d[0]),
281                u(self.gain_map_gamma_n[1], self.gain_map_gamma_d[1]),
282                u(self.gain_map_gamma_n[2], self.gain_map_gamma_d[2]),
283            ],
284            base_offset: arr(&self.base_offset_n, &self.base_offset_d),
285            alternate_offset: arr(&self.alternate_offset_n, &self.alternate_offset_d),
286            base_hdr_headroom: u(self.base_hdr_headroom_n, self.base_hdr_headroom_d),
287            alternate_hdr_headroom: u(self.alternate_hdr_headroom_n, self.alternate_hdr_headroom_d),
288            backward_direction: self.backward_direction,
289            use_base_color_space: self.use_base_color_space,
290        }
291    }
292
293    /// True when at least one per-channel parameter differs between channels,
294    /// i.e. the metadata must be written in the three-channel form.
295    pub fn is_multichannel(&self) -> bool {
296        let same = |n: &[i32; 3], d: &[u32; 3]| {
297            n[0] == n[1] && n[1] == n[2] && d[0] == d[1] && d[1] == d[2]
298        };
299        let same_u = |n: &[u32; 3], d: &[u32; 3]| {
300            n[0] == n[1] && n[1] == n[2] && d[0] == d[1] && d[1] == d[2]
301        };
302        !(same(&self.gain_map_min_n, &self.gain_map_min_d)
303            && same(&self.gain_map_max_n, &self.gain_map_max_d)
304            && same_u(&self.gain_map_gamma_n, &self.gain_map_gamma_d)
305            && same(&self.base_offset_n, &self.base_offset_d)
306            && same(&self.alternate_offset_n, &self.alternate_offset_d))
307    }
308
309    /// The common denominator, if every rational in the (written) channels
310    /// shares one; the writer then uses the compact common-denominator form.
311    fn common_denominator(&self, channels: usize) -> Option<u32> {
312        let d = self.base_hdr_headroom_d;
313        if d == 0 || self.alternate_hdr_headroom_d != d {
314            return None;
315        }
316        for c in 0..channels {
317            if self.gain_map_min_d[c] != d
318                || self.gain_map_max_d[c] != d
319                || self.gain_map_gamma_d[c] != d
320                || self.base_offset_d[c] != d
321                || self.alternate_offset_d[c] != d
322            {
323                return None;
324            }
325        }
326        Some(d)
327    }
328
329    /// Validate the rationals (no zero denominators).
330    fn validate(&self) -> Result<(), EncodeError> {
331        if self.base_hdr_headroom_d == 0 || self.alternate_hdr_headroom_d == 0 {
332            return Err(bad("zero denominator in HDR headroom"));
333        }
334        for c in 0..3 {
335            if self.gain_map_min_d[c] == 0
336                || self.gain_map_max_d[c] == 0
337                || self.gain_map_gamma_d[c] == 0
338                || self.base_offset_d[c] == 0
339                || self.alternate_offset_d[c] == 0
340            {
341                return Err(bad("zero denominator in per-channel gain map parameter"));
342            }
343            if self.gain_map_gamma_n[c] == 0 {
344                return Err(bad("gain map gamma must be non-zero"));
345            }
346        }
347        Ok(())
348    }
349
350    /// serialize to the ISO 21496-1 binary layout (big-endian):
351    ///
352    /// ```text
353    /// u16 minimum_version = 0
354    /// u16 writer_version  = 0
355    /// u8  flags: bit7 multichannel, bit6 use_base_color_space,
356    ///            bit2 backward_direction, bit3 common denominator
357    /// [u32 common_denominator]
358    /// base_hdr_headroom, alternate_hdr_headroom
359    /// per channel (1 or 3): min, max, gamma, base_offset, alternate_offset
360    /// ```
361    ///
362    /// Each rational is `n` alone in the common-denominator form, or `n, d`
363    /// otherwise. Single-channel form is used when all three channels agree.
364    pub fn to_metadata(&self) -> Result<Vec<u8>, EncodeError> {
365        self.validate()?;
366        let channels = if self.is_multichannel() { 3 } else { 1 };
367        let common = self.common_denominator(channels);
368
369        let mut flags = 0u8;
370        if channels == 3 {
371            flags |= IS_MULTICHANNEL_MASK;
372        }
373        if self.use_base_color_space {
374            flags |= USE_BASE_COLORSPACE_MASK;
375        }
376        if self.backward_direction {
377            flags |= BACKWARD_DIRECTION_MASK;
378        }
379        if common.is_some() {
380            flags |= USE_COMMON_DENOMINATOR_MASK;
381        }
382
383        let mut out = Vec::with_capacity(5 + 4 + 16 + 40 * channels);
384        out.extend_from_slice(&0u16.to_be_bytes()); // minimum_version
385        out.extend_from_slice(&0u16.to_be_bytes()); // writer_version
386        out.push(flags);
387
388        let put_u32 = |out: &mut Vec<u8>, v: u32| out.extend_from_slice(&v.to_be_bytes());
389        let put_s32 = |out: &mut Vec<u8>, v: i32| out.extend_from_slice(&v.to_be_bytes());
390
391        if let Some(d) = common {
392            put_u32(&mut out, d);
393            put_u32(&mut out, self.base_hdr_headroom_n);
394            put_u32(&mut out, self.alternate_hdr_headroom_n);
395            for c in 0..channels {
396                put_s32(&mut out, self.gain_map_min_n[c]);
397                put_s32(&mut out, self.gain_map_max_n[c]);
398                put_u32(&mut out, self.gain_map_gamma_n[c]);
399                put_s32(&mut out, self.base_offset_n[c]);
400                put_s32(&mut out, self.alternate_offset_n[c]);
401            }
402        } else {
403            put_u32(&mut out, self.base_hdr_headroom_n);
404            put_u32(&mut out, self.base_hdr_headroom_d);
405            put_u32(&mut out, self.alternate_hdr_headroom_n);
406            put_u32(&mut out, self.alternate_hdr_headroom_d);
407            for c in 0..channels {
408                put_s32(&mut out, self.gain_map_min_n[c]);
409                put_u32(&mut out, self.gain_map_min_d[c]);
410                put_s32(&mut out, self.gain_map_max_n[c]);
411                put_u32(&mut out, self.gain_map_max_d[c]);
412                put_u32(&mut out, self.gain_map_gamma_n[c]);
413                put_u32(&mut out, self.gain_map_gamma_d[c]);
414                put_s32(&mut out, self.base_offset_n[c]);
415                put_u32(&mut out, self.base_offset_d[c]);
416                put_s32(&mut out, self.alternate_offset_n[c]);
417                put_u32(&mut out, self.alternate_offset_d[c]);
418            }
419        }
420        Ok(out)
421    }
422
423    /// Parse the ISO 21496-1 binary layout written by [`IsoGainMap::to_metadata`]
424    /// (or by libultrahdr / any Ultra HDR encoder). Single-channel metadata is
425    /// expanded to three identical channels.
426    pub fn from_metadata(in_data: &[u8]) -> Result<Self, EncodeError> {
427        if in_data.len() < 5 {
428            return Err(bad("gain map metadata too short"));
429        }
430
431        let mut pos = 0;
432        let min_version = u16::from_be_bytes([in_data[0], in_data[1]]);
433        pos += 2;
434        if min_version != 0 {
435            return Err(bad("unsupported gain map metadata minimum version"));
436        }
437        pos += 2; // writer_version: informational only
438
439        let flags = in_data[pos];
440        pos += 1;
441        let channel_count = if (flags & IS_MULTICHANNEL_MASK) != 0 {
442            3
443        } else {
444            1
445        };
446
447        let mut m = IsoGainMap {
448            use_base_color_space: (flags & USE_BASE_COLORSPACE_MASK) != 0,
449            backward_direction: (flags & BACKWARD_DIRECTION_MASK) != 0,
450            ..IsoGainMap::default()
451        };
452        let use_common_denominator = (flags & USE_COMMON_DENOMINATOR_MASK) != 0;
453
454        if use_common_denominator {
455            let d = read_u32(in_data, &mut pos)?;
456            m.base_hdr_headroom_n = read_u32(in_data, &mut pos)?;
457            m.base_hdr_headroom_d = d;
458            m.alternate_hdr_headroom_n = read_u32(in_data, &mut pos)?;
459            m.alternate_hdr_headroom_d = d;
460
461            for c in 0..channel_count {
462                m.gain_map_min_n[c] = read_s32(in_data, &mut pos)?;
463                m.gain_map_min_d[c] = d;
464                m.gain_map_max_n[c] = read_s32(in_data, &mut pos)?;
465                m.gain_map_max_d[c] = d;
466                m.gain_map_gamma_n[c] = read_u32(in_data, &mut pos)?;
467                m.gain_map_gamma_d[c] = d;
468                m.base_offset_n[c] = read_s32(in_data, &mut pos)?;
469                m.base_offset_d[c] = d;
470                m.alternate_offset_n[c] = read_s32(in_data, &mut pos)?;
471                m.alternate_offset_d[c] = d;
472            }
473        } else {
474            m.base_hdr_headroom_n = read_u32(in_data, &mut pos)?;
475            m.base_hdr_headroom_d = read_u32(in_data, &mut pos)?;
476            m.alternate_hdr_headroom_n = read_u32(in_data, &mut pos)?;
477            m.alternate_hdr_headroom_d = read_u32(in_data, &mut pos)?;
478
479            for c in 0..channel_count {
480                m.gain_map_min_n[c] = read_s32(in_data, &mut pos)?;
481                m.gain_map_min_d[c] = read_u32(in_data, &mut pos)?;
482                m.gain_map_max_n[c] = read_s32(in_data, &mut pos)?;
483                m.gain_map_max_d[c] = read_u32(in_data, &mut pos)?;
484                m.gain_map_gamma_n[c] = read_u32(in_data, &mut pos)?;
485                m.gain_map_gamma_d[c] = read_u32(in_data, &mut pos)?;
486                m.base_offset_n[c] = read_s32(in_data, &mut pos)?;
487                m.base_offset_d[c] = read_u32(in_data, &mut pos)?;
488                m.alternate_offset_n[c] = read_s32(in_data, &mut pos)?;
489                m.alternate_offset_d[c] = read_u32(in_data, &mut pos)?;
490            }
491        }
492
493        for c in channel_count..3 {
494            m.gain_map_min_n[c] = m.gain_map_min_n[0];
495            m.gain_map_min_d[c] = m.gain_map_min_d[0];
496            m.gain_map_max_n[c] = m.gain_map_max_n[0];
497            m.gain_map_max_d[c] = m.gain_map_max_d[0];
498            m.gain_map_gamma_n[c] = m.gain_map_gamma_n[0];
499            m.gain_map_gamma_d[c] = m.gain_map_gamma_d[0];
500            m.base_offset_n[c] = m.base_offset_n[0];
501            m.base_offset_d[c] = m.base_offset_d[0];
502            m.alternate_offset_n[c] = m.alternate_offset_n[0];
503            m.alternate_offset_d[c] = m.alternate_offset_d[0];
504        }
505
506        m.validate()?;
507        Ok(m)
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514
515    fn sample_floats() -> GainMapFloats {
516        GainMapFloats {
517            min: [-0.5, -0.25, 0.0],
518            max: [2.0, 2.5, 3.0],
519            gamma: [1.0, 1.2, 0.8],
520            base_offset: [1.0 / 64.0; 3],
521            alternate_offset: [1.0 / 64.0; 3],
522            base_hdr_headroom: 0.0,
523            alternate_hdr_headroom: 2.32,
524            backward_direction: false,
525            use_base_color_space: true,
526        }
527    }
528
529    #[test]
530    fn multichannel_round_trip_is_exact() {
531        let m = IsoGainMap::from_floats(&sample_floats()).unwrap();
532        assert!(m.is_multichannel());
533        let bytes = m.to_metadata().unwrap();
534        // 5 header + 4*4 headroom + 3 channels * 10 u32.
535        assert_eq!(bytes.len(), 5 + 16 + 3 * 40);
536        assert_eq!(bytes[4] & IS_MULTICHANNEL_MASK, IS_MULTICHANNEL_MASK);
537        let back = IsoGainMap::from_metadata(&bytes).unwrap();
538        assert_eq!(back, m);
539    }
540
541    #[test]
542    fn single_channel_uses_compact_common_denominator_form() {
543        let m = IsoGainMap {
544            gain_map_min_n: [-2; 3],
545            gain_map_max_n: [6; 3],
546            gain_map_gamma_n: [4; 3],
547            base_offset_n: [0; 3],
548            alternate_offset_n: [0; 3],
549            gain_map_min_d: [4; 3],
550            gain_map_max_d: [4; 3],
551            gain_map_gamma_d: [4; 3],
552            base_offset_d: [4; 3],
553            alternate_offset_d: [4; 3],
554            base_hdr_headroom_n: 0,
555            base_hdr_headroom_d: 4,
556            alternate_hdr_headroom_n: 8,
557            alternate_hdr_headroom_d: 4,
558            backward_direction: true,
559            use_base_color_space: false,
560        };
561        assert!(!m.is_multichannel());
562        let bytes = m.to_metadata().unwrap();
563        // 5 header + common denominator + 2 headroom numerators + 5 numerators.
564        assert_eq!(bytes.len(), 5 + 4 + 8 + 20);
565        assert_eq!(bytes[..4], [0, 0, 0, 0]);
566        assert_eq!(
567            bytes[4],
568            BACKWARD_DIRECTION_MASK | USE_COMMON_DENOMINATOR_MASK
569        );
570        let back = IsoGainMap::from_metadata(&bytes).unwrap();
571        assert_eq!(back, m);
572        let f = back.to_floats();
573        assert_eq!(f.min, [-0.5; 3]);
574        assert_eq!(f.max, [1.5; 3]);
575        assert_eq!(f.alternate_hdr_headroom, 2.0);
576        assert!(f.backward_direction);
577        assert!(!f.use_base_color_space);
578    }
579
580    #[test]
581    fn floats_survive_the_rational_round_trip() {
582        let f = sample_floats();
583        let back = IsoGainMap::from_floats(&f).unwrap().to_floats();
584        for c in 0..3 {
585            assert!((back.min[c] - f.min[c]).abs() < 1e-6);
586            assert!((back.max[c] - f.max[c]).abs() < 1e-6);
587            assert!((back.gamma[c] - f.gamma[c]).abs() < 1e-6);
588            assert!((back.base_offset[c] - f.base_offset[c]).abs() < 1e-6);
589        }
590        assert!((back.alternate_hdr_headroom - f.alternate_hdr_headroom).abs() < 1e-6);
591    }
592
593    #[test]
594    fn rejects_bad_floats() {
595        let f = GainMapFloats {
596            gamma: [1.0, 0.0, 1.0],
597            ..GainMapFloats::default()
598        };
599        assert!(IsoGainMap::from_floats(&f).is_err());
600        let f = GainMapFloats {
601            base_hdr_headroom: -1.0,
602            ..GainMapFloats::default()
603        };
604        assert!(IsoGainMap::from_floats(&f).is_err());
605        let f = GainMapFloats {
606            min: [f32::NAN, 0.0, 0.0],
607            ..GainMapFloats::default()
608        };
609        assert!(IsoGainMap::from_floats(&f).is_err());
610    }
611
612    #[test]
613    fn rejects_truncated_and_wrong_version() {
614        let m = IsoGainMap::from_floats(&sample_floats()).unwrap();
615        let bytes = m.to_metadata().unwrap();
616        assert!(IsoGainMap::from_metadata(&bytes[..bytes.len() - 1]).is_err());
617        let mut v = bytes.clone();
618        v[1] = 1;
619        assert!(IsoGainMap::from_metadata(&v).is_err());
620        let mut zero = IsoGainMap::default();
621        zero.gain_map_min_d[0] = 0;
622        assert!(zero.to_metadata().is_err());
623    }
624
625    #[test]
626    fn parses_libultrahdr_style_single_channel_blob() {
627        // Hand-assembled: version 0/0, flags = use_base_color_space only,
628        // explicit denominators, one channel.
629        let mut b = vec![0, 0, 0, 0, USE_BASE_COLORSPACE_MASK];
630        let mut u = |v: u32| b.extend_from_slice(&v.to_be_bytes());
631        u(0);
632        u(1); // base headroom 0/1
633        u(3);
634        u(1); // alt headroom 3/1
635        u(0u32.wrapping_sub(1));
636        u(2); // min -1/2
637        u(3);
638        u(1); // max 3/1
639        u(1);
640        u(1); // gamma 1/1
641        u(1);
642        u(64); // base offset 1/64
643        u(1);
644        u(64); // alt offset 1/64
645        let m = IsoGainMap::from_metadata(&b).unwrap();
646        assert_eq!(m.gain_map_min_n, [-1; 3]);
647        assert_eq!(m.gain_map_min_d, [2; 3]);
648        assert_eq!(m.gain_map_max_n, [3; 3]);
649        assert_eq!(m.alternate_hdr_headroom_n, 3);
650        assert!(m.use_base_color_space);
651        assert!(!m.backward_direction);
652        assert_eq!(m.to_metadata().unwrap(), b);
653    }
654}