j2k-jpeg 0.6.1

JPEG inspect/decode and fallback encode support for j2k
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
// SPDX-License-Identifier: Apache-2.0

use crate::decoder::Decoder;
use crate::error::{JpegError, MarkerKind};
use crate::info::{ColorSpace, SamplingFactors, SofKind};
use crate::internal::checkpoint::{build_checkpoint_plan, DeviceCheckpoint};
use crate::parse::header::parse_header;
use crate::parse::scan::ScanComponent;
use crate::parse::tables::RawHuffmanTable;
use alloc::vec::Vec;

const MAX_NONRESTART_ENTROPY_CHECKPOINTS: u32 = 2048;

#[derive(Debug, Clone, PartialEq, Eq)]
/// Error while building a backend fast-path JPEG packet.
pub enum FastPacketError {
    /// Header or entropy decode failed.
    Decode(JpegError),
    /// JPEG SOF kind is not supported by the fast path.
    UnsupportedSof(SofKind),
    /// JPEG color space is not supported by the selected fast path.
    UnsupportedColorSpace(ColorSpace),
    /// JPEG component sampling does not match the selected fast path.
    UnsupportedSampling,
    /// Scan component order does not match SOF component order.
    UnsupportedComponentOrder,
    /// Stream does not contain a scan payload.
    MissingScan,
    /// Referenced quantization table is absent.
    MissingQuantTable {
        /// Quantization table slot.
        slot: u8,
    },
    /// Referenced Huffman table is absent.
    MissingHuffmanTable {
        /// Huffman table class.
        kind: TableKind,
        /// Huffman table slot.
        slot: u8,
    },
    /// Entropy payload contains a marker unsupported by the fast path.
    EntropyMarkerUnsupported {
        /// Raw marker byte following `0xff`.
        marker: u8,
    },
    /// Entropy payload ended before the packet could be built.
    TruncatedEntropy,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Huffman table class used by fast-path packet builders.
pub enum TableKind {
    /// DC Huffman table.
    Dc,
    /// AC Huffman table.
    Ac,
}

impl From<JpegError> for FastPacketError {
    fn from(value: JpegError) -> Self {
        Self::Decode(value)
    }
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Huffman table payload copied into backend-compatible packet structs.
pub struct JpegHuffmanTable {
    /// JPEG BITS counts for code lengths 1 through 16.
    pub bits: [u8; 16],
    /// Number of populated entries in `values`.
    pub values_len: u16,
    /// JPEG HUFFVAL symbols padded to fixed capacity.
    pub values: [u8; 256],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Entropy decoder resume point for fast-path packet decoding.
pub struct JpegEntropyCheckpointV1 {
    /// MCU index for this checkpoint.
    pub mcu_index: u32,
    /// Byte offset into the entropy payload.
    pub entropy_pos: u32,
    /// Buffered entropy bits.
    pub bit_acc: u64,
    /// Number of valid bits in `bit_acc`.
    pub bit_count: u32,
    /// Previous Y DC predictor.
    pub y_prev_dc: i32,
    /// Previous Cb DC predictor.
    pub cb_prev_dc: i32,
    /// Previous Cr DC predictor.
    pub cr_prev_dc: i32,
    /// Reserved for ABI-compatible future expansion.
    pub reserved: u32,
}

impl JpegHuffmanTable {
    fn from_raw(raw: &RawHuffmanTable) -> Self {
        let mut values = [0u8; 256];
        let slice = raw.values.as_slice();
        values[..slice.len()].copy_from_slice(slice);
        Self {
            bits: raw.bits,
            values_len: slice.len() as u16,
            values,
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Backend fast-path packet for 8-bit 4:2:0 JPEG tiles.
pub struct JpegFast420PacketV1 {
    /// Image dimensions as `(width, height)` in pixels.
    pub dimensions: (u32, u32),
    /// Number of MCUs per row.
    pub mcus_per_row: u32,
    /// Number of MCU rows.
    pub mcu_rows: u32,
    /// Restart interval in MCUs, or zero when absent.
    pub restart_interval_mcus: u32,
    /// Byte offsets of restart-addressable entropy segments.
    pub restart_offsets: Vec<u32>,
    /// Entropy resume checkpoints.
    pub entropy_checkpoints: Vec<JpegEntropyCheckpointV1>,
    /// Y quantization table in natural order.
    pub y_quant: [u16; 64],
    /// Cb quantization table in natural order.
    pub cb_quant: [u16; 64],
    /// Cr quantization table in natural order.
    pub cr_quant: [u16; 64],
    /// Y DC Huffman table.
    pub y_dc_table: JpegHuffmanTable,
    /// Y AC Huffman table.
    pub y_ac_table: JpegHuffmanTable,
    /// Cb DC Huffman table.
    pub cb_dc_table: JpegHuffmanTable,
    /// Cb AC Huffman table.
    pub cb_ac_table: JpegHuffmanTable,
    /// Cr DC Huffman table.
    pub cr_dc_table: JpegHuffmanTable,
    /// Cr AC Huffman table.
    pub cr_ac_table: JpegHuffmanTable,
    /// Entropy-coded scan bytes.
    pub entropy_bytes: Vec<u8>,
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Backend fast-path packet for 8-bit 4:2:2 JPEG tiles.
pub struct JpegFast422PacketV1 {
    /// Image dimensions as `(width, height)` in pixels.
    pub dimensions: (u32, u32),
    /// Number of MCUs per row.
    pub mcus_per_row: u32,
    /// Number of MCU rows.
    pub mcu_rows: u32,
    /// Restart interval in MCUs, or zero when absent.
    pub restart_interval_mcus: u32,
    /// Byte offsets of restart-addressable entropy segments.
    pub restart_offsets: Vec<u32>,
    /// Entropy resume checkpoints.
    pub entropy_checkpoints: Vec<JpegEntropyCheckpointV1>,
    /// Y quantization table in natural order.
    pub y_quant: [u16; 64],
    /// Cb quantization table in natural order.
    pub cb_quant: [u16; 64],
    /// Cr quantization table in natural order.
    pub cr_quant: [u16; 64],
    /// Y DC Huffman table.
    pub y_dc_table: JpegHuffmanTable,
    /// Y AC Huffman table.
    pub y_ac_table: JpegHuffmanTable,
    /// Cb DC Huffman table.
    pub cb_dc_table: JpegHuffmanTable,
    /// Cb AC Huffman table.
    pub cb_ac_table: JpegHuffmanTable,
    /// Cr DC Huffman table.
    pub cr_dc_table: JpegHuffmanTable,
    /// Cr AC Huffman table.
    pub cr_ac_table: JpegHuffmanTable,
    /// Entropy-coded scan bytes.
    pub entropy_bytes: Vec<u8>,
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Backend fast-path packet for 8-bit 4:4:4 JPEG tiles.
pub struct JpegFast444PacketV1 {
    /// Image dimensions as `(width, height)` in pixels.
    pub dimensions: (u32, u32),
    /// Number of MCUs per row.
    pub mcus_per_row: u32,
    /// Number of MCU rows.
    pub mcu_rows: u32,
    /// Restart interval in MCUs, or zero when absent.
    pub restart_interval_mcus: u32,
    /// Byte offsets of restart-addressable entropy segments.
    pub restart_offsets: Vec<u32>,
    /// Entropy resume checkpoints.
    pub entropy_checkpoints: Vec<JpegEntropyCheckpointV1>,
    /// Y quantization table in natural order.
    pub y_quant: [u16; 64],
    /// Cb quantization table in natural order.
    pub cb_quant: [u16; 64],
    /// Cr quantization table in natural order.
    pub cr_quant: [u16; 64],
    /// Y DC Huffman table.
    pub y_dc_table: JpegHuffmanTable,
    /// Y AC Huffman table.
    pub y_ac_table: JpegHuffmanTable,
    /// Cb DC Huffman table.
    pub cb_dc_table: JpegHuffmanTable,
    /// Cb AC Huffman table.
    pub cb_ac_table: JpegHuffmanTable,
    /// Cr DC Huffman table.
    pub cr_dc_table: JpegHuffmanTable,
    /// Cr AC Huffman table.
    pub cr_ac_table: JpegHuffmanTable,
    /// Entropy-coded scan bytes.
    pub entropy_bytes: Vec<u8>,
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Backend fast-path packet for 8-bit grayscale JPEG tiles.
pub struct JpegGrayPacketV1 {
    /// Image dimensions as `(width, height)` in pixels.
    pub dimensions: (u32, u32),
    /// Number of MCUs per row.
    pub mcus_per_row: u32,
    /// Number of MCU rows.
    pub mcu_rows: u32,
    /// Restart interval in MCUs, or zero when absent.
    pub restart_interval_mcus: u32,
    /// Byte offsets of restart-addressable entropy segments.
    pub restart_offsets: Vec<u32>,
    /// Y quantization table in natural order.
    pub y_quant: [u16; 64],
    /// Y DC Huffman table.
    pub y_dc_table: JpegHuffmanTable,
    /// Y AC Huffman table.
    pub y_ac_table: JpegHuffmanTable,
    /// Entropy-coded scan bytes.
    pub entropy_bytes: Vec<u8>,
}

#[derive(Debug, Clone, Copy)]
struct FastLayout {
    sampling: &'static [(u8, u8)],
    allow_rgb: bool,
    mcu_width: u32,
    mcu_height: u32,
}

const FAST420_LAYOUT: FastLayout = FastLayout {
    sampling: &[(2, 2), (1, 1), (1, 1)],
    allow_rgb: false,
    mcu_width: 16,
    mcu_height: 16,
};

const FAST422_LAYOUT: FastLayout = FastLayout {
    sampling: &[(2, 1), (1, 1), (1, 1)],
    allow_rgb: false,
    mcu_width: 16,
    mcu_height: 8,
};

const FAST444_LAYOUT: FastLayout = FastLayout {
    sampling: &[(1, 1), (1, 1), (1, 1)],
    allow_rgb: true,
    mcu_width: 8,
    mcu_height: 8,
};

#[derive(Debug, Clone, PartialEq, Eq)]
struct ColorFastPacketParts {
    dimensions: (u32, u32),
    mcus_per_row: u32,
    mcu_rows: u32,
    restart_interval_mcus: u32,
    restart_offsets: Vec<u32>,
    entropy_checkpoints: Vec<JpegEntropyCheckpointV1>,
    y_quant: [u16; 64],
    cb_quant: [u16; 64],
    cr_quant: [u16; 64],
    y_dc_table: JpegHuffmanTable,
    y_ac_table: JpegHuffmanTable,
    cb_dc_table: JpegHuffmanTable,
    cb_ac_table: JpegHuffmanTable,
    cr_dc_table: JpegHuffmanTable,
    cr_ac_table: JpegHuffmanTable,
    entropy_bytes: Vec<u8>,
}

macro_rules! impl_from_color_fast_packet_parts {
    ($packet:ty) => {
        impl From<ColorFastPacketParts> for $packet {
            fn from(parts: ColorFastPacketParts) -> Self {
                Self {
                    dimensions: parts.dimensions,
                    mcus_per_row: parts.mcus_per_row,
                    mcu_rows: parts.mcu_rows,
                    restart_interval_mcus: parts.restart_interval_mcus,
                    restart_offsets: parts.restart_offsets,
                    entropy_checkpoints: parts.entropy_checkpoints,
                    y_quant: parts.y_quant,
                    cb_quant: parts.cb_quant,
                    cr_quant: parts.cr_quant,
                    y_dc_table: parts.y_dc_table,
                    y_ac_table: parts.y_ac_table,
                    cb_dc_table: parts.cb_dc_table,
                    cb_ac_table: parts.cb_ac_table,
                    cr_dc_table: parts.cr_dc_table,
                    cr_ac_table: parts.cr_ac_table,
                    entropy_bytes: parts.entropy_bytes,
                }
            }
        }
    };
}

impl_from_color_fast_packet_parts!(JpegFast420PacketV1);
impl_from_color_fast_packet_parts!(JpegFast422PacketV1);
impl_from_color_fast_packet_parts!(JpegFast444PacketV1);

#[derive(Debug, Clone, PartialEq, Eq)]
struct EntropySegments {
    entropy_bytes: Vec<u8>,
    restart_offsets: Vec<u32>,
}

/// Build a 4:2:0 fast-path packet from JPEG bytes.
pub fn build_fast420_packet(bytes: &[u8]) -> Result<JpegFast420PacketV1, FastPacketError> {
    build_color_fast_packet(bytes, FAST420_LAYOUT).map(Into::into)
}

/// Build a 4:4:4 fast-path packet from JPEG bytes.
pub fn build_fast444_packet(bytes: &[u8]) -> Result<JpegFast444PacketV1, FastPacketError> {
    build_color_fast_packet(bytes, FAST444_LAYOUT).map(Into::into)
}

/// Build a 4:2:2 fast-path packet from JPEG bytes.
pub fn build_fast422_packet(bytes: &[u8]) -> Result<JpegFast422PacketV1, FastPacketError> {
    build_color_fast_packet(bytes, FAST422_LAYOUT).map(Into::into)
}

fn build_color_fast_packet(
    bytes: &[u8],
    layout: FastLayout,
) -> Result<ColorFastPacketParts, FastPacketError> {
    let decoder = Decoder::new(bytes)?;
    let header = parse_header(bytes)?;
    if !matches!(header.sof_kind, SofKind::Baseline8 | SofKind::Extended8) {
        return Err(FastPacketError::UnsupportedSof(header.sof_kind));
    }
    if header.bit_depth != 8 {
        return Err(FastPacketError::Decode(JpegError::UnsupportedBitDepth {
            depth: header.bit_depth,
        }));
    }
    let color_space = header.color_space();
    if color_space != ColorSpace::YCbCr && !(layout.allow_rgb && color_space == ColorSpace::Rgb) {
        return Err(FastPacketError::UnsupportedColorSpace(header.color_space()));
    }
    if header.sampling != SamplingFactors::from_validated_components(layout.sampling) {
        return Err(FastPacketError::UnsupportedSampling);
    }
    let scan = header.scan.as_ref().ok_or(FastPacketError::MissingScan)?;
    let [y_scan, cb_scan, cr_scan] = ordered_scan_triplet(&header.component_ids, &scan.components)?;

    let y_quant = quant_for_component(&header.quant_table_ids, &header.quant_tables.entries, 0)?;
    let cb_quant = quant_for_component(&header.quant_table_ids, &header.quant_tables.entries, 1)?;
    let cr_quant = quant_for_component(&header.quant_table_ids, &header.quant_tables.entries, 2)?;
    let y_dc_table = huffman_table(&header.huffman_tables.dc, TableKind::Dc, y_scan.dc_table)?;
    let y_ac_table = huffman_table(&header.huffman_tables.ac, TableKind::Ac, y_scan.ac_table)?;
    let cb_dc_table = huffman_table(&header.huffman_tables.dc, TableKind::Dc, cb_scan.dc_table)?;
    let cb_ac_table = huffman_table(&header.huffman_tables.ac, TableKind::Ac, cb_scan.ac_table)?;
    let cr_dc_table = huffman_table(&header.huffman_tables.dc, TableKind::Dc, cr_scan.dc_table)?;
    let cr_ac_table = huffman_table(&header.huffman_tables.ac, TableKind::Ac, cr_scan.ac_table)?;

    let entropy_offset = header.sos_offset.ok_or(FastPacketError::MissingScan)?;
    let restart_interval_mcus = u32::from(header.restart_interval.unwrap_or(0));
    let EntropySegments {
        entropy_bytes,
        restart_offsets,
    } = extract_entropy_segments(&bytes[entropy_offset..], header.restart_interval)?;
    let (width, height) = header.dimensions;
    let mcus_per_row = width.div_ceil(layout.mcu_width);
    let mcu_rows = height.div_ceil(layout.mcu_height);
    let total_mcus = mcus_per_row
        .checked_mul(mcu_rows)
        .ok_or(FastPacketError::Decode(JpegError::DimensionOverflow {
            width,
            height,
        }))?;
    let entropy_checkpoints =
        build_fast_entropy_checkpoints(&decoder, &bytes[entropy_offset..], total_mcus)?;

    Ok(ColorFastPacketParts {
        dimensions: header.dimensions,
        mcus_per_row,
        mcu_rows,
        restart_interval_mcus,
        restart_offsets,
        entropy_checkpoints,
        y_quant,
        cb_quant,
        cr_quant,
        y_dc_table,
        y_ac_table,
        cb_dc_table,
        cb_ac_table,
        cr_dc_table,
        cr_ac_table,
        entropy_bytes,
    })
}

/// Build a grayscale fast-path packet from JPEG bytes.
pub fn build_gray_packet(bytes: &[u8]) -> Result<JpegGrayPacketV1, FastPacketError> {
    let header = parse_header(bytes)?;
    if !matches!(header.sof_kind, SofKind::Baseline8 | SofKind::Extended8) {
        return Err(FastPacketError::UnsupportedSof(header.sof_kind));
    }
    if header.bit_depth != 8 {
        return Err(FastPacketError::Decode(JpegError::UnsupportedBitDepth {
            depth: header.bit_depth,
        }));
    }
    if header.color_space() != ColorSpace::Grayscale {
        return Err(FastPacketError::UnsupportedColorSpace(header.color_space()));
    }
    if header.sampling != SamplingFactors::from_validated_components(&[(1, 1)]) {
        return Err(FastPacketError::UnsupportedSampling);
    }

    let scan = header.scan.as_ref().ok_or(FastPacketError::MissingScan)?;
    if header.component_ids.len() != 1 || scan.components.len() != 1 {
        return Err(FastPacketError::UnsupportedComponentOrder);
    }
    if scan.components[0].id != header.component_ids[0] {
        return Err(FastPacketError::UnsupportedComponentOrder);
    }

    let y_quant = quant_for_component(&header.quant_table_ids, &header.quant_tables.entries, 0)?;
    let y_dc_table = huffman_table(
        &header.huffman_tables.dc,
        TableKind::Dc,
        scan.components[0].dc_table,
    )?;
    let y_ac_table = huffman_table(
        &header.huffman_tables.ac,
        TableKind::Ac,
        scan.components[0].ac_table,
    )?;

    let entropy_offset = header.sos_offset.ok_or(FastPacketError::MissingScan)?;
    let restart_interval_mcus = u32::from(header.restart_interval.unwrap_or(0));
    let EntropySegments {
        entropy_bytes,
        restart_offsets,
    } = extract_entropy_segments(&bytes[entropy_offset..], header.restart_interval)?;
    let (width, height) = header.dimensions;

    Ok(JpegGrayPacketV1 {
        dimensions: header.dimensions,
        mcus_per_row: width.div_ceil(8),
        mcu_rows: height.div_ceil(8),
        restart_interval_mcus,
        restart_offsets,
        y_quant,
        y_dc_table,
        y_ac_table,
        entropy_bytes,
    })
}

/// Build a 4:2:0 fast-path packet from an inspected decoder.
pub fn build_fast420_packet_for_decoder(
    decoder: &crate::decoder::Decoder<'_>,
) -> Result<JpegFast420PacketV1, FastPacketError> {
    build_fast420_packet(decoder.bytes)
}

/// Build a 4:4:4 fast-path packet from an inspected decoder.
pub fn build_fast444_packet_for_decoder(
    decoder: &crate::decoder::Decoder<'_>,
) -> Result<JpegFast444PacketV1, FastPacketError> {
    build_fast444_packet(decoder.bytes)
}

/// Build a 4:2:2 fast-path packet from an inspected decoder.
pub fn build_fast422_packet_for_decoder(
    decoder: &crate::decoder::Decoder<'_>,
) -> Result<JpegFast422PacketV1, FastPacketError> {
    build_fast422_packet(decoder.bytes)
}

/// Build a grayscale fast-path packet from an inspected decoder.
pub fn build_gray_packet_for_decoder(
    decoder: &crate::decoder::Decoder<'_>,
) -> Result<JpegGrayPacketV1, FastPacketError> {
    build_gray_packet(decoder.bytes)
}

fn quant_for_component(
    quant_table_ids: &[u8],
    tables: &[Option<[u16; 64]>; 4],
    component_idx: usize,
) -> Result<[u16; 64], FastPacketError> {
    let slot = *quant_table_ids
        .get(component_idx)
        .ok_or(FastPacketError::UnsupportedComponentOrder)?;
    tables[slot as usize].ok_or(FastPacketError::MissingQuantTable { slot })
}

fn ordered_scan_triplet(
    component_ids: &[u8],
    scan_components: &[ScanComponent],
) -> Result<[ScanComponent; 3], FastPacketError> {
    if component_ids.len() != 3 || scan_components.len() != 3 {
        return Err(FastPacketError::UnsupportedComponentOrder);
    }

    let mut ordered = [None; 3];
    for (index, &component_id) in component_ids.iter().enumerate() {
        let Some(component) = scan_components
            .iter()
            .copied()
            .find(|component| component.id == component_id)
        else {
            return Err(FastPacketError::UnsupportedComponentOrder);
        };
        ordered[index] = Some(component);
    }

    match ordered {
        [Some(first), Some(second), Some(third)] => Ok([first, second, third]),
        _ => Err(FastPacketError::UnsupportedComponentOrder),
    }
}

fn huffman_table(
    tables: &[Option<RawHuffmanTable>; 4],
    kind: TableKind,
    slot: u8,
) -> Result<JpegHuffmanTable, FastPacketError> {
    let raw = tables[slot as usize]
        .as_ref()
        .ok_or(FastPacketError::MissingHuffmanTable { kind, slot })?;
    Ok(JpegHuffmanTable::from_raw(raw))
}

fn nonrestart_entropy_chunk_mcus(total_mcus: u32) -> u32 {
    total_mcus
        .div_ceil(MAX_NONRESTART_ENTROPY_CHECKPOINTS)
        .max(1)
}

fn build_fast_entropy_checkpoints(
    decoder: &Decoder<'_>,
    scan_bytes: &[u8],
    total_mcus: u32,
) -> Result<Vec<JpegEntropyCheckpointV1>, FastPacketError> {
    let device_checkpoints = build_checkpoint_plan(
        &decoder.plan,
        scan_bytes,
        nonrestart_entropy_chunk_mcus(total_mcus),
    )?;
    device_checkpoints
        .iter()
        .map(|checkpoint| packet_checkpoint_from_device(checkpoint, scan_bytes))
        .collect()
}

fn packet_checkpoint_from_device(
    checkpoint: &DeviceCheckpoint,
    scan_bytes: &[u8],
) -> Result<JpegEntropyCheckpointV1, FastPacketError> {
    Ok(JpegEntropyCheckpointV1 {
        mcu_index: checkpoint.mcu_index,
        entropy_pos: destuffed_entropy_offset(scan_bytes, checkpoint.scan_offset)?,
        bit_acc: checkpoint.bit_accumulator,
        bit_count: u32::from(checkpoint.bits_buffered),
        y_prev_dc: checkpoint.prev_dc[0],
        cb_prev_dc: checkpoint.prev_dc[1],
        cr_prev_dc: checkpoint.prev_dc[2],
        reserved: 0,
    })
}

fn destuffed_entropy_offset(scan_bytes: &[u8], target: usize) -> Result<u32, FastPacketError> {
    if target > scan_bytes.len() {
        return Err(FastPacketError::TruncatedEntropy);
    }

    let mut pos = 0usize;
    let mut destuffed = 0usize;
    while pos < target {
        if scan_bytes[pos] != 0xff {
            pos += 1;
            destuffed += 1;
            continue;
        }

        let marker = *scan_bytes
            .get(pos + 1)
            .ok_or(FastPacketError::TruncatedEntropy)?;
        if pos + 2 > target {
            return Err(FastPacketError::TruncatedEntropy);
        }
        match marker {
            0x00 => {
                pos += 2;
                destuffed += 1;
            }
            0xd0..=0xd7 | 0xd9 => {
                pos += 2;
            }
            marker => return Err(FastPacketError::EntropyMarkerUnsupported { marker }),
        }
    }

    if pos != target {
        return Err(FastPacketError::TruncatedEntropy);
    }
    u32::try_from(destuffed).map_err(|_| FastPacketError::TruncatedEntropy)
}

fn extract_entropy_segments(
    bytes: &[u8],
    restart_interval: Option<u16>,
) -> Result<EntropySegments, FastPacketError> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut restart_offsets = vec![0u32];
    let mut pos = 0usize;
    let mut expected_rst = 0xD0u8;
    while pos < bytes.len() {
        let byte = bytes[pos];
        if byte != 0xFF {
            out.push(byte);
            pos += 1;
            continue;
        }
        let next = *bytes
            .get(pos + 1)
            .ok_or(FastPacketError::TruncatedEntropy)?;
        match next {
            0x00 => {
                out.push(0xFF);
                pos += 2;
            }
            0xD9 => {
                return Ok(EntropySegments {
                    entropy_bytes: out,
                    restart_offsets,
                });
            }
            0xD0..=0xD7 if restart_interval.unwrap_or(0) != 0 => {
                if next != expected_rst {
                    return Err(FastPacketError::EntropyMarkerUnsupported { marker: next });
                }
                restart_offsets
                    .push(u32::try_from(out.len()).map_err(|_| FastPacketError::TruncatedEntropy)?);
                expected_rst = if expected_rst == 0xD7 {
                    0xD0
                } else {
                    expected_rst + 1
                };
                pos += 2;
            }
            marker => {
                return Err(FastPacketError::EntropyMarkerUnsupported { marker });
            }
        }
    }
    Err(FastPacketError::Decode(JpegError::MissingMarker {
        marker: MarkerKind::Eoi,
    }))
}