Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_planet5.rs

mamaps_planet5.rs474 lines · 19.2 KiBRaw
1//! `mamaps_planet5` — transcode a finished tile archive into the planet5 tile format.
2//!
3//! ```text
4//! mamaps_planet5 IN.mamaps OUT.mamaps [--dict-bytes N] [--train-per-band N]
5//! ```
6//!
7//! Reads the tile archive `mamaps_build` wrote (v8/v9 header, DEFLATE or zstd v10 bodies) and
8//! writes the same tiles as:
9//!
10//! * **v11 bodies** — byte-for-byte the v10 body except that the heightmap is MED-residual coded
11//! (`tilecodec::mamaps::body::serialize_into_v11`), and since the ~50 GB revision v12: shared
12//! point runs between parts of a layer (`serialize_into_v12`); decodes to the identical `Body`;
13//! * **dictionary zstd** — one zstd dictionary trained per zoom band (z0-9, z10-11, z12, z13,
14//! z14) on a stride sample of that band's v11 bodies, every body compressed at zstd-19 against
15//! its band's dictionary; the dictionaries go into the v10 header's dictionary section.
16//!
17//! Every addressed tile id is appended in order through `StreamWriter`, so runs and content
18//! dedup are rebuilt exactly as the generator builds them, and the content-derived build id is
19//! re-derived over the new bodies (seeded with the input's id).
20//!
21//! * **superblocks** (header v11, `--no-superblocks` to disable) — the bodies of an aligned 8x8
22//! block of z10-z13 tiles (4x4 at z14) compressed as one frame (`tilecodec::mamaps::superblock`):
23//! neighbours share landuse, roads and terrain that a per-tile frame cannot. Only tiles whose
24//! body no other tile references (and that are not part of a run) join a block; shared bodies
25//! (ocean, empty land) stay single deduplicated frames. A block of one stays a plain body.
26//!
27//! Lossless: `--verify` decodes every output body and compares the parsed `Body` with the
28//! input's. Deterministic: the training sample is a fixed stride and the encoder is a pure
29//! function of input + dictionary, so the output does not depend on the thread count.
30use std::collections::HashMap;
31use std::fs::File;
32use std::path::PathBuf;
33use std::process::ExitCode;
34use std::sync::Arc;
35use std::time::Instant;
36
37use rayon::prelude::*;
38use tile_build::mamaps::body::{serialize_into_v12, Body, Scratch, BODY_HEADER_LEN};
39use tile_build::mamaps::header::{Header, FLAG_RINGS_VALIDATED};
40use tile_build::mamaps::index;
41use tile_build::mamaps::read::decompress;
42use tile_build::mamaps::write::{hash64, Options, StreamWriter};
43use tile_build::mamaps::zdict::ZDicts;
44use tilecodec::pmtiles::tile_zxy;
45
46const BANDS: usize = 5;
47
48fn band(z: u8) -> usize {
49 match z {
50 0..=9 => 0,
51 10..=11 => 1,
52 12 => 2,
53 13 => 3,
54 _ => 4,
55 }
56}
57
58/// A compressed body plus its content hash, shared between encoders and writers.
59type ArcBody = Arc<(Vec<u8>, u64)>;
60/// `(offset, band)` key of a single (non-superblock) body.
61type BodyKey = (u64, usize);
62/// Superblock candidate group: `(zoom, block x, block y)` key plus member indexes.
63type SbGroup = ((u8, u64, u64), Vec<usize>);
64/// One superblock's encode result: `(group, body, raw length)`.
65type EncodedSb = Result<(u32, ArcBody, u64), String>;
66/// One single body's encode result: `(key, body, raw length)`.
67type EncodedBody = Result<(BodyKey, ArcBody, u64), String>;
68
69/// One leaf entry: first tile id, run length, absolute body offset and stored length.
70#[derive(Clone, Copy)]
71struct Ent {
72 id: u64,
73 run: u32,
74 off: u64,
75 len: u32,
76}
77
78fn entries(map: &[u8], hdr: &Header) -> Result<Vec<Ent>, String> {
79 let root = index::parse_root(
80 &map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize],
81 )
82 .map_err(|e| e.0)?;
83 let per: Vec<Result<Vec<Ent>, String>> = root
84 .par_iter()
85 .map(|re| {
86 let raw_len = re.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;
87 let at = (hdr.leaf_offset + re.leaf_offset) as usize;
88 let raw = if re.stored_len == 0 {
89 map[at..at + raw_len].to_vec()
90 } else {
91 index::decompress_leaf(&map[at..at + re.stored_len as usize], raw_len)
92 .map_err(|e| e.0)?
93 };
94 Ok(index::parse_leaf(&raw)
95 .map_err(|e| e.0)?
96 .iter()
97 .map(|e| Ent {
98 id: re.base_tile_id + e.tile_id_lo as u64,
99 run: e.run_length,
100 off: hdr.data_offset + re.base_data_offset + e.offset_delta as u64,
101 len: e.length,
102 })
103 .collect())
104 })
105 .collect();
106 let mut out = Vec::new();
107 for p in per {
108 out.extend(p?);
109 }
110 out.sort_by_key(|e| e.id);
111 Ok(out)
112}
113
114/// The v11 encoding of one stored input body.
115fn to_v11(map: &[u8], hdr: &Header, off: u64, len: u32) -> Result<(Vec<u8>, Body), String> {
116 let stored = &map[off as usize..off as usize + len as usize];
117 let raw = decompress(hdr.compression, stored).map_err(|e| e.0)?;
118 let body = Body::parse(&raw).map_err(|e| e.0)?;
119 let mut s = Scratch::default();
120 // A v10 sparse carriageway table whose rows are all default is written as a convention with
121 // zero entries, and parses back as `convention: Some` with no rows -- a model the serializer
122 // refuses. Re-supply the all-default rows for the roads layer so the v11 body carries the
123 // identical table (zero entries + the convention) and parses back to the same `Body`.
124 let v11 = if body.convention.is_some() && body.carriageways.is_empty() {
125 let mut b = body.clone();
126 let roads = tile_build::mamaps::dict::LAYER_ROADS;
127 let n = b
128 .layer(roads)
129 .map(|l| l.features.len())
130 .ok_or("a body with a marking convention and no roads layer")?;
131 b.carriageways = vec![(roads, vec![tile_build::mamaps::body::Carriageway::default(); n])];
132 serialize_into_v12(&b, &mut s).map_err(|e| e.0)?.to_vec()
133 } else {
134 serialize_into_v12(&body, &mut s).map_err(|e| e.0)?.to_vec()
135 };
136 Ok((v11, body))
137}
138
139fn main() -> ExitCode {
140 let args: Vec<String> = std::env::args().collect();
141 let mut pos = Vec::new();
142 let (mut dict_bytes, mut per_band, mut verify) = (112 * 1024usize, 20_000usize, false);
143 let mut superblocks = true;
144 let mut i = 1;
145 while i < args.len() {
146 match args[i].as_str() {
147 "--dict-bytes" => {
148 dict_bytes = args[i + 1].parse().expect("--dict-bytes N");
149 i += 1;
150 }
151 "--train-per-band" => {
152 per_band = args[i + 1].parse().expect("--train-per-band N");
153 i += 1;
154 }
155 "--verify" => verify = true,
156 "--no-superblocks" => superblocks = false,
157 a => pos.push(a.to_string()),
158 }
159 i += 1;
160 }
161 if pos.len() != 2 {
162 eprintln!("usage: mamaps_planet5 IN.mamaps OUT.mamaps [--dict-bytes N] [--train-per-band N] [--verify] [--no-superblocks]");
163 return ExitCode::from(2);
164 }
165 match run(&pos[0], &pos[1], dict_bytes, per_band, verify, superblocks) {
166 Ok(()) => ExitCode::SUCCESS,
167 Err(e) => {
168 eprintln!("mamaps_planet5: {e}");
169 ExitCode::FAILURE
170 }
171 }
172}
173
174/// Superblock side of a tile at zoom `z`: 2^3 (8x8) for z10-z13, 2^2 (4x4) at z14 (bigger
175/// bodies: a 4x4 block already holds as much as an 8x8 z13 one). None below z10.
176fn superblock_shift(z: u8) -> Option<u32> {
177 match z {
178 10..=13 => Some(3),
179 14.. => Some(2),
180 _ => None,
181 }
182}
183
184/// Group index per entry (None = not in a superblock): consecutive candidate entries -- run 1,
185/// a body no other tile references -- in the same aligned block at one zoom. Hilbert order
186/// keeps an aligned block contiguous, so a block is one stretch of entries.
187fn superblock_groups(ents: &[Ent]) -> Vec<Option<u32>> {
188 let mut refs: HashMap<u64, u64> = HashMap::with_capacity(ents.len());
189 for e in ents {
190 *refs.entry(e.off).or_default() += e.run as u64;
191 }
192 let mut group = vec![None; ents.len()];
193 let mut cur: Option<SbGroup> = None;
194 let mut next = 0u32;
195 let mut close = |cur: &mut Option<SbGroup>, group: &mut Vec<Option<u32>>| {
196 if let Some((_, members)) = cur.take() {
197 if members.len() >= 2 {
198 for i in members {
199 group[i] = Some(next);
200 }
201 next += 1;
202 }
203 }
204 };
205 for (i, e) in ents.iter().enumerate() {
206 let (z, x, y) = tile_zxy(e.id);
207 let Some(g) = superblock_shift(z) else { continue };
208 if e.run != 1 || refs[&e.off] != 1 {
209 continue;
210 }
211 let key = (z, x >> g, y >> g);
212 match &mut cur {
213 Some((k, members)) if *k == key => members.push(i),
214 _ => {
215 close(&mut cur, &mut group);
216 cur = Some((key, vec![i]));
217 }
218 }
219 }
220 close(&mut cur, &mut group);
221 group
222}
223
224fn run(
225 input: &str,
226 output: &str,
227 dict_bytes: usize,
228 per_band: usize,
229 verify: bool,
230 superblocks: bool,
231) -> Result<(), String> {
232 let t0 = Instant::now();
233 let f = File::open(input).map_err(|e| format!("open {input}: {e}"))?;
234 let map = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| format!("mmap {input}: {e}"))?;
235 let hdr =
236 Header::parse(&map[..tilecodec::stream::OPEN_PREFIX_BYTES as usize]).map_err(|e| e.0)?;
237 if hdr.compression == tile_build::mamaps::header::COMPRESSION_ZSTD_DICT {
238 return Err("the input is already a planet5 archive".into());
239 }
240 let ents = entries(&map, &hdr)?;
241 println!(
242 "input: {} leaf entries, {} bytes of tile data ({:.1}s)",
243 ents.len(),
244 hdr.data_len,
245 t0.elapsed().as_secs_f64()
246 );
247
248 // 1. Training: a fixed stride over each band's distinct bodies.
249 let mut uniq: Vec<Vec<(u64, u32)>> = vec![Vec::new(); BANDS];
250 {
251 let mut seen: Vec<std::collections::HashSet<u64>> = vec![Default::default(); BANDS];
252 for e in &ents {
253 let b = band(tile_zxy(e.id).0);
254 if seen[b].insert(e.off) {
255 uniq[b].push((e.off, e.len));
256 }
257 }
258 }
259 let dicts: Vec<Vec<u8>> = uniq
260 .par_iter()
261 .enumerate()
262 .map(|(b, v)| -> Result<Vec<u8>, String> {
263 if v.len() < 256 {
264 return Ok(Vec::new()); // too few bodies to train on: plain zstd frames
265 }
266 let step = (v.len() / per_band).max(1);
267 let samples: Vec<Vec<u8>> = v
268 .iter()
269 .step_by(step)
270 .map(|&(off, len)| {
271 to_v11(&map, &hdr, off, len).map(|(r, _)| r[BODY_HEADER_LEN..].to_vec())
272 })
273 .collect::<Result<_, _>>()?;
274 let d = zstd::dict::from_samples(&samples, dict_bytes)
275 .map_err(|e| format!("train band {b}: {e}"))?;
276 println!(
277 " band {b}: {} distinct bodies, trained on {} -> {} B dictionary",
278 v.len(),
279 samples.len(),
280 d.len()
281 );
282 Ok(d)
283 })
284 .collect::<Result<_, _>>()?;
285 let kept: Vec<Vec<u8>> = dicts.iter().filter(|d| !d.is_empty()).cloned().collect();
286 let section = ZDicts::serialize(&kept);
287 let verify_dicts = ZDicts::parse(&section).map_err(|e| e.0)?;
288 let enc_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts
289 .iter()
290 .map(|d| -> Result<Option<zstd_rs::EncoderDictionary>, String> {
291 if d.is_empty() {
292 return Ok(None);
293 }
294 let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd)
295 .map_err(|e| format!("{e:?}"))?;
296 Ok(Some(zstd_rs::EncoderDictionary::new(&dd, 19).map_err(|e| format!("{e:?}"))?))
297 })
298 .collect::<Result<_, _>>()?;
299 println!(
300 "trained {} dictionaries ({} B section) in {:.1}s",
301 kept.len(),
302 section.len(),
303 t0.elapsed().as_secs_f64()
304 );
305
306 // 2. Re-encode and append, in tile id order, in batches.
307 let out_path = PathBuf::from(output);
308 let mut writer = StreamWriter::new(Options {
309 min_zoom: hdr.min_zoom,
310 max_zoom: hdr.max_zoom,
311 build_id: hdr.build_id,
312 build_id_from_content: true,
313 compress: true,
314 zdicts: Some(section),
315 rings_validated: hdr.flags & FLAG_RINGS_VALIDATED != 0,
316 leaf_entry_capacity: hdr.leaf_entry_capacity,
317 spill_dir: out_path.parent().map(|p| p.to_path_buf()),
318 superblocks,
319 min_lon_e7: hdr.min_lon_e7,
320 min_lat_e7: hdr.min_lat_e7,
321 max_lon_e7: hdr.max_lon_e7,
322 max_lat_e7: hdr.max_lat_e7,
323 ..Options::default()
324 })
325 .map_err(|e| e.0)?;
326 let cfg = zstd_rs::CompressionConfig { level: 19, ..zstd_rs::CompressionConfig::DEFAULT };
327 let (mut raw_in, mut stored_out) = (0u64, 0u64);
328 const BATCH: usize = 1 << 21;
329 let groups = if superblocks { superblock_groups(&ents) } else { vec![None; ents.len()] };
330 let (mut sb_count, mut sb_members) = (0u64, 0u64);
331 // Batches end only between superblocks, so a block is encoded within one batch.
332 let mut ranges: Vec<(usize, usize)> = Vec::new();
333 let mut start = 0usize;
334 for i in 1..=ents.len() {
335 if i == ents.len()
336 || (i - start >= BATCH && (groups[i].is_none() || groups[i] != groups[i - 1]))
337 {
338 ranges.push((start, i));
339 start = i;
340 }
341 }
342 for (bi, &(lo, hi)) in ranges.iter().enumerate() {
343 let batch = &ents[lo..hi];
344 let bgroups = &groups[lo..hi];
345 // Superblocks of this batch: members' v11 bodies assembled, compressed with the band
346 // dictionary, in parallel.
347 let mut blocks: Vec<(u32, Vec<usize>)> = Vec::new();
348 for (k, g) in bgroups.iter().enumerate() {
349 if let Some(g) = g {
350 match blocks.last_mut() {
351 Some((lg, m)) if lg == g => m.push(k),
352 _ => blocks.push((*g, vec![k])),
353 }
354 }
355 }
356 let sb_encoded: Vec<EncodedSb> = blocks
357 .par_iter()
358 .map_init(
359 || zstd_rs::Compressor::new(cfg).expect("zstd level"),
360 |enc, (g, members)| {
361 let b = band(tile_zxy(batch[members[0]].id).0);
362 let mut bodies: Vec<(u64, Vec<u8>)> = Vec::with_capacity(members.len());
363 let mut models = Vec::with_capacity(members.len());
364 for &k in members {
365 let e = batch[k];
366 let (v11, body) = to_v11(&map, &hdr, e.off, e.len)?;
367 bodies.push((e.id, v11));
368 models.push(body);
369 }
370 let raw = tile_build::mamaps::superblock::assemble(&bodies);
371 let mut stored = Vec::with_capacity(raw.len() / 2);
372 stored.extend_from_slice(&raw[..BODY_HEADER_LEN]);
373 enc.compress(&raw[BODY_HEADER_LEN..], enc_dicts[b].as_ref(), &mut stored)
374 .map_err(|e| format!("zstd: {e:?}"))?;
375 if verify {
376 let back = tile_build::mamaps::read::decompress_with(
377 tile_build::mamaps::header::COMPRESSION_ZSTD_DICT,
378 &stored,
379 Some(&verify_dicts),
380 )
381 .map_err(|e| e.0)?;
382 let m = tile_build::mamaps::superblock::members(&back).map_err(|e| e.0)?;
383 for ((id, bytes), model) in m.iter().zip(models.iter()) {
384 if Body::parse(bytes).map_err(|e| e.0)? != *model {
385 return Err(format!("superblock member {id} does not round-trip"));
386 }
387 }
388 }
389 let h = hash64(&stored);
390 Ok((*g, Arc::new((stored, h)), raw.len() as u64))
391 },
392 )
393 .collect();
394 let mut by_group: HashMap<u32, ArcBody> = HashMap::with_capacity(sb_encoded.len());
395 for r in sb_encoded {
396 let (g, v, raw) = r?;
397 raw_in += raw;
398 stored_out += v.0.len() as u64;
399 by_group.insert(g, v);
400 }
401 sb_count += blocks.len() as u64;
402 sb_members += blocks.iter().map(|b| b.1.len() as u64).sum::<u64>();
403 // Distinct (offset, band) pairs of the other entries, encoded in parallel.
404 let mut keys: Vec<(u64, u32, usize)> = batch
405 .iter()
406 .zip(bgroups)
407 .filter(|(_, g)| g.is_none())
408 .map(|(e, _)| (e.off, e.len, band(tile_zxy(e.id).0)))
409 .collect();
410 keys.sort_unstable();
411 keys.dedup();
412 let encoded: Vec<EncodedBody> = keys
413 .par_iter()
414 .map_init(
415 || zstd_rs::Compressor::new(cfg).expect("zstd level"),
416 |enc, &(off, len, b)| {
417 let (v11, body) = to_v11(&map, &hdr, off, len)?;
418 let mut stored = Vec::with_capacity(v11.len() / 2);
419 stored.extend_from_slice(&v11[..BODY_HEADER_LEN]);
420 enc.compress(&v11[BODY_HEADER_LEN..], enc_dicts[b].as_ref(), &mut stored)
421 .map_err(|e| format!("zstd: {e:?}"))?;
422 if verify {
423 let back = tile_build::mamaps::read::decompress_with(
424 tile_build::mamaps::header::COMPRESSION_ZSTD_DICT,
425 &stored,
426 Some(&verify_dicts),
427 )
428 .map_err(|e| e.0)?;
429 if Body::parse(&back).map_err(|e| e.0)? != body {
430 return Err(format!("body at {off} does not round-trip"));
431 }
432 }
433 let h = hash64(&stored);
434 Ok(((off, b), Arc::new((stored, h)), v11.len() as u64))
435 },
436 )
437 .collect();
438 let mut by_key: HashMap<BodyKey, ArcBody> = HashMap::with_capacity(encoded.len());
439 for r in encoded {
440 let (k, v, raw) = r?;
441 raw_in += raw;
442 by_key.insert(k, v);
443 }
444 for (e, g) in batch.iter().zip(bgroups) {
445 if let Some(g) = g {
446 let s = &by_group[g];
447 writer.append_stored_with_hash(e.id, &s.0, s.1).map_err(|e| e.0)?;
448 continue;
449 }
450 let s = &by_key[&(e.off, band(tile_zxy(e.id).0))];
451 for k in 0..e.run as u64 {
452 writer.append_stored_with_hash(e.id + k, &s.0, s.1).map_err(|e| e.0)?;
453 }
454 }
455 stored_out += by_key.values().map(|v| v.0.len() as u64).sum::<u64>();
456 println!(
457 " batch {bi}: {} entries, {} distinct bodies ({:.0}s)",
458 batch.len(),
459 by_key.len(),
460 t0.elapsed().as_secs_f64()
461 );
462 }
463 if superblocks {
464 println!("superblocks: {sb_count} blocks holding {sb_members} tiles");
465 }
466 writer.finish_to_path(&out_path).map_err(|e| e.0)?;
467 let len = std::fs::metadata(&out_path).map_err(|e| e.to_string())?.len();
468 println!(
469 "wrote {output}: {len} bytes (input tile data {} B, v11 raw {raw_in} B, encoded distinct {stored_out} B) in {:.0}s",
470 hdr.data_len,
471 t0.elapsed().as_secs_f64()
472 );
473 Ok(())
474}