rust-j2k 0.5.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C library.
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! Tile packet walks kept across the feeds of an incremental decode.
//!
//! A decode with `strict` off of a prefix of a file reads each tile's
//! packets until its data ends, then walks the rest of the progression to
//! note the packets not read (see [`super::walk_packets`]). Each walk here
//! does the first part once over the whole of the file: it reads each
//! packet once the data holds all of it, and keeps where it stopped. A
//! packet the data cuts is read as far as it goes for the image of that
//! prefix, then put back, and read again once more data comes. The packets
//! after it are counted once, by a second walk of the order that reads no
//! data. From the two, each decode of a prefix gets the coded data and
//! the [`Reach`] a decode of that prefix on its own gets, and is charged
//! the visits that decode would spend, so that it refuses the work it
//! refuses.

use crate::codestream::{MainHeader, Tile};
use crate::tier2::Rect;
use crate::{Error, Result};

use super::progression::{
    COUNTS_SKIP_VISITS, Cursor, Order, PacketId, Step, layer_orders, poc_gaps, reached,
};
use super::{
    BandState, Budget, CodedData, ComponentCoded, Delimiters, END_VISITS, Journal, Meter, Packet,
    PacketStreams, PacketWalk, Reach, Refused, Resolution, ResolutionGeom, Scratch, Undo,
    WorkRefusal, band_states, build_subbands, mark_gap, parse_packet, refused, tile_geometry, undo,
};

/// The packet walks of an incremental decode's tiles, by tile index.
///
/// The walks kept hold no more than about twice what one decode of the
/// same bytes holds at its peak: its image, and the packet walk of its
/// largest tile, which it holds while it reads that tile. A walk's size
/// is every heap allocation it holds, capacity included (see
/// [`TileWalk::bytes`]), and a walk that has read all its packets lets go
/// of its order, tag trees, counts and buffers. A tile whose walk would
/// pass that is not kept: each decode walks its packets from the start,
/// as a one-shot decode does.
///
/// The walks do not decide when a refine decodes: the decoder tries on
/// the first refine with at least one byte fed, then at each doubling of
/// the bytes fed since its last try, whether that try gave an image or was
/// refused.
#[derive(Default)]
pub(crate) struct Walks {
    tiles: Vec<Slot>,
    /// The visits of the walks kept and of those let go (see
    /// [`Walks::visits`]).
    #[cfg(test)]
    visits: u64,
    /// The bytes the walks kept hold, as [`TileWalk::bytes`] counts them.
    kept: u64,
    /// The most bytes one tile's walk has held, kept or not.
    largest: u64,
}

/// What is kept of one tile's walk.
#[derive(Default)]
enum Slot {
    /// Nothing: the tile has had no data yet.
    #[default]
    Empty,
    /// The walk, and the bytes it holds.
    Kept(Box<TileWalk>, u64),
    /// A walk too large to keep, of `bytes`, for the tile's header as it
    /// was (see [`TileWalk::volumes`]).
    Unkept {
        bytes: u64,
        volumes: usize,
        packed: bool,
    },
}

impl Walks {
    /// What a decode with `strict` off of the bytes `tile` holds gets from
    /// its packets, under `header`, its resolved header: the coded data,
    /// and what was not read. `meter` is charged what that decode's walk
    /// would charge it, and the work bound refuses this walk where it
    /// refuses that one. `poc_bitmap`, `reduction` and `layers` are as
    /// [`super::decode_packets_partial`] takes them, and must be the same
    /// on every call for a tile. `image` is the bytes of the image the
    /// decode returns.
    ///
    /// A tile whose later tile-part adds `POC` volumes, or packed packet
    /// headers where it had none, has another order of packets, or reads
    /// them from elsewhere: its walk is started again.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn walk<'t>(
        &mut self,
        header: &MainHeader,
        tile: &'t Tile<'t>,
        meter: &Meter,
        poc_bitmap: u64,
        reduction: u8,
        layers: Option<u16>,
        image: u64,
    ) -> std::result::Result<(CodedData<'t>, Reach), Refused> {
        let index = tile.index as usize;
        if self.tiles.len() <= index {
            self.tiles.resize_with(index + 1, Slot::default);
        }
        let volumes = header.poc.len();
        let packed = !tile.packed_headers.is_empty();
        let changed = match &self.tiles[index] {
            Slot::Empty => false,
            Slot::Kept(walk, _) => walk.volumes != volumes || walk.packed != packed,
            Slot::Unkept {
                volumes: v,
                packed: p,
                ..
            } => *v != volumes || *p != packed,
        };
        if changed {
            self.let_go(index);
            self.tiles[index] = Slot::Empty;
        }
        let fits = |walks: &Walks, bytes: u64| {
            let room = image.saturating_add(walks.largest).saturating_mul(2);
            walks.kept.saturating_add(bytes) <= room
        };
        // Whether the walk is new, so none of its visits is counted yet.
        #[cfg(test)]
        let fresh = !matches!(self.tiles[index], Slot::Kept(..));
        match std::mem::take(&mut self.tiles[index]) {
            Slot::Kept(walk, bytes) => self.tiles[index] = Slot::Kept(walk, bytes),
            Slot::Empty => {
                let walk = TileWalk::new(header, tile, reduction, layers);
                let bytes = walk.bytes();
                self.largest = self.largest.max(bytes);
                self.tiles[index] = if fits(self, bytes) {
                    self.kept += bytes;
                    Slot::Kept(Box::new(walk), bytes)
                } else {
                    Slot::Unkept {
                        bytes,
                        volumes,
                        packed,
                    }
                };
            }
            Slot::Unkept { bytes, .. } if fits(self, bytes) => {
                let walk = TileWalk::new(header, tile, reduction, layers);
                let bytes = walk.bytes();
                self.kept += bytes;
                self.tiles[index] = Slot::Kept(Box::new(walk), bytes);
            }
            unkept => self.tiles[index] = unkept,
        }
        let Slot::Kept(walk, bytes) = &mut self.tiles[index] else {
            return super::decode_packets_partial(
                header, tile, meter, poc_bitmap, reduction, layers,
            );
        };
        #[cfg(test)]
        let visits = if fresh { 0 } else { walk.visits() };
        let walked = walk.walk(header, tile, meter, poc_bitmap);
        #[cfg(test)]
        {
            self.visits = self.visits + walk.visits() - visits;
        }
        let now = walk.bytes();
        self.kept = self.kept - *bytes + now;
        *bytes = now;
        self.largest = self.largest.max(now);
        // A walk that has grown past the room is let go. Its decode has
        // what it read; the next walks of the tile go from the start.
        if !fits(self, 0) {
            self.let_go(index);
            self.tiles[index] = Slot::Unkept {
                bytes: now,
                volumes,
                packed,
            };
        }
        walked
    }

    /// Let go of the walk of tile `index`, if one is kept. Its visits stay
    /// counted.
    fn let_go(&mut self, index: usize) {
        if let Slot::Kept(_, bytes) = &self.tiles[index] {
            self.kept -= *bytes;
            self.tiles[index] = Slot::Empty;
        }
    }

    /// How many tiles have a walk kept, and how many one too large to keep.
    #[cfg(test)]
    pub(crate) fn kept(&self) -> (usize, usize) {
        let kept = self
            .tiles
            .iter()
            .filter(|s| matches!(s, Slot::Kept(..)))
            .count();
        let unkept = self
            .tiles
            .iter()
            .filter(|s| matches!(s, Slot::Unkept { .. }))
            .count();
        (kept, unkept)
    }

    /// The packet visits the walks have spent: the visits the decodes they
    /// stand for charge for the packets and progression points read or
    /// counted, each counted once however many decodes charged it. A walk
    /// let go, or started again, keeps its count; the walks of a tile not
    /// kept are not counted.
    #[cfg(test)]
    pub(crate) fn visits(&self) -> u64 {
        self.visits
    }
}

/// How a step of the walk over new data ended.
enum Advanced {
    /// At the end of the data, or of the order.
    Stopped,
    /// Short of visits: the decode of this prefix is refused too.
    Refused,
    /// At a fault in the packet the walk read: the decode of this prefix
    /// fails there too, unless the visits it has spent by then, given, are
    /// more than it has.
    Failed(Error, u64),
}

/// One tile's walk.
struct TileWalk {
    /// How many `POC` volumes the tile's header had when the walk started.
    volumes: usize,
    /// Whether the tile's packet headers were packed (`PPT` or `PPM`).
    packed: bool,
    /// The code-blocks each component's geometry holds in the resolutions
    /// the reduction drops, which a decode charges as it builds them.
    dropped: Vec<u64>,
    /// The fault that ended the geometry, after the components `dropped`
    /// holds.
    failure: Option<Error>,
    geoms: Vec<Vec<ResolutionGeom>>,
    /// The tile's rectangle on the reference grid.
    rect: Rect,
    states: Vec<Vec<Vec<BandState>>>,
    delimiters: Delimiters,
    /// Each component's code-block style.
    styles: Vec<u8>,
    /// The decode's layer cap.
    layers: Option<u16>,
    order: Order,
    /// The reading walk.
    cursor: Cursor,
    /// Whether the order is a `POC` sequence, whose volumes may emit a
    /// packet again: then a packet of a layer below the precinct's packets
    /// read is one already emitted (see [`TileWalk::advance`]).
    dedup: bool,
    /// The packets the `POC` volumes reach, and whether all of them are
    /// layer orders (see `progression::Emitted`).
    reached: u64,
    layer_orders: bool,
    /// Per component and resolution: the first layer the `POC` volumes
    /// leave out.
    gaps: Vec<Vec<Option<u32>>>,
    /// Per component, resolution and precinct: the packets read whole,
    /// which are its first layers.
    read: Vec<Vec<Vec<u32>>>,
    header_pos: usize,
    body_pos: usize,
    packet_index: u32,
    /// The packet the reading walk is at, not yet read whole.
    pending: Option<PacketId>,
    /// Whether `pending` is read in part into the state, for an image.
    cut: bool,
    /// The visits reading `pending` in part spent.
    pending_visits: u64,
    /// Whether every packet of the order has been read.
    done: bool,
    /// Whether the walk, at its end, has let go of what reads packets.
    shrunk: bool,
    /// Where the walk was before the packets it read ahead, if it did:
    /// packets read whole that more data may yet read otherwise, from the
    /// first that starts, with `SOP` markers, with fewer than two bytes of
    /// the data left.
    tentative: Option<Mark>,
    read_ahead: Vec<Ahead>,
    /// What the reading walk has spent: on the points of the order, on the
    /// packets read whole, and how many packets it found already emitted.
    loops: u64,
    packets: u64,
    parsed: u64,
    skips: u64,
    /// The walk that counts the packets of the order.
    census: Census,
    scratch: Scratch,
    log: Vec<Undo>,
    journal: Journal,
    /// What the end of the data costs (see [`END_VISITS`]).
    end_visits: u64,
}

/// Where a walk was, to go back to (see [`TileWalk::tentative`]).
struct Mark {
    cursor: Cursor,
    pending: Option<PacketId>,
    header_pos: usize,
    body_pos: usize,
    packet_index: u32,
    loops: u64,
    packets: u64,
    parsed: u64,
    skips: u64,
}

/// A packet read ahead, with what puts it back.
struct Ahead {
    id: PacketId,
    log: Vec<Undo>,
    journal: Journal,
}

/// A walk of the order that reads no data: how many packets it emits for
/// each precinct, and what a walk of all of it is charged.
struct Census {
    cursor: Cursor,
    counts: Vec<Vec<Vec<u32>>>,
    loops: u64,
    packets: u64,
    skips: u64,
    done: bool,
}

impl TileWalk {
    fn new(header: &MainHeader, tile: &Tile<'_>, reduction: u8, layers: Option<u16>) -> Self {
        let mut budget = Budget {
            reduction,
            layers,
            ..Budget::decode(0, 0)
        };
        let mut dropped = Vec::new();
        let built = tile_geometry(header, tile.index, &mut budget, |blocks| {
            dropped.push(blocks as u64);
            Ok(())
        })
        .and_then(|geoms| {
            let rect = header
                .siz
                .tile_rect(tile.index)
                .ok_or_else(|| Error::inconsistent(format!("no tile {} in `SIZ`", tile.index)))?;
            Ok((geoms, rect))
        });
        let (geoms, rect, failure) = match built {
            Ok((geoms, rect)) => (geoms, rect, None),
            Err(error) => (
                Vec::new(),
                Rect {
                    x0: 0,
                    y0: 0,
                    x1: 0,
                    y1: 0,
                },
                Some(error),
            ),
        };
        let mut states = band_states(header, &geoms);
        let walk = PacketWalk {
            siz: &header.siz,
            tile: rect,
            geoms: &geoms,
        };
        let order = Order::new(header, &walk);
        let mut gaps: Vec<Vec<Option<u32>>> = geoms.iter().map(|c| vec![None; c.len()]).collect();
        if failure.is_none() {
            // Not strict, a gap is noted, never refused.
            let _ = poc_gaps(header, &walk, |comp, res, layer| {
                let layer = u32::from(layer);
                gaps[comp][res] = Some(gaps[comp][res].map_or(layer, |l| l.min(layer)));
                mark_gap(&mut states[comp][res], layer);
                Ok(())
            });
        }
        let dedup = order.volumes.len() > 1;
        let reached = if dedup && failure.is_none() {
            reached(&order.volumes, &walk, order.max_res)
        } else {
            0
        };
        let counts: Vec<Vec<Vec<u32>>> = geoms
            .iter()
            .map(|c| c.iter().map(|r| vec![0; r.precinct_count()]).collect())
            .collect();
        let end_visits = geoms.iter().map(Vec::len).sum::<usize>() as u64 * END_VISITS as u64;
        TileWalk {
            volumes: header.poc.len(),
            packed: !tile.packed_headers.is_empty(),
            dropped,
            failure,
            states,
            delimiters: Delimiters {
                sop: header.cod.use_sop,
                eph: header.cod.use_eph,
            },
            styles: header
                .components
                .iter()
                .map(|c| c.coding.code_block_style)
                .collect(),
            layers,
            layer_orders: layer_orders(&order.volumes),
            order,
            cursor: Cursor::default(),
            dedup,
            reached,
            gaps,
            read: counts.clone(),
            header_pos: 0,
            body_pos: 0,
            packet_index: 0,
            pending: None,
            cut: false,
            pending_visits: 0,
            done: false,
            shrunk: false,
            tentative: None,
            read_ahead: Vec::new(),
            loops: 0,
            packets: 0,
            parsed: 0,
            skips: 0,
            census: Census {
                cursor: Cursor::default(),
                counts,
                loops: 0,
                packets: 0,
                skips: 0,
                done: false,
            },
            scratch: Scratch::default(),
            log: Vec::new(),
            journal: Journal::default(),
            end_visits,
            geoms,
            rect,
        }
    }

    /// The bytes the walk holds on the heap, capacity included: its
    /// geometry, its packet state, its order, its counts and its buffers.
    /// Only the message of a fault in the geometry is left out; a walk
    /// with one holds no geometry.
    fn bytes(&self) -> u64 {
        use std::mem::size_of;
        /// The bytes of a list of lists: the outer list's, and the inner
        /// lists' items.
        fn nested<T>(lists: &Vec<Vec<T>>) -> usize {
            lists.capacity() * size_of::<Vec<T>>()
                + lists.iter().map(Vec::capacity).sum::<usize>() * size_of::<T>()
        }
        let mut bytes = size_of::<TileWalk>()
            + self.dropped.capacity() * size_of::<u64>()
            + self.styles.capacity()
            + nested(&self.geoms)
            + self.states.capacity() * size_of::<Vec<Vec<BandState>>>()
            + nested(&self.gaps)
            + self.order.heap_bytes()
            + self.scratch.heap_bytes()
            + self.log.capacity() * size_of::<Undo>()
            + self.journal.heap_bytes()
            + self.read_ahead.capacity() * size_of::<Ahead>();
        for resolution in self.geoms.iter().flatten() {
            bytes += resolution.heap_bytes();
        }
        for component in &self.states {
            bytes += nested(component);
            for bands in component {
                bytes += bands.iter().map(BandState::heap_bytes).sum::<usize>();
            }
        }
        for counts in [&self.read, &self.census.counts] {
            bytes += counts.capacity() * size_of::<Vec<Vec<u32>>>();
            bytes += counts.iter().map(nested).sum::<usize>();
        }
        for ahead in &self.read_ahead {
            bytes += ahead.log.capacity() * size_of::<Undo>() + ahead.journal.heap_bytes();
        }
        bytes as u64
    }

    /// Let go of what reads packets, once the walk has read them all: the
    /// order, the tag trees, the counts of packets read, and the buffers.
    /// What builds the image, and the `POC` gaps its report notes, stay.
    fn shrink(&mut self) {
        for component in &mut self.states {
            for bands in component {
                for band in bands {
                    band.drop_trees();
                }
            }
        }
        self.order = Order::default();
        self.styles = Vec::new();
        self.read = Vec::new();
        self.census.counts = Vec::new();
        self.scratch = Scratch::default();
        self.log = Vec::new();
        self.journal = Journal::default();
        self.read_ahead = Vec::new();
        self.shrunk = true;
    }

    /// The visits this walk has spent, each point and packet of the order
    /// counted once (see [`Walks::visits`]).
    #[cfg(test)]
    fn visits(&self) -> u64 {
        let order = (self.loops + self.packets).max(self.census.loops + self.census.packets);
        let spans = self.parsed - self.packets;
        self.dropped
            .iter()
            .fold(order + spans, |a, &b| a.saturating_add(b))
    }

    /// See [`Walks::walk`].
    fn walk<'t>(
        &mut self,
        header: &MainHeader,
        tile: &'t Tile<'t>,
        meter: &Meter,
        poc_bitmap: u64,
    ) -> std::result::Result<(CodedData<'t>, Reach), Refused> {
        let walked = self.charge(header, tile, meter, poc_bitmap).and_then(|()| {
            self.view(header, tile)
                .map_err(|error| refused(meter, error))
        });
        // A packet read in part is put back, to be read again once more
        // data comes.
        self.unwind();
        // A walk at its end reads no more packets: only what builds the
        // image is kept.
        if self.done && !self.shrunk {
            self.shrink();
        }
        walked
    }

    /// Bring the walk up to the data `tile` holds, and charge `meter` as a
    /// decode of that data charges it, in the same order: the geometry,
    /// the `POC` packets, and then the walk.
    fn charge(
        &mut self,
        header: &MainHeader,
        tile: &Tile<'_>,
        meter: &Meter,
        poc_bitmap: u64,
    ) -> std::result::Result<(), Refused> {
        meter.clear_refusal();
        // The decode's bitmap holds at most the visits left as its walk
        // starts (see `Budget::decode`).
        let dense_bits = meter.left().min(poc_bitmap);
        for &blocks in &self.dropped {
            if !meter.try_spend(blocks) {
                return Err(Refused::Work(WorkRefusal::DroppedBlocks { blocks }));
            }
        }
        if let Some(error) = &self.failure {
            return Err(Refused::Other(error.clone()));
        }
        // `dedup` is whether the order has more than one volume; the order
        // itself is let go once the walk is done.
        let sparse = if self.dedup {
            if self.layer_orders && self.reached > meter.left() {
                return Err(Refused::Work(WorkRefusal::PocReach {
                    reached: self.reached,
                }));
            }
            self.reached > dense_bits
        } else {
            false
        };
        let skip = if sparse { COUNTS_SKIP_VISITS as u64 } else { 0 };
        // Each walk here spends no more than the decode's own: each step
        // it takes is one the decode takes. So a walk short of what the
        // decode has left is refused with it.
        let left = meter.left();
        let charge = match self.advance(header, tile, left) {
            Advanced::Refused => return Err(Refused::Work(WorkRefusal::PacketWalk)),
            Advanced::Failed(error, spent) => {
                let spent = spent.saturating_add(self.skips.saturating_mul(skip));
                if !meter.try_spend(spent) {
                    return Err(Refused::Work(WorkRefusal::PacketWalk));
                }
                return Err(Refused::Other(error));
            }
            Advanced::Stopped if self.done => self.loops + self.parsed + self.skips * skip,
            Advanced::Stopped => {
                if !self.count(header, left) {
                    return Err(Refused::Work(WorkRefusal::PacketWalk));
                }
                // The decode reads the packets read whole and the one the
                // data cuts, is charged for the end of the data, and then
                // counts every packet after it.
                let census = &self.census;
                let after = census.packets.saturating_sub(self.packets + 1);
                [
                    census.loops,
                    census.skips.saturating_mul(skip),
                    self.parsed,
                    self.pending_visits,
                    self.end_visits,
                    after,
                ]
                .into_iter()
                .fold(0, u64::saturating_add)
            }
        };
        if !meter.try_spend(charge) {
            return Err(Refused::Work(WorkRefusal::PacketWalk));
        }
        Ok(())
    }

    /// Read the packets the data now holds, spending no more than `left`
    /// visits on the walk in all.
    fn advance(&mut self, header: &MainHeader, tile: &Tile<'_>, left: u64) -> Advanced {
        let meter = Meter::new(left.saturating_sub(self.loops + self.parsed));
        loop {
            let id = match self.pending {
                Some(id) => id,
                None if self.done => return Advanced::Stopped,
                None => {
                    let walk = PacketWalk {
                        siz: &header.siz,
                        tile: self.rect,
                        geoms: &self.geoms,
                    };
                    let before = self.cursor;
                    match self.order.next(&walk, &mut self.cursor) {
                        None => {
                            self.done = true;
                            return Advanced::Stopped;
                        }
                        Some(Step::Point(visits)) => {
                            if !meter.try_spend(visits as u64) {
                                self.cursor = before;
                                return Advanced::Refused;
                            }
                            self.loops += visits as u64;
                            continue;
                        }
                        Some(Step::Packet(id)) => {
                            // Each volume emits a precinct's layers from 0
                            // up, so the layers a `POC` sequence has emitted
                            // of a precinct are always its first ones: those
                            // read whole, as no packet is pending here. A
                            // packet of a layer below them is one emitted
                            // before, which the decode's bitmap or counts
                            // find there.
                            if self.dedup {
                                let read = self.read[id.comp][id.res][id.precinct];
                                debug_assert!(id.layer <= read, "{id:?} after {read} layers");
                                if id.layer < read {
                                    self.skips += 1;
                                    continue;
                                }
                            }
                            self.pending = Some(id);
                            id
                        }
                    }
                }
            };
            // With `SOP` markers, a packet that starts with fewer than two
            // bytes of the data left may yet have an `SOP` before it, which
            // the decode cannot see until more data comes. Read whole, it
            // is read from what may be the marker's first byte, inline, or
            // with no body byte to look at, packed.
            let tentative = self.tentative.is_some()
                || (self.delimiters.sop && tile.data.len().saturating_sub(self.body_pos) < 2);
            let before = meter.spent();
            let (read, header_pos, body_pos) = self.parse(tile, id, &meter);
            let spent = meter.spent() - before;
            match read {
                Ok(Packet::Read) => {
                    if tentative {
                        // It is read for this image, then put back.
                        // The first is put back as the packet to read next;
                        // the rest are emitted again.
                        let first = self.tentative.is_none();
                        if first {
                            self.tentative = Some(Mark {
                                cursor: self.cursor,
                                pending: self.pending,
                                header_pos: self.header_pos,
                                body_pos: self.body_pos,
                                packet_index: self.packet_index,
                                loops: self.loops,
                                packets: self.packets,
                                parsed: self.parsed,
                                skips: self.skips,
                            });
                        }
                        self.read_ahead.push(Ahead {
                            id,
                            log: std::mem::take(&mut self.log),
                            journal: std::mem::take(&mut self.journal),
                        });
                    }
                    self.header_pos = header_pos;
                    self.body_pos = body_pos;
                    self.packet_index += 1;
                    self.read[id.comp][id.res][id.precinct] += 1;
                    self.packets += 1;
                    self.parsed += spent;
                    self.pending = None;
                }
                Ok(Packet::Ended) => {
                    // The decode keeps what the packet holds of whole
                    // code-blocks; it stays in the state for the image.
                    self.cut = true;
                    self.pending_visits = spent;
                    return Advanced::Stopped;
                }
                Err(error) => {
                    self.cut = true;
                    if meter.refusal().is_some() {
                        return Advanced::Refused;
                    }
                    return Advanced::Failed(error, self.loops + self.parsed + spent);
                }
            }
        }
    }

    /// Read packet `id` from where the walk is in `tile`'s data, spending
    /// `meter`; with the stream positions after it.
    fn parse(
        &mut self,
        tile: &Tile<'_>,
        id: PacketId,
        meter: &Meter,
    ) -> (Result<Packet>, usize, usize) {
        let data: &[u8] = &tile.data;
        let mut streams = PacketStreams {
            header: if self.packed {
                &tile.packed_headers
            } else {
                data
            },
            header_pos: self.header_pos,
            data,
            body_pos: self.body_pos,
            packed: self.packed,
            tile: tile.index,
        };
        // The logs hold this packet's changes alone, so that it can be put
        // back whole.
        self.log.clear();
        self.journal.clear();
        let read = parse_packet(
            &mut streams,
            meter,
            id.layer,
            self.packet_index,
            self.delimiters,
            self.styles[id.comp],
            &self.geoms[id.comp][id.res].bands,
            id.precinct,
            &mut self.states[id.comp][id.res],
            &mut self.scratch,
            self.layers.is_none_or(|cap| id.layer < u32::from(cap)),
            Some(&mut self.log),
            Some(&mut self.journal),
        );
        (read, streams.header_pos, streams.body_pos)
    }

    /// Put back the packet read in part, if one is, and then the packets
    /// read ahead, latest first.
    fn unwind(&mut self) {
        if std::mem::take(&mut self.cut) {
            if let Some(id) = self.pending {
                let states = &mut self.states[id.comp][id.res];
                undo(&self.log, states);
                self.journal.restore(states, id.precinct);
            }
            self.pending_visits = 0;
        }
        let Some(mark) = self.tentative.take() else {
            return;
        };
        for ahead in self.read_ahead.drain(..).rev() {
            let id = ahead.id;
            let states = &mut self.states[id.comp][id.res];
            undo(&ahead.log, states);
            ahead.journal.restore(states, id.precinct);
            self.read[id.comp][id.res][id.precinct] -= 1;
        }
        self.cursor = mark.cursor;
        self.pending = mark.pending;
        self.header_pos = mark.header_pos;
        self.body_pos = mark.body_pos;
        self.packet_index = mark.packet_index;
        self.loops = mark.loops;
        self.packets = mark.packets;
        self.parsed = mark.parsed;
        self.skips = mark.skips;
        self.done = false;
    }

    /// Count the packets of the order, spending no more than `left` visits
    /// on the count in all; whether it got to the end.
    fn count(&mut self, header: &MainHeader, left: u64) -> bool {
        let census = &mut self.census;
        if census.done {
            return true;
        }
        let meter = Meter::new(left.saturating_sub(census.loops + census.packets));
        let walk = PacketWalk {
            siz: &header.siz,
            tile: self.rect,
            geoms: &self.geoms,
        };
        loop {
            let before = census.cursor;
            match self.order.next(&walk, &mut census.cursor) {
                None => {
                    census.done = true;
                    return true;
                }
                Some(Step::Point(visits)) => {
                    if !meter.try_spend(visits as u64) {
                        census.cursor = before;
                        return false;
                    }
                    census.loops += visits as u64;
                }
                Some(Step::Packet(id)) => {
                    if meter.left() == 0 {
                        census.cursor = before;
                        return false;
                    }
                    // As in the reading walk, a packet of a layer below
                    // the precinct's count is one already emitted.
                    let count = &mut census.counts[id.comp][id.res][id.precinct];
                    if self.dedup && id.layer < *count {
                        census.skips += 1;
                        continue;
                    }
                    meter.try_spend(1);
                    *count += 1;
                    census.packets += 1;
                }
            }
        }
    }

    /// The coded data and the reach of the walk as it stands.
    fn view<'t>(
        &mut self,
        header: &MainHeader,
        tile: &'t Tile<'t>,
    ) -> Result<(CodedData<'t>, Reach)> {
        let data: &'t [u8] = &tile.data;
        let mut reach = Reach {
            missing_from: self.gaps.clone(),
            ..Reach::default()
        };
        let mut components = Vec::with_capacity(self.states.len());
        for (comp, component) in self.states.iter_mut().enumerate() {
            let rect = header
                .siz
                .tile_component_rect(tile.index, comp)
                .ok_or_else(|| Error::inconsistent(format!("no component {comp} in `SIZ`")))?;
            let mut resolutions = Vec::with_capacity(component.len());
            for (res, bands) in component.iter_mut().enumerate() {
                // A precinct whose packets the data has not all brought is
                // missing from its first packet not read.
                let (read, counts): (&[u32], &[u32]) = if self.shrunk {
                    (&[], &[])
                } else {
                    (&self.read[comp][res], &self.census.counts[comp][res])
                };
                for (precinct, &read) in read.iter().enumerate() {
                    let ended = (!self.done && read < counts[precinct]).then_some(read);
                    if let Some(layer) = ended {
                        let from = &mut reach.missing_from[comp][res];
                        *from = Some(from.map_or(layer, |f| f.min(layer)));
                    }
                    for band in bands.iter_mut() {
                        if let Some(state) = band.precincts.get_mut(precinct) {
                            state.ended = ended;
                        }
                    }
                }
                let level = &self.geoms[comp][res];
                let subbands = if level.bands.is_empty() {
                    Vec::new()
                } else {
                    build_subbands(&level.bands, bands, data)
                };
                resolutions.push(Resolution { subbands });
            }
            components.push(ComponentCoded {
                resolutions,
                rect: Some(rect),
            });
        }
        // Bytes left after the last packet are noted; data that ran out
        // leaves none.
        if self.done {
            if self.body_pos < data.len() {
                reach.leftover = Some((self.body_pos, data.len() - self.body_pos));
            }
            if self.packed && self.header_pos < tile.packed_headers.len() {
                reach.leftover_packed = Some(tile.packed_headers.len() - self.header_pos);
            }
        }
        Ok((CodedData { components }, reach))
    }
}