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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / reader.rs

reader.rs491 lines · 17.4 KiBRaw
1//! A host-side reader for the `.transit` (TRX2) packs [`crate::index`] writes.
2//!
3//! This is a **deliberate reimplementation** of the on-device reader
4//! `maps/src/main/rust/src/transit.rs`, not shared code. Two independent
5//! decoders of the same bytes must agree; keeping them separate is what makes a
6//! layout mistake in either one show up as a failing test or a dump diff instead
7//! of a pack the device silently mis-reads. Anything learned here must be
8//! mirrored there by hand — that is the point.
9//!
10//! Used by `index`'s tests and by `src/bin/transit_dump.rs`.
11
12use crate::index::{HEADER_LEN, MAGIC, NONE, SECTION_COUNT, SECTION_COUNT_V6, VERSION, VERSION_MIN};
13
14// Section slot numbers. Slot `i` must describe section `i`; the device reader
15// hardcodes the same numbers.
16pub const SEC_STRINGS: usize = 0;
17pub const SEC_STOPS: usize = 1;
18pub const SEC_ROUTES: usize = 2;
19pub const SEC_ROUTE_STOPS: usize = 3;
20pub const SEC_ROUTE_TRIPS: usize = 4;
21pub const SEC_PROFILES: usize = 5;
22pub const SEC_PROFILES_IDX: usize = 6;
23pub const SEC_STOP_ROUTES: usize = 7;
24pub const SEC_STOP_ROUTES_IDX: usize = 8;
25pub const SEC_TRANSFERS: usize = 9;
26pub const SEC_TRANSFERS_IDX: usize = 10;
27pub const SEC_SERVICES: usize = 11;
28pub const SEC_EXCEPTIONS: usize = 12;
29pub const SEC_GRID_CELL_IDS: usize = 13;
30pub const SEC_GRID_CELL_OFF: usize = 14;
31pub const SEC_GRID_STOPS: usize = 15;
32pub const SEC_FEEDS: usize = 16;
33pub const SEC_FEED_TZ: usize = 17;
34pub const SEC_EXCEPTIONS_IDX: usize = 18;
35pub const SEC_STOP_ROUTE_POS: usize = 19;
36pub const SEC_SHAPE_COORDS: usize = 20;
37pub const SEC_ROUTE_SHAPE_IDX: usize = 21;
38pub const SEC_ROUTE_STOP_SHAPE: usize = 22;
39pub const SEC_FEED_MOTIS_PREFIX: usize = 23;
40pub const SEC_STOP_GTFS_ID: usize = 24;
41pub const SEC_ROUTE_TRIP_RECS: usize = 25;
42pub const SEC_ROUTE_TRIP_OFF: usize = 26;
43pub const SEC_RAIL_LINES: usize = 27;
44
45/// Bytes per v6 trip record: `u32 start_time, profile_id, service_idx, headsign_off`.
46pub const TRIP_REC_BYTES: usize = 16;
47use crate::reader_extra::{ri32, ru32, ru64, zigzag};
48pub use crate::reader_extra::read_uvarint;
49
50/// One ROUTES entry (a 32-byte stride).
51#[derive(Clone, Copy, Debug)]
52pub struct RouteRec {
53 pub name_off: u32,
54 pub color: u32,
55 pub route_type: u32,
56 pub feed_idx: u32,
57 pub n_stops: u32,
58 pub first_route_stop: u32,
59 pub n_trips: u32,
60 /// Byte offset into ROUTE_TRIPS.
61 pub trips_off: u32,
62}
63
64/// One trip decoded out of a route's ROUTE_TRIPS varint block.
65#[derive(Clone, Copy, Debug)]
66pub struct TripRec {
67 pub start_time: u32,
68 pub profile_id: u32,
69 pub service_idx: u32,
70 pub headsign_off: u32,
71}
72
73/// One SERVICES entry (a 12-byte stride).
74#[derive(Clone, Copy, Debug)]
75pub struct ServiceRec {
76 /// Bit `b` set = runs on day `b`, Monday = 0.
77 pub weekday_mask: u8,
78 pub start_date: u32,
79 pub end_date: u32,
80}
81
82/// The header's grid parameters.
83#[derive(Clone, Copy, Debug)]
84pub struct GridParams {
85 pub lat0_e7: i32,
86 pub lon0_e7: i32,
87 pub cell_e7: u32,
88 pub cols: u32,
89 pub rows: u32,
90}
91
92pub struct Reader {
93 buf: Vec<u8>,
94 sec: Vec<(usize, usize)>,
95}
96
97impl Reader {
98 /// Validate the header and index the section directory.
99 pub fn new(buf: Vec<u8>) -> Result<Reader, String> {
100 if buf.len() < HEADER_LEN {
101 return Err(format!("pack is {} bytes, shorter than the header", buf.len()));
102 }
103 let magic = ru32(&buf, 0);
104 if magic != MAGIC {
105 return Err(format!("bad magic {magic:#x}"));
106 }
107 let version = ru32(&buf, 4);
108 if !(VERSION_MIN..=VERSION).contains(&version) {
109 return Err(format!("version {version} outside {VERSION_MIN}..={VERSION}"));
110 }
111 let count = ru32(&buf, 8) as usize;
112 if count != SECTION_COUNT && count != SECTION_COUNT_V6 {
113 return Err(format!("section_count {count}, expected {SECTION_COUNT}"));
114 }
115 if buf.len() < HEADER_LEN + count * 16 {
116 return Err("pack is truncated inside the section directory".to_string());
117 }
118 let mut sec = Vec::with_capacity(count);
119 for i in 0..count {
120 let base = HEADER_LEN + i * 16;
121 let off = ru64(&buf, base) as usize;
122 let len = ru64(&buf, base + 8) as usize;
123 match off.checked_add(len) {
124 Some(end) if end <= buf.len() => {}
125 _ => return Err(format!("section {i} at {off}+{len} runs past the file")),
126 }
127 sec.push((off, len));
128 }
129 Ok(Reader { buf, sec })
130 }
131
132 /// Read the pack at `path`.
133 pub fn open(path: &std::path::Path) -> Result<Reader, String> {
134 let buf = std::fs::read(path)
135 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
136 Reader::new(buf)
137 }
138
139 /// The `idx`-th u32 of the header.
140 fn hdr(&self, idx: usize) -> u32 {
141 ru32(&self.buf, idx * 4)
142 }
143
144 pub fn version(&self) -> u32 {
145 self.hdr(1)
146 }
147 pub fn section_count(&self) -> u32 {
148 self.hdr(2)
149 }
150 pub fn stop_count(&self) -> u32 {
151 self.hdr(3)
152 }
153 pub fn route_count(&self) -> u32 {
154 self.hdr(4)
155 }
156 pub fn trip_count(&self) -> u32 {
157 self.hdr(5)
158 }
159 pub fn service_count(&self) -> u32 {
160 self.hdr(6)
161 }
162 pub fn profile_count(&self) -> u32 {
163 self.hdr(7)
164 }
165 pub fn feed_count(&self) -> u32 {
166 self.hdr(8)
167 }
168 pub fn grid_cell_count(&self) -> u32 {
169 self.hdr(9)
170 }
171 /// The pack name the device falls back to.
172 pub fn pack_name(&self) -> String {
173 self.read_str(self.hdr(10))
174 }
175 /// `(min_lat_e7, min_lon_e7, max_lat_e7, max_lon_e7)`.
176 pub fn bbox(&self) -> (i32, i32, i32, i32) {
177 (
178 self.hdr(11) as i32,
179 self.hdr(12) as i32,
180 self.hdr(13) as i32,
181 self.hdr(14) as i32,
182 )
183 }
184 pub fn grid(&self) -> GridParams {
185 GridParams {
186 lat0_e7: self.hdr(15) as i32,
187 lon0_e7: self.hdr(16) as i32,
188 cell_e7: self.hdr(17),
189 cols: self.hdr(18),
190 rows: self.hdr(19),
191 }
192 }
193
194 pub fn sec_bytes(&self, s: usize) -> &[u8] {
195 let (o, l) = self.sec[s];
196 &self.buf[o..o + l]
197 }
198
199 /// The NUL-terminated string at STRINGS offset `off`; "" for [`NONE`].
200 pub fn read_str(&self, off: u32) -> String {
201 if off == NONE {
202 return String::new();
203 }
204 let s = self.sec_bytes(SEC_STRINGS);
205 let start = off as usize;
206 let mut n = 0;
207 while start + n < s.len() && s[start + n] != 0 {
208 n += 1;
209 }
210 String::from_utf8_lossy(&s[start..start + n]).into_owned()
211 }
212
213 /// `(lat, lon)` in degrees.
214 pub fn stop_ll(&self, i: u32) -> (f64, f64) {
215 let (lat, lon) = self.stop_ll_e7(i);
216 (lat as f64 * 1e-7, lon as f64 * 1e-7)
217 }
218
219 pub fn stop_ll_e7(&self, i: u32) -> (i32, i32) {
220 let s = self.sec_bytes(SEC_STOPS);
221 let base = i as usize * 16;
222 (ri32(s, base), ri32(s, base + 4))
223 }
224
225 pub fn stop_name(&self, i: u32) -> String {
226 self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 8))
227 }
228
229 pub fn stop_code(&self, i: u32) -> String {
230 self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 12))
231 }
232
233 /// The raw GTFS `stop_id` (v5 STOP_GTFS_ID).
234 pub fn stop_gtfs_id(&self, i: u32) -> String {
235 self.read_str(ru32(self.sec_bytes(SEC_STOP_GTFS_ID), i as usize * 4))
236 }
237
238 pub fn route(&self, r: u32) -> RouteRec {
239 let s = self.sec_bytes(SEC_ROUTES);
240 let base = r as usize * 32;
241 RouteRec {
242 name_off: ru32(s, base),
243 color: ru32(s, base + 4),
244 route_type: ru32(s, base + 8),
245 feed_idx: ru32(s, base + 12),
246 n_stops: ru32(s, base + 16),
247 first_route_stop: ru32(s, base + 20),
248 n_trips: ru32(s, base + 24),
249 trips_off: ru32(s, base + 28),
250 }
251 }
252
253 /// ROUTE_STOPS entry `i` (an absolute stop index).
254 pub fn route_stop(&self, i: u32) -> u32 {
255 ru32(self.sec_bytes(SEC_ROUTE_STOPS), i as usize * 4)
256 }
257
258 /// A route's stop pattern.
259 pub fn route_stops(&self, rec: &RouteRec) -> Vec<u32> {
260 (0..rec.n_stops).map(|p| self.route_stop(rec.first_route_stop + p)).collect()
261 }
262
263 /// Decode a route's varint trip block, in start-time order.
264 pub fn route_trips(&self, rec: &RouteRec) -> Vec<TripRec> {
265 let s = self.sec_bytes(SEC_ROUTE_TRIPS);
266 let mut pos = rec.trips_off as usize;
267 let mut prev = 0u32;
268 let mut out = Vec::with_capacity(rec.n_trips as usize);
269 for _ in 0..rec.n_trips {
270 let start_time = prev + read_uvarint(s, &mut pos) as u32;
271 out.push(TripRec {
272 start_time,
273 profile_id: read_uvarint(s, &mut pos) as u32,
274 service_idx: read_uvarint(s, &mut pos) as u32,
275 headsign_off: read_uvarint(s, &mut pos) as u32,
276 });
277 prev = start_time;
278 }
279 out
280 }
281
282 /// A route's trips read from v6's fixed-stride table instead of the varint stream.
283 ///
284 /// The point of the table is that a trip is addressable by index, so the device
285 /// reader can stop decoding trips its scan never looks at. Here it serves a second
286 /// purpose: it is an independent decoding of the same data, so
287 /// [`Self::route_trips_strided`] and [`Self::route_trips`] disagreeing means the
288 /// writer emitted two views that do not match.
289 pub fn route_trips_strided(&self, route_idx: u32) -> Vec<TripRec> {
290 let off = self.sec_bytes(SEC_ROUTE_TRIP_OFF);
291 let recs = self.sec_bytes(SEC_ROUTE_TRIP_RECS);
292 if (route_idx as usize + 2) * 4 > off.len() {
293 return Vec::new();
294 }
295 let base = ru32(off, route_idx as usize * 4) as usize;
296 let end = ru32(off, (route_idx as usize + 1) * 4) as usize;
297 if end < base || end * TRIP_REC_BYTES > recs.len() {
298 return Vec::new();
299 }
300 (base..end)
301 .map(|i| {
302 let at = i * TRIP_REC_BYTES;
303 TripRec {
304 start_time: ru32(recs, at),
305 profile_id: ru32(recs, at + 4),
306 service_idx: ru32(recs, at + 8),
307 headsign_off: ru32(recs, at + 12),
308 }
309 })
310 .collect()
311 }
312
313 /// Profile `pid` as per-stop `(arr, dep)` offsets relative to a trip's
314 /// `start_time`. `arr[0]` is negative by the first dwell.
315 pub fn profile(&self, pid: u32) -> Vec<(i64, i64)> {
316 let idx = self.sec_bytes(SEC_PROFILES_IDX);
317 let off = ru32(idx, pid as usize * 4) as usize;
318 let s = self.sec_bytes(SEC_PROFILES);
319 let mut pos = off;
320 let n = read_uvarint(s, &mut pos) as usize;
321 let dwell0 = read_uvarint(s, &mut pos) as i64;
322 let mut out = Vec::with_capacity(n);
323 out.push((-dwell0, 0i64));
324 let mut prev_dep = 0i64;
325 for _ in 1..n {
326 let hop = read_uvarint(s, &mut pos) as i64;
327 let dwell = read_uvarint(s, &mut pos) as i64;
328 let arr = prev_dep + hop;
329 let dep = arr + dwell;
330 out.push((arr, dep));
331 prev_dep = dep;
332 }
333 out
334 }
335
336 pub fn feed_name(&self, feed_idx: u32) -> String {
337 self.read_str(ru32(self.sec_bytes(SEC_FEEDS), feed_idx as usize * 4))
338 }
339
340 pub fn feed_tz(&self, feed_idx: u32) -> String {
341 self.read_str(ru32(self.sec_bytes(SEC_FEED_TZ), feed_idx as usize * 4))
342 }
343
344 pub fn feed_motis_prefix(&self, feed_idx: u32) -> String {
345 self.read_str(ru32(self.sec_bytes(SEC_FEED_MOTIS_PREFIX), feed_idx as usize * 4))
346 }
347
348 pub fn service(&self, service_idx: u32) -> ServiceRec {
349 let s = self.sec_bytes(SEC_SERVICES);
350 let base = service_idx as usize * 12;
351 ServiceRec {
352 weekday_mask: s[base],
353 start_date: ru32(s, base + 4),
354 end_date: ru32(s, base + 8),
355 }
356 }
357
358 /// `(service_idx, date, added)` exceptions for one service, via the CSR.
359 pub fn service_exceptions(&self, service_idx: u32) -> Vec<(u32, u32, u32)> {
360 let idx = self.sec_bytes(SEC_EXCEPTIONS_IDX);
361 let s = self.sec_bytes(SEC_EXCEPTIONS);
362 let lo = ru32(idx, service_idx as usize * 4) as usize;
363 let hi = ru32(idx, (service_idx as usize + 1) * 4) as usize;
364 (lo..hi)
365 .map(|i| (ru32(s, i * 12), ru32(s, i * 12 + 4), ru32(s, i * 12 + 8)))
366 .collect()
367 }
368
369 /// `(route_idx, stop_pos)` pairs serving `stop`, via STOP_ROUTES(+_POS).
370 pub fn stop_routes(&self, stop: u32) -> Vec<(u32, u32)> {
371 let idx = self.sec_bytes(SEC_STOP_ROUTES_IDX);
372 let routes = self.sec_bytes(SEC_STOP_ROUTES);
373 let pos = self.sec_bytes(SEC_STOP_ROUTE_POS);
374 let lo = ru32(idx, stop as usize * 4) as usize;
375 let hi = ru32(idx, (stop as usize + 1) * 4) as usize;
376 (lo..hi).map(|i| (ru32(routes, i * 4), ru32(pos, i * 4))).collect()
377 }
378
379 /// `(to_stop, secs)` footpaths from `stop`.
380 pub fn transfers(&self, stop: u32) -> Vec<(u32, u32)> {
381 let idx = self.sec_bytes(SEC_TRANSFERS_IDX);
382 let s = self.sec_bytes(SEC_TRANSFERS);
383 let lo = ru32(idx, stop as usize * 4) as usize;
384 let hi = ru32(idx, (stop as usize + 1) * 4) as usize;
385 (lo..hi).map(|i| (ru32(s, i * 8), ru32(s, i * 8 + 4))).collect()
386 }
387
388 /// Every non-empty grid cell as `(cell_id, stops)`, in file order (which the
389 /// reader requires to be `cell_id`-ascending).
390 pub fn grid_cells(&self) -> Vec<(u32, Vec<u32>)> {
391 let ids = self.sec_bytes(SEC_GRID_CELL_IDS);
392 let offs = self.sec_bytes(SEC_GRID_CELL_OFF);
393 let stops = self.sec_bytes(SEC_GRID_STOPS);
394 (0..self.grid_cell_count() as usize)
395 .map(|c| {
396 let lo = ru32(offs, c * 4) as usize;
397 let hi = ru32(offs, (c + 1) * 4) as usize;
398 (ru32(ids, c * 4), (lo..hi).map(|k| ru32(stops, k * 4)).collect())
399 })
400 .collect()
401 }
402
403 /// Byte offset of route `r`'s shape blob in SHAPE_COORDS, or `None`.
404 pub fn route_shape_off(&self, r: u32) -> Option<usize> {
405 let idx = self.sec_bytes(SEC_ROUTE_SHAPE_IDX);
406 let route_count = self.route_count() as usize;
407 assert_eq!(idx.len(), (route_count + 1) * 4, "ROUTE_SHAPE_IDX size");
408 let off = ru32(idx, r as usize * 4);
409 if off == NONE {
410 return None;
411 }
412 let bound = ru32(idx, route_count * 4) as usize;
413 assert_eq!(bound, self.sec_bytes(SEC_SHAPE_COORDS).len(), "ROUTE_SHAPE_IDX bound");
414 assert!(off as usize + 4 <= bound, "shape offset {off} out of SHAPE_COORDS");
415 Some(off as usize)
416 }
417
418 /// Decode the whole polyline at byte offset `off` in SHAPE_COORDS.
419 pub fn shape_points(&self, off: usize) -> Vec<(i32, i32)> {
420 let s = self.sec_bytes(SEC_SHAPE_COORDS);
421 let n = ru32(s, off) as usize;
422 let mut pos = off + 4;
423 let (mut lat, mut lon) = (0i64, 0i64);
424 (0..n)
425 .map(|_| {
426 lat += zigzag(read_uvarint(s, &mut pos));
427 lon += zigzag(read_uvarint(s, &mut pos));
428 (lat as i32, lon as i32)
429 })
430 .collect()
431 }
432
433 /// Vertex index for ROUTE_STOPS entry `i` ([`NONE`] when unshaped).
434 pub fn route_stop_shape(&self, i: u32) -> u32 {
435 ru32(self.sec_bytes(SEC_ROUTE_STOP_SHAPE), i as usize * 4)
436 }
437
438 /// Nearest stop to `(lat, lon)` via the sparse spatial grid, searching ±1
439 /// cell exactly as the device does.
440 pub fn nearest(&self, lat: f64, lon: f64) -> Option<u32> {
441 let g = self.grid();
442 let lat_e7 = (lat * 1e7) as i64;
443 let lon_e7 = (lon * 1e7) as i64;
444 let row0 = ((lat_e7 - g.lat0_e7 as i64) / g.cell_e7 as i64).max(0);
445 let col0 = ((lon_e7 - g.lon0_e7 as i64) / g.cell_e7 as i64).max(0);
446 let ids = self.sec_bytes(SEC_GRID_CELL_IDS);
447 let offs = self.sec_bytes(SEC_GRID_CELL_OFF);
448 let stops = self.sec_bytes(SEC_GRID_STOPS);
449 let n_cells = ids.len() / 4;
450 let find = |cid: u32| -> Option<usize> {
451 let (mut lo, mut hi) = (0usize, n_cells);
452 while lo < hi {
453 let mid = (lo + hi) / 2;
454 let v = ru32(ids, mid * 4);
455 if v == cid {
456 return Some(mid);
457 } else if v < cid {
458 lo = mid + 1;
459 } else {
460 hi = mid;
461 }
462 }
463 None
464 };
465 let mut best = None;
466 let mut bestd = f64::MAX;
467 for dr in -1..=1 {
468 for dc in -1..=1 {
469 let r = row0 + dr;
470 let c = col0 + dc;
471 if r < 0 || c < 0 || c >= g.cols as i64 {
472 continue;
473 }
474 if let Some(ci) = find((r * g.cols as i64 + c) as u32) {
475 let s = ru32(offs, ci * 4) as usize;
476 let e = ru32(offs, (ci + 1) * 4) as usize;
477 for k in s..e {
478 let sid = ru32(stops, k * 4);
479 let (slat, slon) = self.stop_ll(sid);
480 let d = (slat - lat).powi(2) + (slon - lon).powi(2);
481 if d < bestd {
482 bestd = d;
483 best = Some(sid);
484 }
485 }
486 }
487 }
488 }
489 best
490 }
491}