Skip to main content

xue/encode/
temporal.rs

1//! Xue temporal grouping, tiling and residual coding — the port of
2//! `xuebuild/temporal.py`.
3//!
4//! Residuals are one-byte modulo-256 wrapping differences. Wrapping
5//! subtraction and addition are lossless for every byte pair, so there is no
6//! residual range check, no signed interpretation, and no RAW fallback.
7//!
8//! Grouping is shared by both container versions: a group is a run of
9//! consecutive frames formed inside a segment of constant step. What differs
10//! is what a group is physically — v1 stores one plane per frame with a
11//! middle anchor, v2 packs the group into each tile's chunk with the
12//! residuals chained against the previous frame.
13
14use crate::format::{crc32, ChunkEntry, GroupEntry, Predictor, TileGeometry, VariableEntry};
15
16use crate::encode::errors::{EncodeError, Result};
17
18pub const GROUP_LENGTH: usize = 6;
19
20pub fn encode_residual(current: &[u8], base: &[u8]) -> Result<Vec<u8>> {
21    if current.len() != base.len() {
22        return Err(EncodeError::conversion("plane lengths differ"));
23    }
24    Ok(current
25        .iter()
26        .zip(base)
27        .map(|(value, anchor)| value.wrapping_sub(*anchor))
28        .collect())
29}
30
31/// Maximal runs of constant step (docs/format.md "segment"): a boundary falls
32/// between two frames exactly where the step changes, so a uniform axis is one
33/// segment and the GFS 240-hour axis is two.
34pub fn split_segments(offsets: &[i64]) -> Result<Vec<Vec<i64>>> {
35    if offsets.windows(2).any(|pair| pair[1] <= pair[0]) {
36        return Err(EncodeError::conversion(
37            "forecast hours must be unique and ascending",
38        ));
39    }
40    let Some(&first) = offsets.first() else {
41        return Err(EncodeError::conversion("time axis is empty"));
42    };
43    let mut segments = vec![vec![first]];
44    let mut step: Option<i64> = None;
45    for pair in offsets.windows(2) {
46        let (previous, current) = (pair[0], pair[1]);
47        if step.is_some_and(|step| current - previous != step) {
48            segments.push(vec![current]);
49        } else {
50            segments.last_mut().expect("non-empty").push(current);
51        }
52        step = Some(current - previous);
53    }
54    Ok(segments)
55}
56
57/// Temporal groups, formed inside segments of constant step so no group
58/// straddles a change of cadence (an ANCHOR residual is then always a
59/// difference between frames one step apart).
60pub fn group_forecast_hours(offsets: &[i64]) -> Result<Vec<Vec<i64>>> {
61    Ok(split_segments(offsets)?
62        .into_iter()
63        .flat_map(|segment| {
64            segment
65                .chunks(GROUP_LENGTH)
66                .map(<[i64]>::to_vec)
67                .collect::<Vec<_>>()
68        })
69        .collect())
70}
71
72/// One tile's block of a group's planes, frame-major and clipped.
73///
74/// `planes` are the group's frames in axis order, each a flat plane of the
75/// grid `geometry` describes. The block is the tile's clipped rectangle, so
76/// the last column and the last row come out narrower or shorter.
77pub fn tile_stack(planes: &[&[u8]], geometry: &TileGeometry, tile: u32) -> Result<Vec<u8>> {
78    let (row, column) = geometry.origin(tile);
79    let (height, width) = geometry.shape(tile);
80    let grid_width = geometry.width as usize;
81    let mut block = Vec::with_capacity(planes.len() * height as usize * width as usize);
82    for plane in planes {
83        if plane.len() != grid_width * geometry.height as usize {
84            return Err(EncodeError::conversion("plane does not match the grid"));
85        }
86        for line in 0..height as usize {
87            let start = (row as usize + line) * grid_width + column as usize;
88            block.extend_from_slice(&plane[start..start + width as usize]);
89        }
90    }
91    Ok(block)
92}
93
94/// The stored bytes of one chunk, in place.
95///
96/// RAW leaves the codes alone — the only encoding precipitation tolerates.
97/// PREVIOUS keeps the first frame whole and replaces every later frame with
98/// its modulo-256 difference against the frame before it in the same chunk,
99/// which is the preceding frame on the axis because a group is contiguous.
100pub fn encode_chunk(block: &mut [u8], predictor: Predictor, stride: usize) -> Result<()> {
101    match predictor {
102        Predictor::Raw => Ok(()),
103        Predictor::Previous => {
104            // Walk backwards so each frame still sees the untouched codes of
105            // the frame before it.
106            let frames = block.len() / stride.max(1);
107            for frame in (1..frames).rev() {
108                let (previous, current) = block.split_at_mut(frame * stride);
109                let previous = &previous[(frame - 1) * stride..];
110                for (target, base) in current[..stride].iter_mut().zip(previous.iter()) {
111                    *target = target.wrapping_sub(*base);
112                }
113            }
114            Ok(())
115        }
116        other => Err(EncodeError::conversion(format!(
117            "predictor {other:?} is not valid in a v2 chunk"
118        ))),
119    }
120}
121
122/// The v2 index tables and uncompressed chunks of one bundle.
123///
124/// `plane` resolves one (frame offset, variable id) pair to its codes. Every
125/// variable shares the file's one axis and therefore its groups, and the
126/// chunks come back in the physical order the spec fixes: group, then tile
127/// row-major, then variable. The planes of a group are looked up once and
128/// then cut tile by tile, so a bundle borrows each plane once rather than
129/// once per tile.
130pub fn build_chunks<'a>(
131    offsets: &[i64],
132    variables: &[VariableEntry],
133    plane: &dyn Fn(i64, u8) -> Result<&'a [u8]>,
134    geometry: &TileGeometry,
135) -> Result<(Vec<GroupEntry>, Vec<(ChunkEntry, Vec<u8>)>)> {
136    let mut groups = Vec::new();
137    let mut chunks = Vec::new();
138    let mut first_frame = 0u16;
139    for group in group_forecast_hours(offsets)? {
140        groups.push(GroupEntry {
141            first_frame,
142            frame_count: group.len() as u8,
143        });
144        first_frame += group.len() as u16;
145        // One lookup per (frame, variable) for the whole group, reused by
146        // every tile.
147        let frames: Vec<Vec<&[u8]>> = variables
148            .iter()
149            .map(|variable| {
150                group
151                    .iter()
152                    .map(|offset| plane(*offset, variable.variable_id))
153                    .collect::<Result<Vec<_>>>()
154            })
155            .collect::<Result<_>>()?;
156        for tile in 0..geometry.count() {
157            let (height, width) = geometry.shape(tile);
158            let stride = height as usize * width as usize;
159            for (variable, planes) in variables.iter().zip(&frames) {
160                let mut block = tile_stack(planes, geometry, tile)?;
161                // The CRC covers the reconstruction, so take it before the
162                // residual chain overwrites the codes in place.
163                let entry = ChunkEntry {
164                    compressed_length: 0,
165                    crc32: crc32(&block),
166                };
167                encode_chunk(&mut block, variable.predictor, stride)?;
168                chunks.push((entry, block));
169            }
170        }
171    }
172    Ok((groups, chunks))
173}