jxl_frame/data/
patch.rs

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
use jxl_bitstream::{unpack_signed, Bitstream};
use jxl_image::ImageHeader;
use jxl_oxide_common::Bundle;

use crate::{FrameHeader, Result};

#[derive(Debug)]
pub struct Patches {
    pub patches: Vec<PatchRef>,
}

#[derive(Debug)]
pub struct PatchRef {
    pub ref_idx: u32,
    pub x0: u32,
    pub y0: u32,
    pub width: u32,
    pub height: u32,
    pub patch_targets: Vec<PatchTarget>,
}

#[derive(Debug)]
pub struct PatchTarget {
    pub x: i32,
    pub y: i32,
    pub blending: Vec<BlendingModeInformation>,
}

#[derive(Debug)]
pub struct BlendingModeInformation {
    pub mode: PatchBlendMode,
    pub alpha_channel: u32,
    pub clamp: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PatchBlendMode {
    None = 0,
    Replace,
    Add,
    Mul,
    BlendAbove,
    BlendBelow,
    MulAddAbove,
    MulAddBelow,
}

impl TryFrom<u32> for PatchBlendMode {
    type Error = jxl_bitstream::Error;

    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        use PatchBlendMode::*;

        Ok(match value {
            0 => PatchBlendMode::None,
            1 => Replace,
            2 => Add,
            3 => Mul,
            4 => BlendAbove,
            5 => BlendBelow,
            6 => MulAddAbove,
            7 => MulAddBelow,
            _ => {
                return Err(jxl_bitstream::Error::InvalidEnum {
                    name: "PatchBlendMode",
                    value,
                })
            }
        })
    }
}

impl PatchBlendMode {
    #[inline]
    pub fn use_alpha(self) -> bool {
        matches!(
            self,
            Self::BlendAbove | Self::BlendBelow | Self::MulAddAbove | Self::MulAddBelow
        )
    }
}

impl Bundle<(&ImageHeader, &FrameHeader)> for Patches {
    type Error = crate::Error;

    fn parse(
        bitstream: &mut Bitstream,
        (image_header, frame_header): (&ImageHeader, &FrameHeader),
    ) -> Result<Self> {
        let num_extra = image_header.metadata.ec_info.len();
        let alpha_channel_indices = image_header
            .metadata
            .ec_info
            .iter()
            .enumerate()
            .filter_map(|(idx, info)| info.is_alpha().then_some(idx as u32))
            .collect::<Vec<_>>();

        let mut decoder = jxl_coding::Decoder::parse(bitstream, 10)?;
        decoder.begin(bitstream)?;

        let frame_width = frame_header.width;
        let frame_height = frame_header.height;
        let max_num_patch_refs =
            (1 << 24).min((frame_width as u64 * frame_height as u64 / 16) as u32);
        let max_num_patches = max_num_patch_refs * 4; // from libjxl limits

        let num_patch_refs = decoder.read_varint(bitstream, 0)?;
        tracing::trace!(num_patch_refs, "Patch ref");
        if num_patch_refs > max_num_patch_refs {
            tracing::error!(num_patch_refs, max_num_patch_refs, "Too many patches");
            return Err(jxl_bitstream::Error::ProfileConformance("too many patches").into());
        }

        let mut total_patches = 0u32;
        let patches = std::iter::repeat_with(|| -> Result<_> {
            let ref_idx = decoder.read_varint(bitstream, 1)?;
            if ref_idx >= 4 {
                tracing::error!(ref_idx, "PatchRef index out of bounds");
                return Err(
                    jxl_bitstream::Error::ValidationFailed("PatchRef index out of bounds").into(),
                );
            }
            let x0 = decoder.read_varint(bitstream, 3)?;
            let y0 = decoder.read_varint(bitstream, 3)?;
            let width = decoder.read_varint(bitstream, 2)? + 1;
            let height = decoder.read_varint(bitstream, 2)? + 1;
            let count = decoder.read_varint(bitstream, 7)? + 1;
            tracing::trace!(ref_idx, x0, y0, width, height, count, "Patch target");

            total_patches += count;
            if total_patches > max_num_patches {
                tracing::error!(total_patches, max_num_patches, "Too many patches");
                return Err(jxl_bitstream::Error::ProfileConformance("too many patches").into());
            }

            let mut prev_xy = None;
            let patch_targets = std::iter::repeat_with(|| -> Result<_> {
                let (x, y) = if let Some((px, py)) = prev_xy {
                    let dx = decoder.read_varint(bitstream, 6)?;
                    let dy = decoder.read_varint(bitstream, 6)?;
                    let dx = unpack_signed(dx);
                    let dy = unpack_signed(dy);
                    let x = dx.checked_add(px);
                    let y = dy.checked_add(py);
                    let (Some(x), Some(y)) = (x, y) else {
                        tracing::error!(px, py, dx, dy, "Patch coord overflow");
                        return Err(
                            jxl_bitstream::Error::ValidationFailed("patch coord overflow").into(),
                        );
                    };
                    (x, y)
                } else {
                    (
                        decoder.read_varint(bitstream, 4)? as i32,
                        decoder.read_varint(bitstream, 4)? as i32,
                    )
                };
                prev_xy = Some((x, y));

                let blending = std::iter::repeat_with(|| -> Result<_> {
                    let raw_mode = decoder.read_varint(bitstream, 5)?;
                    let mode = PatchBlendMode::try_from(raw_mode)?;
                    let alpha_channel = if raw_mode >= 4 && alpha_channel_indices.len() >= 2 {
                        decoder.read_varint(bitstream, 8)?
                    } else {
                        alpha_channel_indices.first().copied().unwrap_or_default()
                    };
                    let clamp = if raw_mode >= 3 {
                        decoder.read_varint(bitstream, 9)? != 0
                    } else {
                        false
                    };

                    Ok(BlendingModeInformation {
                        mode,
                        alpha_channel,
                        clamp,
                    })
                })
                .take(num_extra + 1)
                .collect::<Result<Vec<_>>>()?;

                Ok(PatchTarget { x, y, blending })
            })
            .take(count as usize)
            .collect::<Result<Vec<_>>>()?;

            Ok(PatchRef {
                ref_idx,
                x0,
                y0,
                width,
                height,
                patch_targets,
            })
        })
        .take(num_patch_refs as usize)
        .collect::<Result<Vec<_>>>()?;

        decoder.finalize()?;
        Ok(Self { patches })
    }
}