Skip to main content

xue/decode/
bundle.rs

1//! The two public readers.
2//!
3//! [`Bundle`] owns a complete file. [`StreamingBundle`] owns only the
4//! structural prefix and accepts payload bytes as range responses arrive.
5//! Both are thin shells over the shared [`Core`]: the accessors below read
6//! validated metadata, and the decode calls delegate outright.
7//!
8//! Both read either container version. The tiled calls — a frame restricted
9//! to a tile rectangle, a cell's series, the spans either of them still needs
10//! — are the ones v2 adds; on a v1 file they report that the file has no
11//! tiles rather than pretending otherwise.
12
13use crate::decode::core::{Core, PayloadStore};
14use crate::decode::structure::{checked_end, parse_structure, Layout, ParseMode};
15use crate::format::{err, DecodeError, FrameRequest, TileGeometry, TileRect};
16
17pub struct Bundle {
18    core: Core,
19}
20
21impl Bundle {
22    /// Parse and fully validate a bundle, copying the bytes into owned memory.
23    pub fn open(bytes: &[u8]) -> Result<Self, DecodeError> {
24        let structure = parse_structure(bytes, ParseMode::FullFile)?;
25        Ok(Bundle {
26            core: Core::new(structure, PayloadStore::Full(bytes.to_vec())),
27        })
28    }
29
30    pub fn metadata_json(&self) -> &str {
31        &self.core.structure.metadata.json
32    }
33
34    pub fn plane_length(&self) -> usize {
35        self.core.structure.metadata.plane_length as usize
36    }
37
38    pub fn frame_count(&self) -> u32 {
39        self.core.structure.metadata.frame_count
40    }
41
42    pub fn variable_ids(&self) -> &[u8] {
43        &self.core.structure.metadata.variable_ids
44    }
45
46    /// Seconds per axis unit: a frame's valid time is
47    /// `runTime + frameOffset * unitSeconds`.
48    pub fn unit_seconds(&self) -> u32 {
49        self.core.structure.metadata.unit_seconds
50    }
51
52    /// The materialized frame-offset axis, ascending — the keys every plane
53    /// of every variable is addressed by.
54    pub fn frame_offsets(&self) -> &[u16] {
55        &self.core.structure.metadata.offsets
56    }
57
58    pub fn clear_cache(&mut self) {
59        self.core.clear_cache();
60    }
61
62    /// The file's tiling, or `None` for a plane-major v1 file.
63    pub fn tile_geometry(&self) -> Option<TileGeometry> {
64        self.core.tile_geometry()
65    }
66
67    pub fn decode_frame(&mut self, request: FrameRequest) -> Result<&[u8], DecodeError> {
68        self.core.decode_frame(request)
69    }
70
71    /// Decode only the tiles a viewport covers, into the same whole-plane
72    /// buffer. Cells outside the rectangle keep whatever the buffer held, so
73    /// a renderer must draw only the rectangle it asked for.
74    pub fn decode_frame_tiles(
75        &mut self,
76        request: FrameRequest,
77        tiles: TileRect,
78    ) -> Result<&[u8], DecodeError> {
79        self.core.decode_frame_tiles(request, Some(tiles))
80    }
81
82    /// One cell's code on every frame of the axis, in axis order.
83    pub fn decode_series(
84        &mut self,
85        variable_id: u8,
86        column: u32,
87        row: u32,
88    ) -> Result<Vec<u8>, DecodeError> {
89        self.core.decode_series(variable_id, column, row)
90    }
91}
92
93/// A bundle opened from just its structural prefix, with payload bytes
94/// arriving incrementally as HTTP range responses.
95///
96/// The prefix must span at least `[0, dataOffset)` — header, metadata, index,
97/// and dictionary. Callers then ask [`missing_group_span`] which byte range a
98/// frame's temporal group still needs, fetch it, and hand it to
99/// [`insert_range`]; the writer keeps each group's payloads contiguous, so
100/// one range request per group suffices.
101///
102/// [`missing_group_span`]: StreamingBundle::missing_group_span
103/// [`insert_range`]: StreamingBundle::insert_range
104pub struct StreamingBundle {
105    core: Core,
106}
107
108impl StreamingBundle {
109    pub fn open_prefix(prefix: &[u8]) -> Result<Self, DecodeError> {
110        let structure = parse_structure(prefix, ParseMode::Prefix)?;
111        let payloads = vec![None; structure.payload_count()];
112        Ok(StreamingBundle {
113            core: Core::new(
114                structure,
115                PayloadStore::Sparse {
116                    payloads,
117                    resident_bytes: 0,
118                },
119            ),
120        })
121    }
122
123    pub fn metadata_json(&self) -> &str {
124        &self.core.structure.metadata.json
125    }
126
127    pub fn plane_length(&self) -> usize {
128        self.core.structure.metadata.plane_length as usize
129    }
130
131    pub fn frame_count(&self) -> u32 {
132        self.core.structure.metadata.frame_count
133    }
134
135    pub fn variable_ids(&self) -> &[u8] {
136        &self.core.structure.metadata.variable_ids
137    }
138
139    /// Seconds per axis unit: a frame's valid time is
140    /// `runTime + frameOffset * unitSeconds`.
141    pub fn unit_seconds(&self) -> u32 {
142        self.core.structure.metadata.unit_seconds
143    }
144
145    /// The materialized frame-offset axis, ascending — the keys every plane
146    /// of every variable is addressed by.
147    pub fn frame_offsets(&self) -> &[u16] {
148        &self.core.structure.metadata.offsets
149    }
150
151    pub fn clear_cache(&mut self) {
152        self.core.clear_cache();
153    }
154
155    /// The file's tiling, or `None` for a plane-major v1 file.
156    pub fn tile_geometry(&self) -> Option<TileGeometry> {
157        self.core.tile_geometry()
158    }
159
160    /// End of the structural prefix: the minimum bytes `open_prefix` needs.
161    pub fn data_offset(&self) -> u64 {
162        self.core.structure.data_offset
163    }
164
165    pub fn file_size(&self) -> u64 {
166        self.core.structure.file_size
167    }
168
169    /// Sum of every payload's compressed length.
170    pub fn total_payload_bytes(&self) -> u64 {
171        (0..self.core.structure.payload_count())
172            .map(|position| {
173                let (start, end) = self.core.structure.payload_span(position);
174                end - start
175            })
176            .sum()
177    }
178
179    /// Compressed bytes inserted so far.
180    pub fn resident_payload_bytes(&self) -> u64 {
181        match &self.core.store {
182            PayloadStore::Sparse { resident_bytes, .. } => *resident_bytes,
183            PayloadStore::Full(_) => unreachable!("streaming bundles use a sparse store"),
184        }
185    }
186
187    /// The contiguous byte span `[start, end)` still needed to decode any
188    /// frame of the temporal group containing `request`, or `None` when the
189    /// whole group is already resident.
190    ///
191    /// This is the global-view request in both versions, and it stays one
192    /// range in both: v1 keeps a variable's group adjacent, v2 keeps a whole
193    /// group — every tile, every variable — adjacent.
194    pub fn missing_group_span(
195        &self,
196        request: FrameRequest,
197    ) -> Result<Option<(u64, u64)>, DecodeError> {
198        Ok(coalesce(
199            self.missing_positions(request, None)?
200                .into_iter()
201                .map(|position| self.core.structure.payload_span(position)),
202        ))
203    }
204
205    /// The byte spans a frame still needs, restricted to a tile rectangle and
206    /// coalesced where the tiles are adjacent in the file — one span per tile
207    /// row per group, since a row of tiles is contiguous.
208    pub fn missing_spans(
209        &self,
210        request: FrameRequest,
211        tiles: Option<TileRect>,
212    ) -> Result<Vec<(u64, u64)>, DecodeError> {
213        Ok(merge_adjacent(
214            self.missing_positions(request, tiles)?
215                .into_iter()
216                .map(|position| self.core.structure.payload_span(position)),
217        ))
218    }
219
220    /// The spans one cell's series still needs: one chunk per group, so at
221    /// most one span per group and nothing proportional to the frame count.
222    pub fn missing_series_spans(
223        &self,
224        variable_id: u8,
225        column: u32,
226        row: u32,
227    ) -> Result<Vec<(u64, u64)>, DecodeError> {
228        let tiles = self.core.tiled()?;
229        let variable_position = tiles.variable_position(variable_id)?;
230        let tile = tiles.geometry.tile_of(row, column)?;
231        let spans = (0..tiles.groups.len())
232            .map(|group| tiles.chunk_position(group as u32, tile, variable_position))
233            .filter(|&position| {
234                !self
235                    .core
236                    .store
237                    .is_resident(position, self.core.structure.payload_span(position))
238            })
239            .map(|position| self.core.structure.payload_span(position));
240        Ok(merge_adjacent(spans))
241    }
242
243    /// The index positions a frame needs and does not have yet, ascending.
244    fn missing_positions(
245        &self,
246        request: FrameRequest,
247        tiles: Option<TileRect>,
248    ) -> Result<Vec<usize>, DecodeError> {
249        let positions = match &self.core.structure.layout {
250            Layout::Planes(planes) => {
251                if tiles.is_some() {
252                    return Err(err("a plane-major file has no tiles"));
253                }
254                let target = planes.entries[planes.entry_position(request)?];
255                planes
256                    .entries
257                    .iter()
258                    .enumerate()
259                    .filter(|(_, member)| {
260                        member.variable_id == target.variable_id
261                            && member.group_id == target.group_id
262                    })
263                    .map(|(position, _)| position)
264                    .collect::<Vec<_>>()
265            }
266            Layout::Tiles(layout) => {
267                let variable_position = layout.variable_position(request.variable_id)?;
268                let (group, _) =
269                    layout.frame_group[self.core.structure.frame_index(request.frame_offset)?];
270                (0..layout.geometry.count())
271                    .filter(|&tile| tiles.is_none_or(|rect| rect.contains(&layout.geometry, tile)))
272                    .map(|tile| layout.chunk_position(group, tile, variable_position))
273                    .collect::<Vec<_>>()
274            }
275        };
276        Ok(positions
277            .into_iter()
278            .filter(|&position| {
279                !self
280                    .core
281                    .store
282                    .is_resident(position, self.core.structure.payload_span(position))
283            })
284            .collect())
285    }
286
287    /// Store payload bytes covering `[offset, offset + bytes.len())` of the
288    /// file. Every index entry whose payload lies fully inside the range
289    /// becomes resident; partial overlaps are ignored.
290    pub fn insert_range(&mut self, offset: u64, bytes: &[u8]) -> Result<(), DecodeError> {
291        let end = checked_end(
292            offset,
293            bytes.len() as u64,
294            self.core.structure.file_size,
295            "inserted",
296        )?;
297        let PayloadStore::Sparse {
298            payloads,
299            resident_bytes,
300        } = &mut self.core.store
301        else {
302            unreachable!("streaming bundles use a sparse store");
303        };
304        for position in 0..self.core.structure.payload_count() {
305            if payloads[position].is_some() {
306                continue;
307            }
308            let (start, stop) = self.core.structure.payload_span(position);
309            if start == stop || start < offset || stop > end {
310                continue;
311            }
312            let from = (start - offset) as usize;
313            payloads[position] = Some(bytes[from..from + (stop - start) as usize].to_vec());
314            *resident_bytes += stop - start;
315        }
316        Ok(())
317    }
318
319    pub fn decode_frame(&mut self, request: FrameRequest) -> Result<&[u8], DecodeError> {
320        self.core.decode_frame(request)
321    }
322
323    /// Decode only the tiles a viewport covers; see [`Bundle::decode_frame_tiles`].
324    pub fn decode_frame_tiles(
325        &mut self,
326        request: FrameRequest,
327        tiles: TileRect,
328    ) -> Result<&[u8], DecodeError> {
329        self.core.decode_frame_tiles(request, Some(tiles))
330    }
331
332    /// One cell's code on every frame of the axis, in axis order.
333    pub fn decode_series(
334        &mut self,
335        variable_id: u8,
336        column: u32,
337        row: u32,
338    ) -> Result<Vec<u8>, DecodeError> {
339        self.core.decode_series(variable_id, column, row)
340    }
341}
342
343/// The one span covering every span given, or `None` when there are none.
344fn coalesce(spans: impl Iterator<Item = (u64, u64)>) -> Option<(u64, u64)> {
345    spans.reduce(|(low, high), (start, end)| (low.min(start), high.max(end)))
346}
347
348/// The given spans in ascending order, with touching ones joined. Chunks are
349/// strictly adjacent in the file, so a run of neighbouring tiles collapses to
350/// a single range request.
351fn merge_adjacent(spans: impl Iterator<Item = (u64, u64)>) -> Vec<(u64, u64)> {
352    let mut spans: Vec<(u64, u64)> = spans.collect();
353    spans.sort_unstable();
354    let mut merged: Vec<(u64, u64)> = Vec::with_capacity(spans.len());
355    for (start, end) in spans {
356        match merged.last_mut() {
357            Some(last) if start <= last.1 => last.1 = last.1.max(end),
358            _ => merged.push((start, end)),
359        }
360    }
361    merged
362}