jxl_oxide/
aux_box.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
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
use std::io::Write;

use brotli_decompressor::DecompressorWriter;
use jxl_bitstream::container::box_header::ContainerBoxType;
use jxl_bitstream::ParseEvent;

use crate::Result;

mod exif;
mod jbrd;

pub use exif::*;
pub use jbrd::*;

#[derive(Debug, Default)]
pub struct AuxBoxReader {
    data: DataKind,
    done: bool,
}

#[derive(Default)]
enum DataKind {
    #[default]
    Init,
    NoData,
    Raw(Vec<u8>),
    Brotli(Box<DecompressorWriter<Vec<u8>>>),
}

impl std::fmt::Debug for DataKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Init => write!(f, "Init"),
            Self::NoData => write!(f, "NoData"),
            Self::Raw(buf) => f
                .debug_tuple("Raw")
                .field(&format_args!("{} byte(s)", buf.len()))
                .finish(),
            Self::Brotli(_) => f.debug_tuple("Brotli").finish(),
        }
    }
}

impl AuxBoxReader {
    pub(super) fn new() -> Self {
        Self::default()
    }

    pub(super) fn ensure_raw(&mut self) {
        if self.done {
            return;
        }

        match self.data {
            DataKind::Init => {
                self.data = DataKind::Raw(Vec::new());
            }
            DataKind::NoData | DataKind::Brotli(_) => {
                panic!();
            }
            DataKind::Raw(_) => {}
        }
    }

    pub(super) fn ensure_brotli(&mut self) -> Result<()> {
        if self.done {
            return Ok(());
        }

        match self.data {
            DataKind::Init => {
                let writer = DecompressorWriter::new(Vec::<u8>::new(), 4096);
                self.data = DataKind::Brotli(Box::new(writer));
            }
            DataKind::NoData | DataKind::Raw(_) => {
                panic!();
            }
            DataKind::Brotli(_) => {}
        }
        Ok(())
    }
}

impl AuxBoxReader {
    pub fn feed_data(&mut self, data: &[u8]) -> Result<()> {
        if self.done {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "cannot feed into finalized box",
            )
            .into());
        }

        match self.data {
            DataKind::Init => {
                self.data = DataKind::Raw(data.to_vec());
            }
            DataKind::NoData => {
                unreachable!();
            }
            DataKind::Raw(ref mut buf) => {
                buf.extend_from_slice(data);
            }
            DataKind::Brotli(ref mut writer) => {
                writer.write_all(data)?;
            }
        }
        Ok(())
    }

    pub fn finalize(&mut self) -> Result<()> {
        if self.done {
            return Ok(());
        }

        if let DataKind::Brotli(ref mut writer) = self.data {
            writer.flush()?;
            writer.close()?;
        }

        match std::mem::replace(&mut self.data, DataKind::NoData) {
            DataKind::Init | DataKind::NoData => {}
            DataKind::Raw(buf) => self.data = DataKind::Raw(buf),
            DataKind::Brotli(writer) => {
                let inner = writer.into_inner().inspect_err(|_| {
                    tracing::warn!("Brotli decompressor reported an error");
                });
                let buf = inner.unwrap_or_else(|buf| buf);
                self.data = DataKind::Raw(buf);
            }
        }

        self.done = true;
        Ok(())
    }
}

impl AuxBoxReader {
    pub fn is_done(&self) -> bool {
        self.done
    }

    pub fn data(&self) -> AuxBoxData<&[u8]> {
        if !self.is_done() {
            return AuxBoxData::Decoding;
        }

        match &self.data {
            DataKind::Init | DataKind::Brotli(_) => AuxBoxData::Decoding,
            DataKind::NoData => AuxBoxData::NotFound,
            DataKind::Raw(buf) => AuxBoxData::Data(buf),
        }
    }
}

/// Auxiliary box data.
pub enum AuxBoxData<T> {
    /// The box has data.
    Data(T),
    /// The box has not been decoded yet.
    Decoding,
    /// The box was not found.
    NotFound,
}

impl<T> std::fmt::Debug for AuxBoxData<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Data(_) => write!(f, "Data(_)"),
            Self::Decoding => write!(f, "Decoding"),
            Self::NotFound => write!(f, "NotFound"),
        }
    }
}

impl<T> AuxBoxData<T> {
    pub fn has_data(&self) -> bool {
        matches!(self, Self::Data(_))
    }

    pub fn is_decoding(&self) -> bool {
        matches!(self, Self::Decoding)
    }

    pub fn is_not_found(&self) -> bool {
        matches!(self, Self::NotFound)
    }

    pub fn unwrap(self) -> T {
        let Self::Data(x) = self else {
            panic!("cannot unwrap `AuxBoxData` which doesn't have any data");
        };
        x
    }

    pub fn unwrap_or(self, or: T) -> T {
        match self {
            Self::Data(x) => x,
            _ => or,
        }
    }

    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> AuxBoxData<U> {
        match self {
            Self::Data(x) => AuxBoxData::Data(f(x)),
            Self::Decoding => AuxBoxData::Decoding,
            Self::NotFound => AuxBoxData::NotFound,
        }
    }

    pub fn as_ref(&self) -> AuxBoxData<&T> {
        match self {
            Self::Data(x) => AuxBoxData::Data(x),
            Self::Decoding => AuxBoxData::Decoding,
            Self::NotFound => AuxBoxData::NotFound,
        }
    }
}

impl<T, E> AuxBoxData<std::result::Result<T, E>> {
    pub fn transpose(self) -> std::result::Result<AuxBoxData<T>, E> {
        match self {
            Self::Data(Ok(x)) => Ok(AuxBoxData::Data(x)),
            Self::Data(Err(e)) => Err(e),
            Self::Decoding => Ok(AuxBoxData::Decoding),
            Self::NotFound => Ok(AuxBoxData::NotFound),
        }
    }
}

/// Auxiliary box list of a JPEG XL container, which may contain Exif and/or XMP metadata.
#[derive(Debug)]
pub struct AuxBoxList {
    boxes: Vec<(ContainerBoxType, AuxBoxReader)>,
    jbrd: Jbrd,
    current_box_ty: Option<ContainerBoxType>,
    current_box: AuxBoxReader,
    last_box: bool,
}

impl AuxBoxList {
    pub(super) fn new() -> Self {
        Self {
            boxes: Vec::new(),
            jbrd: Jbrd::new(),
            current_box_ty: None,
            current_box: AuxBoxReader::new(),
            last_box: false,
        }
    }

    pub(super) fn handle_event(&mut self, event: ParseEvent) -> Result<()> {
        match event {
            ParseEvent::BitstreamKind(_) => {}
            ParseEvent::Codestream(_) => {}
            ParseEvent::NoMoreAuxBox => {
                self.current_box_ty = None;
                self.last_box = true;
            }
            ParseEvent::AuxBoxStart {
                ty,
                brotli_compressed,
                last_box,
            } => {
                self.current_box_ty = Some(ty);
                if ty != ContainerBoxType::JPEG_RECONSTRUCTION {
                    if brotli_compressed {
                        self.current_box.ensure_brotli()?;
                    } else {
                        self.current_box.ensure_raw();
                    }
                }
                self.last_box = last_box;
            }
            ParseEvent::AuxBoxData(ty, buf) => {
                self.current_box_ty = Some(ty);
                if ty == ContainerBoxType::JPEG_RECONSTRUCTION {
                    self.jbrd.feed_bytes(buf)?;
                } else {
                    self.current_box.feed_data(buf)?;
                }
            }
            ParseEvent::AuxBoxEnd(ty) => {
                self.current_box_ty = Some(ty);
                self.finalize()?;
            }
        }
        Ok(())
    }

    fn finalize(&mut self) -> Result<()> {
        match self.current_box_ty {
            Some(ContainerBoxType::JPEG_RECONSTRUCTION) => {
                self.jbrd.finalize()?;
            }
            Some(ty) => {
                self.current_box.finalize()?;
                let finished_box = std::mem::replace(&mut self.current_box, AuxBoxReader::new());
                self.boxes.push((ty, finished_box));
            }
            None => {
                return Ok(());
            }
        }

        self.current_box_ty = None;
        Ok(())
    }

    pub(super) fn eof(&mut self) -> Result<()> {
        self.finalize()?;
        self.last_box = true;
        Ok(())
    }
}

impl AuxBoxList {
    pub(crate) fn jbrd(&self) -> AuxBoxData<&jxl_jbr::JpegBitstreamData> {
        if let Some(data) = self.jbrd.data() {
            AuxBoxData::Data(data)
        } else if self.last_box
            && self.current_box_ty != Some(ContainerBoxType::JPEG_RECONSTRUCTION)
        {
            AuxBoxData::NotFound
        } else {
            AuxBoxData::Decoding
        }
    }

    fn first_of_type(&self, ty: ContainerBoxType) -> AuxBoxData<&[u8]> {
        let maybe = self.boxes.iter().find(|&&(ty_to_test, _)| ty_to_test == ty);
        let data = maybe.map(|(_, b)| b.data());

        if let Some(data) = data {
            data
        } else if self.last_box && self.current_box_ty != Some(ty) {
            AuxBoxData::NotFound
        } else {
            AuxBoxData::Decoding
        }
    }

    /// Returns the first Exif metadata, if any.
    pub fn first_exif(&self) -> Result<AuxBoxData<RawExif>> {
        let exif = self.first_of_type(ContainerBoxType::EXIF);
        exif.map(RawExif::new).transpose()
    }

    /// Returns the first XML metadata, if any.
    pub fn first_xml(&self) -> AuxBoxData<&[u8]> {
        self.first_of_type(ContainerBoxType::XML)
    }
}