Modern Apps git

← Modern-Apps.git

tilecodec: planet5 tile format, zstd dictionaries + v11 bodies (#planet5)

Commit
063fd0c020248da962667ccb10bc0eb1e54acdf6
Author
Vayun Mathur <[email protected]>
When
2026-11-14 00:53 UTC (22 days ago)
Parents
10c69d6
Owner decision (2026-11-14): ship "balanced" with the planet5 format
changes for a ~60 GB planet. This is the tile half of the format.

Header v10 (FORMAT_VERSION_HEADER_V10) means exactly one thing:
bodies are zstd frames that may reference a trained dictionary
(COMPRESSION_ZSTD_DICT = 3). The dictionaries live in a section
between the root index and the leaves, so the 128-byte header needs
no new field: its extent is root_offset + root_len .. leaf_offset.
Section wire: "MZD1", u32 count, then count x (u32 len, zstd dict).
Each frame names its dictionary in its frame header, so the decoder
loads all of them and needs no zoom-to-dictionary mapping.

- zdict.rs: ZDicts parse/serialize, validated on open; decode through
  a per-thread ruzstd FrameDecoder with the dictionaries preloaded
  (loading builds entropy tables, far dearer than a tile). Pure Rust,
  so the Android cdylib keeps its no-C-toolchain rule.
- read: decompress_with(compression, stored, dicts); MamapsArchive
  fetches the section once on open (inside the 16 KiB prefix when it
  fits, else one extra read) and threads it through tile() and the
  batched tiles(); read_all/open_prefix get zdicts_in/zdict_extent.
- header: parse accepts v8, v9 and v10 (v10 iff compression 3) and
  checks the dictionary section has room; serialize stamps v10 for
  compression 3. A v8/v9-only reader (planet4 apps) refuses v10
  cleanly, which is what keeps them on planet4.
- write: Options.zdicts writes the section and the v10 header;
  bodies are appended pre-compressed by the generator.
- body v11 (FORMAT_VERSION_V11): a v10 body whose heightmap samples
  are MED (LOCO-I) predicted zigzag residuals in the same u16 slots,
  mod 2^16 so any cliff round-trips. Lossless; serialize_into_v11
  and Body::parse decode it back to the identical model. Measured
  -1.15 GB on the planet sample at zstd-19.

Planet4 (v9) archives still read unchanged: the renderer's real-
archive suite passes 6/6 on today's 81.3 GB world.mamaps with this
reader.

Verified: cargo test -p tilecodec --features write (195 pass; new
tests round-trip a v11 heightmap including a wrapping residual, and a
v10 archive through MamapsArchive, read_all and zdict_extent).

Diff

library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex dae0f1df08..b30dd6a745 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -77,6 +77,6 @@ pub use model::{     ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG, ROOF_ORIENT_MAX, ROOF_PYRAMIDAL, ROOF_SHAPE_MAX,     ROOF_SKILLION, };-pub use emit::{Scratch, serialize, serialize_into, serialize_into_v10};+pub use emit::{Scratch, serialize, serialize_into, serialize_into_v10, serialize_into_v11}; pub(crate) use codec::parse_layer; pub(crate) use tables::align4;
library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex 73b616675d..1c47110d51 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -111,10 +111,12 @@ impl Body {         if version != crate::mamaps::header::FORMAT_VERSION             && version != crate::mamaps::header::FORMAT_VERSION_V9             && version != crate::mamaps::header::FORMAT_VERSION_V10+            && version != crate::mamaps::header::FORMAT_VERSION_V11         {             return err(format!("unsupported .mamaps body version {version}"));         }-        let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10;+        let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11;+        let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10 || v11;         let raw_len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;         if raw_len != buf.len() {             return err(format!(@@ -264,7 +266,10 @@ impl Body {                 buildings = table;             }             if has_heightmap {-                let (grid, used) = parse_heightmap(&buf[at..])?;+                let (mut grid, used) = parse_heightmap(&buf[at..])?;+                if v11 {+                    super::tables::unresidual_heightmap(&mut grid);+                }                 at += used;                 heightmap = Some(grid);             }
library/tilecodec/src/main/rust/src/mamaps/body/emit.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rsindex a75c620d19..b7031ce457 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs@@ -45,6 +45,12 @@ pub fn serialize_into_v10<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&     serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION_V10) } +/// Serialise a planet5 v11 body: v10 records and side tables, with the heightmap stored as MED+/// residuals (see [`crate::mamaps::header::FORMAT_VERSION_V11`]). Lossless; same model back.+pub fn serialize_into_v11<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [u8]> {+    serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION_V11)+}+ fn serialize_into_version<'s>(     body: &Body,     scratch: &'s mut Scratch,@@ -281,7 +287,9 @@ fn serialize_into_version<'s>(         }         let out = &mut payloads[i];         out.clear();-        if version == crate::mamaps::header::FORMAT_VERSION_V10 {+        if version == crate::mamaps::header::FORMAT_VERSION_V10+            || version == crate::mamaps::header::FORMAT_VERSION_V11+        {             write_v10_layer_payload(layer, out)?;         } else {             write_full_layer_payload(layer, out);@@ -311,7 +319,9 @@ fn serialize_into_version<'s>(     if !body.buildings.is_empty() {         body_flags |= BODY_FLAG_BUILDING_TABLE;     }-    let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10;+    let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10+        || version == crate::mamaps::header::FORMAT_VERSION_V11;+    let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11;     if body.heightmap.is_some() {         body_flags |= BODY_FLAG_HEIGHTMAP;     }@@ -386,7 +396,11 @@ fn serialize_into_version<'s>(         }     }     if let Some(grid) = &body.heightmap {-        serialize_heightmap(grid, assembled);+        if v11 {+            super::tables::serialize_heightmap_residual(grid, assembled);+        } else {+            serialize_heightmap(grid, assembled);+        }     }     if !body.carriageways.is_empty() {         // The convention only reaches the wire alongside a table, so a body that sets one without
library/tilecodec/src/main/rust/src/mamaps/body/tables.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rsindex c2e88be74a..c6f10c0ea2 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs@@ -564,3 +564,62 @@ pub fn serialize_heightmap(grid: &Heightmap, out: &mut Vec<u8>) {         out.push(0);     } }++/// The MED (LOCO-I) prediction for sample `(r, c)` of a `d x d` grid from already-known+/// neighbours: left, up and up-left. First row predicts from the left, first column from above,+/// the first sample from sea level (32768). Shared by the encoder and the decoder so they agree.+#[inline]+fn med_predict(s: &[u16], d: usize, r: usize, c: usize) -> u16 {+    if r == 0 && c == 0 {+        return 32768;+    }+    if r == 0 {+        return s[c - 1];+    }+    if c == 0 {+        return s[(r - 1) * d];+    }+    let (l, u, ul) = (s[r * d + c - 1] as i32, s[(r - 1) * d + c] as i32, s[(r - 1) * d + c - 1] as i32);+    let (lo, hi) = (l.min(u), l.max(u));+    let p = if ul >= hi {+        lo+    } else if ul <= lo {+        hi+    } else {+        l + u - ul+    };+    p as u16+}++/// Serialise a heightmap as v11 MED residuals: the same `dim` + `dim*dim` u16 layout as+/// [`serialize_heightmap`], each sample replaced by `zigzag((sample - prediction) mod 2^16)`.+/// Flat or smoothly sloping ground becomes runs of tiny values, which is what zstd needs.+pub fn serialize_heightmap_residual(grid: &Heightmap, out: &mut Vec<u8>) {+    let d = grid.dim as usize;+    out.extend_from_slice(&grid.dim.to_le_bytes());+    for r in 0..d {+        for c in 0..d {+            let v = grid.samples[r * d + c];+            let e = v.wrapping_sub(med_predict(&grid.samples, d, r, c)) as i16;+            let zz = ((e << 1) ^ (e >> 15)) as u16;+            out.extend_from_slice(&zz.to_le_bytes());+        }+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}++/// Undo [`serialize_heightmap_residual`] in place, in raster order so every prediction reads+/// samples already reconstructed.+pub(crate) fn unresidual_heightmap(grid: &mut Heightmap) {+    let d = grid.dim as usize;+    for r in 0..d {+        for c in 0..d {+            let zz = grid.samples[r * d + c];+            let e = ((zz >> 1) as i16) ^ -((zz & 1) as i16);+            let p = med_predict(&grid.samples, d, r, c);+            grid.samples[r * d + c] = p.wrapping_add(e as u16);+        }+    }+}
library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsindex b3dfacbfa2..f68b095e74 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -23,8 +23,9 @@ mod types; mod tests;  pub use consts::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, FLAG_BODIES_COMPRESSED,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, FLAG_BODIES_COMPRESSED,     FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,-    FORMAT_VERSION_V9, FORMAT_VERSION_V10, HEADER_LEN, MAGIC, MAX_ZOOM,+    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, FORMAT_VERSION_V10, FORMAT_VERSION_V11, HEADER_LEN, MAGIC,+    MAX_ZOOM, }; pub use types::Header;
library/tilecodec/src/main/rust/src/mamaps/header/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rsindex 6e370331c0..efc219854a 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -82,6 +82,20 @@ pub const FORMAT_VERSION_V9: u8 = 9; /// body, not the header — but builders ship v10 bodies under v9+ headers. pub const FORMAT_VERSION_V10: u8 = 10; +/// The planet5 *header* version: bodies are zstd frames that reference trained dictionaries+/// ([`COMPRESSION_ZSTD_DICT`]), stored in a section between the root index and the leaves.+///+/// Planet5 size work. Shares the number 10 with the v10 *body* version but lives in a different+/// byte (header byte 7 vs body byte 3); the two never meet. A v8/v9-only reader refuses a v10+/// header cleanly, which is what keeps planet4 apps on planet4. This reader still speaks v8 and+/// v9 headers unchanged.+pub const FORMAT_VERSION_HEADER_V10: u8 = 10;++/// Body version 11: a v10 body whose heightmap samples are MED-predicted (LOCO-I) zigzag+/// residuals rather than raw `u16`s. Lossless (mod 2^16 arithmetic); only the entropy of the+/// heightmap section changes, which is what makes it compress. Planet5 only.+pub const FORMAT_VERSION_V11: u8 = 11;+ pub const HEADER_LEN: usize = 128;  /// Bodies are compressed frames; clear means the body is stored raw.@@ -131,6 +145,10 @@ pub const COMPRESSION_DEFLATE: u8 = 1; /// `ruzstd`) so the aarch64-linux-android cdylib keeps its no-C-toolchain /// property — see the crate docs in `Cargo.toml`. pub const COMPRESSION_ZSTD: u8 = 2;+/// zstd frames that may reference a trained dictionary by the dictionary id in their frame header+/// (planet5, header version [`FORMAT_VERSION_HEADER_V10`] only). The dictionaries live in the+/// section between the root index and the leaves (see [`crate::mamaps::zdict`]).+pub const COMPRESSION_ZSTD_DICT: u8 = 3;  /// The deepest zoom a `tile_id_lo` can span inside one leaf. See [`crate::mamaps::index`]. pub const MAX_ZOOM: u8 = 22;
library/tilecodec/src/main/rust/src/mamaps/header/parse.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rsindex 182bbbb68b..7ba3edced2 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs@@ -7,8 +7,9 @@ use crate::proto::{err, Result};  use super::consts::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, FLAG_LEAF_LEN_64, FORMAT_VERSION,-    FORMAT_VERSION_V9, HEADER_LEN, KNOWN_FLAGS, MAGIC, MAX_ZOOM,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, FLAG_LEAF_LEN_64,+    FORMAT_VERSION, FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, HEADER_LEN, KNOWN_FLAGS, MAGIC,+    MAX_ZOOM, }; use super::types::Header; @@ -32,9 +33,18 @@ impl Header {             return err("not a .mamaps archive (bad magic)");         }         let version = buf[7];-        if version != FORMAT_VERSION && version != FORMAT_VERSION_V9 {+        if version != FORMAT_VERSION && version != FORMAT_VERSION_V9 && version != FORMAT_VERSION_HEADER_V10 {             return err(format!(-                "unsupported .mamaps format version {version} (this reader speaks v{FORMAT_VERSION} and v{FORMAT_VERSION_V9})",+                "unsupported .mamaps format version {version} (this reader speaks v{FORMAT_VERSION}, \+                 v{FORMAT_VERSION_V9} and v{FORMAT_VERSION_HEADER_V10})",+            ));+        }+        // Dictionary compression is exactly what makes a header v10, both ways.+        if (version == FORMAT_VERSION_HEADER_V10) != (buf[12] == COMPRESSION_ZSTD_DICT) {+            return err(format!(+                "a .mamaps v{version} header with compression {} (v{FORMAT_VERSION_HEADER_V10} means \+                 dictionary-zstd bodies and nothing else)",+                buf[12]             ));         }         let u16_at = |o: usize| u16::from_le_bytes([buf[o], buf[o + 1]]);@@ -134,7 +144,7 @@ impl Header {     pub(super) fn check(&self) -> Result<()> {         if !matches!(             self.compression,-            COMPRESSION_NONE | COMPRESSION_DEFLATE | COMPRESSION_ZSTD+            COMPRESSION_NONE | COMPRESSION_DEFLATE | COMPRESSION_ZSTD | COMPRESSION_ZSTD_DICT         ) {             return err(format!("unknown .mamaps compression {}", self.compression));         }@@ -195,6 +205,11 @@ impl Header {                 crate::mamaps::index::ROOT_ENTRY_LEN,             ));         }+        if self.compression == COMPRESSION_ZSTD_DICT+            && self.root_offset + self.root_len as u64 > self.leaf_offset+        {+            return err("a .mamaps v10 header leaves no room for its dictionary section");+        }         if self.bodies_written > self.tiles_addressed {             return err("a .mamaps header stores more bodies than it addresses tiles");         }
library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs b/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rsindex 541edfcabe..b89583ad32 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs@@ -3,7 +3,8 @@ //! Pure moves out of the former single-file header module; nothing here changed.  use super::consts::{-    FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FORMAT_VERSION, FORMAT_VERSION_V9, HEADER_LEN, MAGIC,+    COMPRESSION_ZSTD_DICT, FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FORMAT_VERSION,+    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, HEADER_LEN, MAGIC, }; use super::types::Header; @@ -15,7 +16,13 @@ impl Header {         // Compressed leaves are a v9 frame: the flag is unknown to a v8         // reader, which refuses cleanly rather than misreading the leaf         // section. Everything else keeps the v8 byte (and v8 readers).-        out.push(if (self.flags & FLAG_LEAVES_COMPRESSED) != 0 { FORMAT_VERSION_V9 } else { FORMAT_VERSION });+        out.push(if self.compression == COMPRESSION_ZSTD_DICT {+            FORMAT_VERSION_HEADER_V10+        } else if (self.flags & FLAG_LEAVES_COMPRESSED) != 0 {+            FORMAT_VERSION_V9+        } else {+            FORMAT_VERSION+        });         out.extend_from_slice(&(HEADER_LEN as u16).to_le_bytes());         out.extend_from_slice(&self.flags.to_le_bytes());         out.push(self.compression);
library/tilecodec/src/main/rust/src/mamaps/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/mod.rsindex d5514c54cf..c4da552d0c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -47,6 +47,7 @@ pub mod dict; pub mod header; pub mod index; pub mod read;+pub mod zdict;  // The archive section index (ArchiveView + kind consts) is read-side: Android reads the // graph/transit/poi sidecars bundled in a .mamaps. Only the writer below is write-gated.
library/tilecodec/src/main/rust/src/mamaps/read.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read.rs b/library/tilecodec/src/main/rust/src/mamaps/read.rsindex a7bd8e815b..104e2253b3 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read.rs@@ -55,6 +55,6 @@ use crate::stream::{RangeReader, OPEN_PREFIX_BYTES}; use std::cell::RefCell;  pub use archive::MamapsArchive;-pub use helpers::{decompress, open_prefix, read_all, MIN_FILE_LEN};+pub use helpers::{decompress, decompress_with, open_prefix, read_all, zdict_extent, zdicts_in, MIN_FILE_LEN}; pub use leaf_cache::{LeafCache, DEFAULT_LEAF_CACHE_BYTES, DEFAULT_LEAF_CACHE_CAPACITY}; pub use overlay::{OverlayArchive, TileSource, base_matches, prune_tombstones};
library/tilecodec/src/main/rust/src/mamaps/read/archive.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rsindex 8ffa44b45c..c371b41c0b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -1,4 +1,4 @@-use super::helpers::decompress;+use super::helpers::{decompress_with, zdict_extent}; use super::leaf_cache::LeafCache; use crate::mamaps::body::Body; use crate::mamaps::dict::Dictionary;@@ -29,6 +29,8 @@ pub struct MamapsArchive<R: RangeReader> {     pub dictionary: Dictionary,     root: Vec<RootEntry>,     leaves: Arc<LeafCache>,+    /// The archive's trained dictionaries (planet5 v10 headers), fetched once on open.+    zdicts: Option<Arc<crate::mamaps::zdict::ZDicts>>, }  /// Where one tile's bytes live, decided from the root index plus the shared leaf cache.@@ -44,6 +46,11 @@ enum TileAddress { }  impl<R: RangeReader> MamapsArchive<R> {+    /// The archive's trained dictionaries, when its bodies use them (planet5).+    pub fn zdicts(&self) -> Option<&crate::mamaps::zdict::ZDicts> {+        self.zdicts.as_deref()+    }+     /// The reader this archive was opened on.     ///     /// So a caller can act on something it only learns from the header — the `build_id`, which@@ -99,7 +106,22 @@ impl<R: RangeReader> MamapsArchive<R> {                 root.len(),             ));         }-        Ok(MamapsArchive { reader, header, dictionary, root, leaves })+        // Planet5: one more read on open for the dictionaries, never one per tile.+        let zdicts = if header.compression == crate::mamaps::header::COMPRESSION_ZSTD_DICT {+            let (start, end) = zdict_extent(&header)?;+            let bytes = if end <= prefix.len() as u64 {+                prefix[start as usize..end as usize].to_vec()+            } else {+                reader.read(start, (end - start) as u32)?+            };+            if bytes.len() as u64 != end - start {+                return err("a .mamaps dictionary section was cut short");+            }+            Some(Arc::new(crate::mamaps::zdict::ZDicts::parse(&bytes)?))+        } else {+            None+        };+        Ok(MamapsArchive { reader, header, dictionary, root, leaves, zdicts })     }      /// The decoded body for a tile, or `None` when the archive does not hold it.@@ -265,7 +287,7 @@ impl<R: RangeReader> MamapsArchive<R> {                 let (offset, length) = body_requests[i];                 match found.get(i) {                     Some(Ok(stored)) if stored.len() == length as usize => {-                        match decompress(self.header.compression, stored) {+                        match decompress_with(self.header.compression, stored, self.zdicts.as_deref()) {                             Ok(raw) => match Body::parse(&raw) {                                 Ok(body) => done[*slot] = Some(Ok(Some(body))),                                 Err(e) => done[*slot] = Some(Err(e)),@@ -397,7 +419,7 @@ impl<R: RangeReader> MamapsArchive<R> {             return err("a .mamaps leaf entry runs past the tile data section");         }         let stored = self.exact(self.header.data_offset + at, entry.length, "a tile body")?;-        Ok(Some(decompress(self.header.compression, &stored)?))+        Ok(Some(decompress_with(self.header.compression, &stored, self.zdicts.as_deref())?))     }      /// The parsed leaf a root entry addresses, from the shared cache or over the wire.
library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rsindex 777ed7baf0..57bccfbc8c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs@@ -1,7 +1,7 @@ use crate::mamaps::body::Body; use crate::mamaps::dict::Dictionary; use crate::mamaps::header::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, Header, HEADER_LEN,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, Header, HEADER_LEN, }; use crate::mamaps::index::{self, RootEntry}; use crate::proto::{Error, Result, err};@@ -13,7 +13,37 @@ use std::io::Read as _; /// frame precisely so this is possible: the length is known before the first byte is inflated, so /// there is no grow-and-copy and no guess. pub fn decompress(compression: u8, stored: &[u8]) -> Result<Vec<u8>> {+    decompress_with(compression, stored, None)+}++/// [`decompress`] for an archive that may carry trained dictionaries (planet5,+/// [`COMPRESSION_ZSTD_DICT`]): `dicts` is that archive's section.+pub fn decompress_with(+    compression: u8,+    stored: &[u8],+    dicts: Option<&crate::mamaps::zdict::ZDicts>,+) -> Result<Vec<u8>> {     match compression {+        COMPRESSION_ZSTD_DICT => {+            let Some(dicts) = dicts else {+                return err("a dictionary-zstd .mamaps body was read without its dictionaries");+            };+            let raw_len = Body::raw_len(stored)? as usize;+            let header_len = crate::mamaps::body::BODY_HEADER_LEN;+            if raw_len < header_len {+                return err("a .mamaps body frame declares a length shorter than a body header");+            }+            let mut out = vec![0u8; raw_len];+            out[..header_len].copy_from_slice(&stored[..header_len]);+            let n = dicts.decode_into(&stored[header_len..], &mut out[header_len..])?;+            if header_len + n != raw_len {+                return err(format!(+                    "a .mamaps body declared {raw_len} bytes but decoded to {}",+                    header_len + n+                ));+            }+            Ok(out)+        }         COMPRESSION_NONE => Ok(stored.to_vec()),         COMPRESSION_DEFLATE => {             let raw_len = Body::raw_len(stored)? as usize;@@ -105,6 +135,7 @@ pub fn open_prefix(bytes: &[u8]) -> Result<(Header, Dictionary, Vec<RootEntry>)> pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> {     let (header, dictionary, root) = open_prefix(bytes)?;     dictionary.check_matches_schema()?;+    let zdicts = zdicts_in(&header, bytes)?;     let mut out = Vec::new();     for entry in &root {         let raw_len = entry.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;@@ -128,7 +159,7 @@ pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> {             out.push((                 entry.base_tile_id + tile.tile_id_lo as u64,                 tile.run_length,-                decompress(header.compression, &bytes[start..end])?,+                decompress_with(header.compression, &bytes[start..end], zdicts.as_ref())?,             ));         }     }@@ -141,3 +172,26 @@ pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> { /// A sanity bound so a reader can reject a prefix that is not a `.mamaps` file at all before /// allocating anything, without depending on the reader's own constant. pub const MIN_FILE_LEN: usize = HEADER_LEN;++/// The dictionary section of an archive held whole in memory, or `None` when its bodies use none.+pub fn zdicts_in(header: &Header, bytes: &[u8]) -> Result<Option<crate::mamaps::zdict::ZDicts>> {+    if header.compression != COMPRESSION_ZSTD_DICT {+        return Ok(None);+    }+    let (start, end) = zdict_extent(header)?;+    if end as usize > bytes.len() {+        return err("a .mamaps dictionary section runs past the file");+    }+    Ok(Some(crate::mamaps::zdict::ZDicts::parse(&bytes[start as usize..end as usize])?))+}++/// Where a v10 archive's dictionary section lives: from the end of the root index to the start+/// of the leaves (see [`crate::mamaps::zdict`]).+pub fn zdict_extent(header: &Header) -> Result<(u64, u64)> {+    let start = header.root_offset + header.root_len as u64;+    let end = header.leaf_offset;+    if end < start || end - start > crate::mamaps::zdict::ZDICT_MAX_BYTES {+        return err("a .mamaps dictionary section has an impossible extent");+    }+    Ok((start, end))+}
library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rsindex 3b48146b08..5ba0f48758 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -385,3 +385,65 @@ fn a_leaf_whose_data_span_would_exceed_u32_max_is_split_and_common_case_stays_by     assert_eq!(hdr.leaf_count as usize, (5000+4096-1)/4096);     eprintln!("end-to-end: 5000 tiles → leaf_count={} leaf_len={}", hdr.leaf_count, hdr.leaf_len); }++/// Planet5 v11 bodies: the heightmap is stored as MED residuals and reads back exactly,+/// including a cliff that wraps the residual past i16 (mod 2^16 arithmetic).+#[test]+fn a_v11_heightmap_round_trips_through_its_residuals() {+    use crate::mamaps::body::{serialize_into_v10, serialize_into_v11, Heightmap, Scratch};+    let mut body = body_for(3);+    let dim = 9u16;+    let samples: Vec<u16> = (0..81u32)+        .map(|i| match i {+            40 => 0,           // a pit at the bottom of the u16 range+            41 => u16::MAX,    // beside a spike at the top: residual wraps+            _ => (32768 + (i % 9) * 7 + (i / 9) * 3) as u16,+        })+        .collect();+    body.heightmap = Some(Heightmap { dim, samples });+    let mut s = Scratch::default();+    let v11 = serialize_into_v11(&body, &mut s).expect("v11").to_vec();+    assert_eq!(v11[3], crate::mamaps::header::FORMAT_VERSION_V11);+    assert_eq!(Body::parse(&v11).expect("parse v11"), body);+    let mut s = Scratch::default();+    let v10 = serialize_into_v10(&body, &mut s).expect("v10").to_vec();+    assert_eq!(v10.len(), v11.len(), "same layout, only the sample values differ");+    assert_eq!(Body::parse(&v10).expect("parse v10"), body);+}++/// Planet5 v10 headers: bodies are zstd frames decoded through the archive's dictionary section,+/// which sits between the root and the leaves. Opens in one prefix read when the section fits,+/// reads back every tile through both the range reader and `read_all`, and a v8/v9-only header+/// version check would see byte 10 and refuse it.+#[test]+fn a_dictionary_archive_round_trips() {+    use crate::mamaps::body::serialize;+    use crate::mamaps::write::compress_body_zstd;+    use crate::mamaps::zdict::ZDicts;+    // No trained dictionary here (tilecodec carries no trainer): an empty section, frames without+    // a dictionary id. The tile_build planet5 transcoder tests the trained path end to end.+    let section = ZDicts::serialize(&[]);+    let mut writer =+        StreamWriter::new(Options { zdicts: Some(section.clone()), ..Options::default() }).expect("options");+    let tiles = [(0u8, 0u64, 0u64, 1i16), (1, 0, 0, 2), (1, 1, 1, 3), (2, 3, 1, 2)];+    for &(z, x, y, seed) in &tiles {+        let raw = serialize(&body_for(seed)).expect("serialize");+        writer.append_stored(tile_id(z, x, y), &compress_body_zstd(&raw)).expect("append");+    }+    let bytes = writer.finish().expect("finish");+    assert_eq!(bytes[7], crate::mamaps::header::FORMAT_VERSION_HEADER_V10, "header v10");+    let a = MamapsArchive::open(Counting { bytes: bytes.clone(), requests: RefCell::new(Vec::new()) })+        .expect("open");+    assert_eq!(a.header.compression, crate::mamaps::header::COMPRESSION_ZSTD_DICT);+    assert_eq!(a.zdicts().expect("dicts").dictionaries().len(), 0);+    assert_eq!(a.reader().requests.borrow().len(), 1, "the section fits the prefix: no extra read");+    for &(z, x, y, seed) in &tiles {+        let got = a.tile(z, x as u32, y as u32).expect("tile").expect("present");+        assert_eq!(got, body_for(seed));+    }+    let all = crate::mamaps::read::read_all(&bytes).expect("read_all");+    assert_eq!(all.len(), tiles.len(), "one entry per tile (no run: the ids are not consecutive)");+    // The section is exactly where the header implies it.+    let (start, end) = crate::mamaps::read::zdict_extent(&a.header).expect("extent");+    assert_eq!(&bytes[start as usize..end as usize], &section[..]);+}
library/tilecodec/src/main/rust/src/mamaps/write/options.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs b/library/tilecodec/src/main/rust/src/mamaps/write/options.rsindex 7d4d5b4c7d..e99a33564c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -22,6 +22,11 @@ pub struct Options {     /// Bodies are zstd frames (header `compression` 2) rather than DEFLATE. Only meaningful with     /// `compress`; the generator compresses (see `compress_body_zstd_level`) and appends stored.     pub zstd: bool,+    /// Planet5: the serialized dictionary section ([`crate::mamaps::zdict::ZDicts::serialize`])+    /// the appended bodies were compressed against. Set, the header becomes v10 with compression+    /// [`crate::mamaps::header::COMPRESSION_ZSTD_DICT`] and the section is written between the+    /// root index and the leaves. Bodies must be appended already compressed.+    pub zdicts: Option<Vec<u8>>,     /// Store each leaf as one raw-DEFLATE frame rather than raw fixed-stride entries.     ///     /// The root stays raw either way — same 32-byte stride, same opening-prefix budget — and@@ -65,6 +70,7 @@ impl Default for Options {             build_id_from_content: false,             compress: true,             zstd: false,+            zdicts: None,             compress_leaves: true,             rings_validated: false,             leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,
library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rsindex 1a0e0764ba..7b4c6fd34c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs@@ -133,7 +133,8 @@ impl StreamWriter {         // The dictionary starts where the 128-byte v8 header ends.         let dict_offset = HEADER_LEN as u64;         let root_offset = dict_offset + dictionary.len() as u64;-        let leaf_offset = root_offset + root_bytes.len() as u64;+        let zdict_bytes: &[u8] = self.options.zdicts.as_deref().unwrap_or(&[]);+        let leaf_offset = root_offset + root_bytes.len() as u64 + zdict_bytes.len() as u64;         let data_offset = leaf_offset + leaf_bytes.len() as u64;         let data_len = self.data.len(); @@ -141,6 +142,8 @@ impl StreamWriter {             flags,             compression: if !self.options.compress {                 COMPRESSION_NONE+            } else if self.options.zdicts.is_some() {+                crate::mamaps::header::COMPRESSION_ZSTD_DICT             } else if self.options.zstd {                 crate::mamaps::header::COMPRESSION_ZSTD             } else {@@ -174,6 +177,7 @@ impl StreamWriter {         prefix.extend_from_slice(&header.serialize());         prefix.extend_from_slice(&dictionary);         prefix.extend_from_slice(&root_bytes);+        prefix.extend_from_slice(zdict_bytes);         prefix.extend_from_slice(&leaf_bytes);         debug_assert_eq!(prefix.len() as u64, data_offset);         Ok((Header::parse(&prefix)?, prefix))
library/tilecodec/src/main/rust/src/mamaps/zdict.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/zdict.rs b/library/tilecodec/src/main/rust/src/mamaps/zdict.rsnew file mode 100644index 0000000000..87b41d408a--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/zdict.rs@@ -0,0 +1,122 @@+//! Trained zstd dictionaries for planet5 tile bodies ([`COMPRESSION_ZSTD_DICT`]).+//!+//! A `.mamaps` body is small (median under 1 KB at z13) and compressed on its own so it can be+//! fetched by range, which leaves most of zstd's window empty: every body re-learns the same+//! record layouts, kinds and varint patterns. A dictionary trained per zoom band supplies that+//! context once for the whole archive — measured −8.5 % (US West, today's settings) to −13 %+//! (coarser geometry) of tile data over zstd-19 alone.+//!+//! # Wire+//!+//! The section sits between the root index and the leaves; its extent is implied by the header+//! (`root_offset + root_len .. leaf_offset`), so the 128-byte header needs no new field:+//!+//! ```text+//! [magic "MZD1"][u32 count] then count x { [u32 len][len bytes: a zstd dictionary] }+//! ```+//!+//! Each dictionary carries its own id and every frame names the dictionary it was compressed+//! with in its frame header, so the decoder needs no zoom-to-dictionary mapping: it holds all of+//! them and the frame picks. A frame without a dictionary id decodes as plain zstd.+//!+//! The decoder is `ruzstd` (pure Rust) like the plain-zstd path, so the Android cdylib keeps its+//! no-C-toolchain property. One decoder per thread per archive is kept with the dictionaries+//! already loaded — loading builds the entropy tables, which costs far more than a tile.+//!+//! [`COMPRESSION_ZSTD_DICT`]: crate::mamaps::header::COMPRESSION_ZSTD_DICT++use crate::proto::{err, Error, Result};+use std::cell::RefCell;+use std::sync::atomic::{AtomicU64, Ordering};++pub const ZDICT_MAGIC: &[u8; 4] = b"MZD1";+/// A sanity bound on the section (5 dictionaries of 112 KiB is ~560 KB).+pub const ZDICT_MAX_BYTES: u64 = 16 << 20;++static NEXT_UID: AtomicU64 = AtomicU64::new(1);++/// The parsed dictionary section of one archive.+#[derive(Debug)]+pub struct ZDicts {+    raw: Vec<Vec<u8>>,+    uid: u64,+}++impl ZDicts {+    pub fn parse(bytes: &[u8]) -> Result<ZDicts> {+        if bytes.len() < 8 || &bytes[..4] != ZDICT_MAGIC {+            return err("a .mamaps dictionary section has no MZD1 magic");+        }+        let count = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize;+        let mut at = 8usize;+        let mut raw = Vec::with_capacity(count);+        for _ in 0..count {+            if at + 4 > bytes.len() {+                return err("a .mamaps dictionary section ends inside a length");+            }+            let len = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;+            at += 4;+            if at + len > bytes.len() {+                return err("a .mamaps dictionary runs past its section");+            }+            // Validate now, so a corrupt dictionary is an open error rather than a tile error.+            ruzstd::decoding::Dictionary::decode_dict(&bytes[at..at + len])+                .map_err(|e| Error(format!("a .mamaps dictionary will not load: {e:?}")))?;+            raw.push(bytes[at..at + len].to_vec());+            at += len;+        }+        if at != bytes.len() {+            return err("a .mamaps dictionary section has trailing bytes");+        }+        Ok(ZDicts { raw, uid: NEXT_UID.fetch_add(1, Ordering::Relaxed) })+    }++    /// The section bytes for `dicts`, the inverse of [`ZDicts::parse`].+    pub fn serialize(dicts: &[Vec<u8>]) -> Vec<u8> {+        let mut out = Vec::new();+        out.extend_from_slice(ZDICT_MAGIC);+        out.extend_from_slice(&(dicts.len() as u32).to_le_bytes());+        for d in dicts {+            out.extend_from_slice(&(d.len() as u32).to_le_bytes());+            out.extend_from_slice(d);+        }+        out+    }++    pub fn dictionaries(&self) -> &[Vec<u8>] {+        &self.raw+    }++    /// Decode one zstd frame (with or without a dictionary id) into `out`, which must be exactly+    /// the decoded length. Returns the bytes written.+    pub fn decode_into(&self, frame: &[u8], out: &mut [u8]) -> Result<usize> {+        thread_local! {+            static DECODERS: RefCell<Vec<(u64, ruzstd::decoding::FrameDecoder)>> =+                const { RefCell::new(Vec::new()) };+        }+        DECODERS.with(|cell| {+            let mut decs = cell.borrow_mut();+            let pos = match decs.iter().position(|(u, _)| *u == self.uid) {+                Some(p) => p,+                None => {+                    let mut dec = ruzstd::decoding::FrameDecoder::new();+                    for d in &self.raw {+                        let dict = ruzstd::decoding::Dictionary::decode_dict(d)+                            .map_err(|e| Error(format!("a .mamaps dictionary will not load: {e:?}")))?;+                        dec.add_dict(dict)+                            .map_err(|e| Error(format!("a .mamaps dictionary will not register: {e:?}")))?;+                    }+                    // A thread serving many archives over its life keeps a few decoders, not all.+                    if decs.len() >= 4 {+                        decs.remove(0);+                    }+                    decs.push((self.uid, dec));+                    decs.len() - 1+                }+            };+            let dec = &mut decs[pos].1;+            dec.decode_all(frame, out)+                .map_err(|e| Error(format!("a .mamaps dictionary-zstd body will not decode: {e:?}")))+        })+    }+}
scripts/maps/tile_build/examples/size_lab/main.rs
diff --git a/scripts/maps/tile_build/examples/size_lab.rs b/scripts/maps/tile_build/examples/size_lab/main.rssimilarity index 100%rename from scripts/maps/tile_build/examples/size_lab.rsrename to scripts/maps/tile_build/examples/size_lab/main.rs
scripts/maps/tile_build/examples/size_lab/more.rs
diff --git a/scripts/maps/tile_build/examples/size_lab_more.rs b/scripts/maps/tile_build/examples/size_lab/more.rssimilarity index 100%rename from scripts/maps/tile_build/examples/size_lab_more.rsrename to scripts/maps/tile_build/examples/size_lab/more.rs