Skip to main content

xue/encode/
ladder.rs

1//! The resolution ladder: the tier names, grids, tiles and decimated codes
2//! of the reduced-resolution rungs a source publishes beside its full tier.
3
4use std::collections::BTreeMap;
5
6use crate::encode::errors::{EncodeError, Result};
7use crate::encode::grid::GridInfo;
8use crate::encode::registry::{Decimation, Registry};
9
10/// The file suffix and STAC tier name of one rung of the resolution ladder:
11/// `half` for factor 2, `quarter` for 4, `eighth` for 8. Any other factor is
12/// a registry bug (`SourceSpec::variant_factors`), reported with the factor.
13///
14/// Mirrors `variant_tier` in `xuebuild/ladder.py`.
15fn tier_name(factor: usize) -> Result<&'static str> {
16    match factor {
17        2 => Ok("half"),
18        4 => Ok("quarter"),
19        8 => Ok("eighth"),
20        _ => Err(EncodeError::conversion(format!(
21            "no tier name for a resolution factor of {factor}"
22        ))),
23    }
24}
25
26/// The grid a ladder rung is published on: the full grid decimated
27/// log2(factor) times (3000 → 1500 → 750 → 375; 721 rows → 361 → 181 → 91),
28/// which is the arithmetic `GridInfo::decimated` repeats rather than one
29/// division by the factor, so a rung's origin and step are exactly the
30/// posters' and the tier above it. Factor 1 is the full grid.
31///
32/// Mirrors `variant_grid` in `xuebuild/ladder.py`.
33fn variant_grid(grid: &GridInfo, factor: usize) -> GridInfo {
34    let mut rung = grid.clone();
35    for _ in 0..factor.trailing_zeros() {
36        rung = rung.decimated();
37    }
38    rung
39}
40
41/// The tile size one bundle is cut with.
42///
43/// A reduced variant divides the source tile by its factor, rounding up, so
44/// tile number n covers the same ground in every tier and a viewport keeps
45/// its tile rectangle across a tier switch (`ceil(ceil(n / 2) / 2) ==
46/// ceil(n / 4)`, so the eighth tier's tile is the half tier's halved twice).
47/// The size is then clamped to the grid, because the format requires
48/// `1 <= tile <= grid` so that a single-tile file states its grid size
49/// exactly — and a regional crop is routinely smaller than the source's tile
50/// (a six-degree showcase window is 24 x 24 cells against the 0.25-degree
51/// grid's 48 x 52 tile). Clamping makes such a file one tile, which is the
52/// right answer: there is nothing left to subdivide. Factor 1 is the full
53/// tier.
54///
55/// Mirrors `bundle_tile(tile, grid, factor=…)` in `xuebuild/ladder.py`.
56pub(super) fn bundle_tile(tile: (usize, usize), grid: &GridInfo, factor: usize) -> (usize, usize) {
57    let tile = (tile.0.div_ceil(factor), tile.1.div_ceil(factor));
58    (tile.0.min(grid.width), tile.1.min(grid.height))
59}
60
61/// Reduced copy of one quantized plane: every `factor`-th row and column of
62/// the full plane from row and column 0 (rows/columns 0, 2, 4, … for the
63/// half tier), matching the poster decimation so every tier shares the same
64/// sample sites — sampling the full plane by 4 or 8 is the same as halving
65/// it twice or three times. `grid` is the full plane's grid.
66///
67/// Mirrors `decimate_codes(codes, grid, factor)` in `xuebuild/ladder.py`.
68pub fn decimate_codes(codes: &[u8], grid: &GridInfo, factor: usize) -> Vec<u8> {
69    let mut reduced =
70        Vec::with_capacity(grid.width.div_ceil(factor) * grid.height.div_ceil(factor));
71    for row in (0..grid.height).step_by(factor) {
72        for column in (0..grid.width).step_by(factor) {
73            reduced.push(codes[row * grid.width + column]);
74        }
75    }
76    reduced
77}
78
79/// Reduced-resolution copy of one quantized plane that keeps peaks: at each
80/// site `decimate_codes` keeps, the largest code within `factor / 2` rows
81/// and columns either side of it, clipped at the plane's edges, so every
82/// cell reaches a site. `nodata_code` counts below every code and is the
83/// site's only when its whole window is nodata.
84///
85/// Mirrors `decimate_peak_codes(codes, grid, factor, nodata_code)` in
86/// `xuebuild/ladder.py`.
87fn decimate_peak_codes(codes: &[u8], grid: &GridInfo, factor: usize, nodata_code: u8) -> Vec<u8> {
88    let half = factor / 2;
89    let mut reduced =
90        Vec::with_capacity(grid.width.div_ceil(factor) * grid.height.div_ceil(factor));
91    for row in (0..grid.height).step_by(factor) {
92        let rows = row.saturating_sub(half)..=(row + half).min(grid.height - 1);
93        for column in (0..grid.width).step_by(factor) {
94            let columns = column.saturating_sub(half)..=(column + half).min(grid.width - 1);
95            let mut peak: Option<u8> = None;
96            for r in rows.clone() {
97                for &code in
98                    &codes[r * grid.width + columns.start()..=r * grid.width + columns.end()]
99                {
100                    if code != nodata_code {
101                        peak = Some(peak.map_or(code, |p| p.max(code)));
102                    }
103                }
104            }
105            reduced.push(peak.unwrap_or(nodata_code));
106        }
107    }
108    reduced
109}
110
111/// One plane's reduced tier: the peak-keeping decimation for a variable
112/// whose registry entry asks for it (the 3.9 µm window, published to show
113/// fires, whose one-cell hot spots a plain decimation drops three times in
114/// four at the half tier), the site's own code otherwise. Mirrors
115/// `decimate_variant_codes` in `xuebuild/ladder.py`.
116fn decimate_variant_codes(
117    variable_id: &str,
118    codes: &[u8],
119    grid: &GridInfo,
120    factor: usize,
121    profile: &str,
122    registry: &Registry,
123) -> Result<Vec<u8>> {
124    if registry.variable(variable_id)?.decimation != Decimation::Peak {
125        return Ok(decimate_codes(codes, grid, factor));
126    }
127    let book = registry.codebook(profile, variable_id)?;
128    let Some(linear) = book.as_linear() else {
129        return Err(EncodeError::conversion(format!(
130            "{variable_id} keeps its peaks only on a linear codebook"
131        )));
132    };
133    Ok(decimate_peak_codes(
134        codes,
135        grid,
136        factor,
137        linear.nodata_code as u8,
138    ))
139}
140
141/// HLS `STREAM-INF` style bandwidth hint: average bits per second needed to
142/// keep up with the 12 fps playback rate while downloading the whole tier.
143pub(super) fn playback_bandwidth(byte_length: usize, frame_count: usize) -> u64 {
144    let fps = 12.0;
145    let value = byte_length as f64 * 8.0 * fps / frame_count.max(1) as f64;
146    (value.round() as u64).max(1)
147}
148
149/// One rung of the ladder: its file suffix, factor, the grid of every family
150/// in play decimated to it, and the codes of every plane sampled from the
151/// full ones.
152pub(super) struct Rung<'a> {
153    pub suffix: String,
154    pub factor: usize,
155    pub grids: Vec<(Option<&'a str>, GridInfo)>,
156    pub codes_by_offset: BTreeMap<i64, Vec<(String, Vec<u8>)>>,
157}
158
159/// The rungs of `factors`, in the order given. `plane_grid` answers the full
160/// grid a plane was quantized on.
161pub(super) fn build_ladder<'a, 'g>(
162    factors: &[usize],
163    grids: &[(Option<&'a str>, GridInfo)],
164    codes_by_offset: &BTreeMap<i64, Vec<(String, Vec<u8>)>>,
165    plane_grid: impl Fn(&str) -> &'g GridInfo,
166    profile: &str,
167    registry: &Registry,
168) -> Result<Vec<Rung<'a>>> {
169    factors
170        .iter()
171        .map(|&factor| {
172            Ok(Rung {
173                suffix: format!(".{}", tier_name(factor)?),
174                factor,
175                grids: grids
176                    .iter()
177                    .map(|(family, family_grid)| (*family, variant_grid(family_grid, factor)))
178                    .collect(),
179                codes_by_offset: codes_by_offset
180                    .iter()
181                    .map(|(offset, planes)| {
182                        Ok((
183                            *offset,
184                            planes
185                                .iter()
186                                .map(|(name, codes)| {
187                                    Ok((
188                                        name.clone(),
189                                        decimate_variant_codes(
190                                            name,
191                                            codes,
192                                            plane_grid(name),
193                                            factor,
194                                            profile,
195                                            registry,
196                                        )?,
197                                    ))
198                                })
199                                .collect::<Result<_>>()?,
200                        ))
201                    })
202                    .collect::<Result<_>>()?,
203            })
204        })
205        .collect::<Result<_>>()
206}
207
208/// One tier of one bundle, as a write task: the full tier (factor 1, no
209/// suffix) or a rung of the ladder.
210pub(super) struct Tier<'a> {
211    pub bundle_id: &'a str,
212    pub suffix: &'a str,
213    pub factor: usize,
214    pub grid: &'a GridInfo,
215    pub codes: &'a BTreeMap<i64, Vec<(String, Vec<u8>)>>,
216}
217
218#[cfg(test)]
219mod ladder_tests {
220    use super::{bundle_tile, decimate_codes, tier_name, variant_grid};
221    use crate::encode::grid::GridInfo;
222
223    #[test]
224    fn a_rung_halves_the_tile_once_per_doubling() {
225        // The satellite tile against the disk, and the 0.25° tile against
226        // the GFS grid: `ceil(n / f)` is `ceil` applied once per halving.
227        let disk = GridInfo::new(3000, 3000, 80.7, 60.0, 0.04, -0.04);
228        assert_eq!(bundle_tile((64, 64), &disk, 1), (64, 64));
229        assert_eq!(bundle_tile((64, 64), &variant_grid(&disk, 2), 2), (32, 32));
230        assert_eq!(bundle_tile((64, 64), &variant_grid(&disk, 4), 4), (16, 16));
231        assert_eq!(bundle_tile((64, 64), &variant_grid(&disk, 8), 8), (8, 8));
232        let world = GridInfo::new(1440, 721, -180.0, 90.0, 0.25, -0.25);
233        assert_eq!(bundle_tile((48, 52), &world, 1), (48, 52));
234        assert_eq!(bundle_tile((48, 52), &variant_grid(&world, 2), 2), (24, 26));
235        assert_eq!(bundle_tile((48, 52), &variant_grid(&world, 4), 4), (12, 13));
236        assert_eq!(bundle_tile((48, 52), &variant_grid(&world, 8), 8), (6, 7));
237        // A grid smaller than the tile clamps to itself in every tier.
238        let window = GridInfo::new(24, 24, 0.0, 6.0, 0.25, -0.25);
239        assert_eq!(bundle_tile((48, 52), &window, 1), (24, 24));
240        assert_eq!(bundle_tile((48, 52), &variant_grid(&window, 8), 8), (3, 3));
241    }
242
243    #[test]
244    fn the_rung_grids_are_the_full_grid_decimated_once_per_doubling() {
245        let world = GridInfo::new(1440, 721, -180.0, 90.0, 0.25, -0.25);
246        for (factor, width, height) in [(1, 1440, 721), (2, 720, 361), (4, 360, 181), (8, 180, 91)]
247        {
248            let rung = variant_grid(&world, factor);
249            assert_eq!(
250                (rung.width, rung.height),
251                (width, height),
252                "factor {factor}"
253            );
254            assert_eq!(rung.longitude_step, 0.25 * factor as f64, "factor {factor}");
255            assert_eq!(rung.first_latitude, 90.0);
256        }
257        let disk = GridInfo::new(3000, 3000, 80.7, 60.0, 0.04, -0.04);
258        assert_eq!(variant_grid(&disk, 8).width, 375);
259        assert_eq!(tier_name(2).unwrap(), "half");
260        assert_eq!(tier_name(4).unwrap(), "quarter");
261        assert_eq!(tier_name(8).unwrap(), "eighth");
262        assert!(tier_name(16).unwrap_err().to_string().contains("16"));
263        assert!(tier_name(3).is_err());
264    }
265
266    #[test]
267    fn sampling_by_four_or_eight_is_repeated_halving() {
268        // An odd-sized plane, so every rung keeps its ceiling row and column.
269        let grid = GridInfo::new(13, 11, 0.0, 10.0, 1.0, -1.0);
270        let codes: Vec<u8> = (0..(13 * 11) as u32)
271            .map(|index| (index * 7 % 251) as u8)
272            .collect();
273        let half = decimate_codes(&codes, &grid, 2);
274        assert_eq!(half.len(), 7 * 6);
275        let half_grid = variant_grid(&grid, 2);
276        let quarter = decimate_codes(&half, &half_grid, 2);
277        assert_eq!(decimate_codes(&codes, &grid, 4), quarter);
278        assert_eq!(quarter.len(), 4 * 3);
279        let eighth = decimate_codes(&quarter, &variant_grid(&half_grid, 2), 2);
280        assert_eq!(decimate_codes(&codes, &grid, 8), eighth);
281        assert_eq!(eighth.len(), 2 * 2);
282        // Row and column 0 of the full plane head every rung.
283        assert_eq!(eighth[0], codes[0]);
284        assert_eq!(eighth[1], codes[8]);
285        assert_eq!(eighth[2], codes[8 * 13]);
286    }
287}