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

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

reader_s1.rs419 lines · 16.0 KiBRaw
1impl Reader {
2 /// Validate the header and index the section directory.
3 pub fn new(buf: Vec<u8>) -> Result<Reader, String> {
4 if buf.len() < HEADER_LEN {
5 return Err(format!("pack is {} bytes, shorter than the header", buf.len()));
6 }
7 let magic = ru32(&buf, 0);
8 if magic != MAGIC {
9 return Err(format!("bad magic {magic:#x}"));
10 }
11 let version = ru32(&buf, 4);
12 if !(VERSION_MIN..=VERSION).contains(&version) {
13 return Err(format!("version {version} outside {VERSION_MIN}..={VERSION}"));
14 }
15 let count = ru32(&buf, 8) as usize;
16 if count != SECTION_COUNT && count != SECTION_COUNT_V6 {
17 return Err(format!("section_count {count}, expected {SECTION_COUNT}"));
18 }
19 if buf.len() < HEADER_LEN + count * 16 {
20 return Err("pack is truncated inside the section directory".to_string());
21 }
22 let mut sec = Vec::with_capacity(count);
23 for i in 0..count {
24 let base = HEADER_LEN + i * 16;
25 let off = ru64(&buf, base) as usize;
26 let len = ru64(&buf, base + 8) as usize;
27 match off.checked_add(len) {
28 Some(end) if end <= buf.len() => {}
29 _ => return Err(format!("section {i} at {off}+{len} runs past the file")),
30 }
31 sec.push((off, len));
32 }
33 Ok(Reader { buf, sec })
34 }
35
36 /// Read the pack at `path`.
37 pub fn open(path: &std::path::Path) -> Result<Reader, String> {
38 let buf =
39 std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
40 Reader::new(buf)
41 }
42
43 /// Read the pack at `path`, but only the header, the directory and the listed sections.
44 ///
45 /// For a caller that needs a few hundred MB of a multi-GB pack: `transit_shapes --pack`
46 /// reads three sections, and reading the whole 4.4 GB world pack first was most of its
47 /// start-up. The buffer is still the file's full length, so every offset means what it
48 /// does in [`open`](Self::open), and it is validated identically; the sections not listed
49 /// read as zeros and must not be used. The zeroed buffer is allocated untouched, so the
50 /// unread sections cost address space, not memory. Listed sections the pack does not have
51 /// (a v6 pack has no RAIL_LINES) are skipped, for the accessors to report.
52 pub fn open_sections(path: &std::path::Path, sections: &[usize]) -> Result<Reader, String> {
53 use std::io::{Read, Seek, SeekFrom};
54 let fail = |e: std::io::Error| format!("cannot read {}: {e}", path.display());
55 let mut f = std::fs::File::open(path).map_err(fail)?;
56 let len = f.metadata().map_err(fail)?.len() as usize;
57 let mut buf = vec![0u8; len];
58 // Header, then the directory it sizes. `new` re-checks both against the real length.
59 let head = HEADER_LEN.min(len);
60 f.read_exact(&mut buf[..head]).map_err(fail)?;
61 if head == HEADER_LEN {
62 let dir_end = (HEADER_LEN + ru32(&buf, 8) as usize * 16).min(len);
63 f.read_exact(&mut buf[HEADER_LEN..dir_end]).map_err(fail)?;
64 }
65 let mut reader = Reader::new(buf)?;
66 for &s in sections {
67 let Some(&(off, l)) = reader.sec.get(s) else { continue };
68 f.seek(SeekFrom::Start(off as u64)).map_err(fail)?;
69 f.read_exact(&mut reader.buf[off..off + l]).map_err(fail)?;
70 }
71 Ok(reader)
72 }
73
74 /// The `idx`-th u32 of the header.
75 fn hdr(&self, idx: usize) -> u32 {
76 ru32(&self.buf, idx * 4)
77 }
78
79 pub fn version(&self) -> u32 {
80 self.hdr(1)
81 }
82 pub fn section_count(&self) -> u32 {
83 self.hdr(2)
84 }
85 pub fn stop_count(&self) -> u32 {
86 self.hdr(3)
87 }
88 pub fn route_count(&self) -> u32 {
89 self.hdr(4)
90 }
91 pub fn trip_count(&self) -> u32 {
92 self.hdr(5)
93 }
94 pub fn service_count(&self) -> u32 {
95 self.hdr(6)
96 }
97 pub fn profile_count(&self) -> u32 {
98 self.hdr(7)
99 }
100 pub fn feed_count(&self) -> u32 {
101 self.hdr(8)
102 }
103 pub fn grid_cell_count(&self) -> u32 {
104 self.hdr(9)
105 }
106 /// The pack name the device falls back to.
107 pub fn pack_name(&self) -> String {
108 self.read_str(self.hdr(10))
109 }
110 /// `(min_lat_e7, min_lon_e7, max_lat_e7, max_lon_e7)`.
111 pub fn bbox(&self) -> (i32, i32, i32, i32) {
112 (self.hdr(11) as i32, self.hdr(12) as i32, self.hdr(13) as i32, self.hdr(14) as i32)
113 }
114 pub fn grid(&self) -> GridParams {
115 GridParams {
116 lat0_e7: self.hdr(15) as i32,
117 lon0_e7: self.hdr(16) as i32,
118 cell_e7: self.hdr(17),
119 cols: self.hdr(18),
120 rows: self.hdr(19),
121 }
122 }
123
124 pub fn sec_bytes(&self, s: usize) -> &[u8] {
125 let (o, l) = self.sec[s];
126 &self.buf[o..o + l]
127 }
128
129 /// The NUL-terminated string at STRINGS offset `off`; "" for [`NONE`].
130 pub fn read_str(&self, off: u32) -> String {
131 if off == NONE {
132 return String::new();
133 }
134 let s = self.sec_bytes(SEC_STRINGS);
135 let start = off as usize;
136 let mut n = 0;
137 while start + n < s.len() && s[start + n] != 0 {
138 n += 1;
139 }
140 String::from_utf8_lossy(&s[start..start + n]).into_owned()
141 }
142
143 /// `(lat, lon)` in degrees.
144 pub fn stop_ll(&self, i: u32) -> (f64, f64) {
145 let (lat, lon) = self.stop_ll_e7(i);
146 (lat as f64 * 1e-7, lon as f64 * 1e-7)
147 }
148
149 pub fn stop_ll_e7(&self, i: u32) -> (i32, i32) {
150 let s = self.sec_bytes(SEC_STOPS);
151 let base = i as usize * 16;
152 (ri32(s, base), ri32(s, base + 4))
153 }
154
155 pub fn stop_name(&self, i: u32) -> String {
156 self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 8))
157 }
158
159 pub fn stop_code(&self, i: u32) -> String {
160 self.read_str(ru32(self.sec_bytes(SEC_STOPS), i as usize * 16 + 12))
161 }
162
163 /// The raw GTFS `stop_id` (v5 STOP_GTFS_ID).
164 pub fn stop_gtfs_id(&self, i: u32) -> String {
165 self.read_str(ru32(self.sec_bytes(SEC_STOP_GTFS_ID), i as usize * 4))
166 }
167
168 pub fn route(&self, r: u32) -> RouteRec {
169 let s = self.sec_bytes(SEC_ROUTES);
170 let base = r as usize * 32;
171 RouteRec {
172 name_off: ru32(s, base),
173 color: ru32(s, base + 4),
174 route_type: ru32(s, base + 8),
175 feed_idx: ru32(s, base + 12),
176 n_stops: ru32(s, base + 16),
177 first_route_stop: ru32(s, base + 20),
178 n_trips: ru32(s, base + 24),
179 trips_off: ru32(s, base + 28),
180 }
181 }
182
183 /// ROUTE_STOPS entry `i` (an absolute stop index).
184 pub fn route_stop(&self, i: u32) -> u32 {
185 ru32(self.sec_bytes(SEC_ROUTE_STOPS), i as usize * 4)
186 }
187
188 /// A route's stop pattern.
189 pub fn route_stops(&self, rec: &RouteRec) -> Vec<u32> {
190 (0..rec.n_stops).map(|p| self.route_stop(rec.first_route_stop + p)).collect()
191 }
192
193 /// Decode a route's varint trip block, in start-time order.
194 pub fn route_trips(&self, rec: &RouteRec) -> Vec<TripRec> {
195 let s = self.sec_bytes(SEC_ROUTE_TRIPS);
196 let mut pos = rec.trips_off as usize;
197 let mut prev = 0u32;
198 let mut out = Vec::with_capacity(rec.n_trips as usize);
199 for _ in 0..rec.n_trips {
200 let start_time = prev + read_uvarint(s, &mut pos) as u32;
201 out.push(TripRec {
202 start_time,
203 profile_id: read_uvarint(s, &mut pos) as u32,
204 service_idx: read_uvarint(s, &mut pos) as u32,
205 headsign_off: read_uvarint(s, &mut pos) as u32,
206 });
207 prev = start_time;
208 }
209 out
210 }
211
212 /// A route's trips read from v6's fixed-stride table instead of the varint stream.
213 ///
214 /// The point of the table is that a trip is addressable by index, so the device
215 /// reader can stop decoding trips its scan never looks at. Here it serves a second
216 /// purpose: it is an independent decoding of the same data, so
217 /// [`Self::route_trips_strided`] and [`Self::route_trips`] disagreeing means the
218 /// writer emitted two views that do not match.
219 pub fn route_trips_strided(&self, route_idx: u32) -> Vec<TripRec> {
220 let off = self.sec_bytes(SEC_ROUTE_TRIP_OFF);
221 let recs = self.sec_bytes(SEC_ROUTE_TRIP_RECS);
222 if (route_idx as usize + 2) * 4 > off.len() {
223 return Vec::new();
224 }
225 let base = ru32(off, route_idx as usize * 4) as usize;
226 let end = ru32(off, (route_idx as usize + 1) * 4) as usize;
227 if end < base || end * TRIP_REC_BYTES > recs.len() {
228 return Vec::new();
229 }
230 (base..end)
231 .map(|i| {
232 let at = i * TRIP_REC_BYTES;
233 TripRec {
234 start_time: ru32(recs, at),
235 profile_id: ru32(recs, at + 4),
236 service_idx: ru32(recs, at + 8),
237 headsign_off: ru32(recs, at + 12),
238 }
239 })
240 .collect()
241 }
242
243 /// Profile `pid` as per-stop `(arr, dep)` offsets relative to a trip's
244 /// `start_time`. `arr[0]` is negative by the first dwell.
245 pub fn profile(&self, pid: u32) -> Vec<(i64, i64)> {
246 let idx = self.sec_bytes(SEC_PROFILES_IDX);
247 let off = ru32(idx, pid as usize * 4) as usize;
248 let s = self.sec_bytes(SEC_PROFILES);
249 let mut pos = off;
250 let n = read_uvarint(s, &mut pos) as usize;
251 let dwell0 = read_uvarint(s, &mut pos) as i64;
252 let mut out = Vec::with_capacity(n);
253 out.push((-dwell0, 0i64));
254 let mut prev_dep = 0i64;
255 for _ in 1..n {
256 let hop = read_uvarint(s, &mut pos) as i64;
257 let dwell = read_uvarint(s, &mut pos) as i64;
258 let arr = prev_dep + hop;
259 let dep = arr + dwell;
260 out.push((arr, dep));
261 prev_dep = dep;
262 }
263 out
264 }
265
266 pub fn feed_name(&self, feed_idx: u32) -> String {
267 self.read_str(ru32(self.sec_bytes(SEC_FEEDS), feed_idx as usize * 4))
268 }
269
270 pub fn feed_tz(&self, feed_idx: u32) -> String {
271 self.read_str(ru32(self.sec_bytes(SEC_FEED_TZ), feed_idx as usize * 4))
272 }
273
274 pub fn feed_motis_prefix(&self, feed_idx: u32) -> String {
275 self.read_str(ru32(self.sec_bytes(SEC_FEED_MOTIS_PREFIX), feed_idx as usize * 4))
276 }
277
278 pub fn service(&self, service_idx: u32) -> ServiceRec {
279 let s = self.sec_bytes(SEC_SERVICES);
280 let base = service_idx as usize * 12;
281 ServiceRec {
282 weekday_mask: s[base],
283 start_date: ru32(s, base + 4),
284 end_date: ru32(s, base + 8),
285 }
286 }
287
288 /// `(service_idx, date, added)` exceptions for one service, via the CSR.
289 pub fn service_exceptions(&self, service_idx: u32) -> Vec<(u32, u32, u32)> {
290 let idx = self.sec_bytes(SEC_EXCEPTIONS_IDX);
291 let s = self.sec_bytes(SEC_EXCEPTIONS);
292 let lo = ru32(idx, service_idx as usize * 4) as usize;
293 let hi = ru32(idx, (service_idx as usize + 1) * 4) as usize;
294 (lo..hi).map(|i| (ru32(s, i * 12), ru32(s, i * 12 + 4), ru32(s, i * 12 + 8))).collect()
295 }
296
297 /// `(route_idx, stop_pos)` pairs serving `stop`, via STOP_ROUTES(+_POS).
298 pub fn stop_routes(&self, stop: u32) -> Vec<(u32, u32)> {
299 let idx = self.sec_bytes(SEC_STOP_ROUTES_IDX);
300 let routes = self.sec_bytes(SEC_STOP_ROUTES);
301 let pos = self.sec_bytes(SEC_STOP_ROUTE_POS);
302 let lo = ru32(idx, stop as usize * 4) as usize;
303 let hi = ru32(idx, (stop as usize + 1) * 4) as usize;
304 (lo..hi).map(|i| (ru32(routes, i * 4), ru32(pos, i * 4))).collect()
305 }
306
307 /// `(to_stop, secs)` footpaths from `stop`.
308 pub fn transfers(&self, stop: u32) -> Vec<(u32, u32)> {
309 let idx = self.sec_bytes(SEC_TRANSFERS_IDX);
310 let s = self.sec_bytes(SEC_TRANSFERS);
311 let lo = ru32(idx, stop as usize * 4) as usize;
312 let hi = ru32(idx, (stop as usize + 1) * 4) as usize;
313 (lo..hi).map(|i| (ru32(s, i * 8), ru32(s, i * 8 + 4))).collect()
314 }
315
316 /// Every non-empty grid cell as `(cell_id, stops)`, in file order (which the
317 /// reader requires to be `cell_id`-ascending).
318 pub fn grid_cells(&self) -> Vec<(u32, Vec<u32>)> {
319 let ids = self.sec_bytes(SEC_GRID_CELL_IDS);
320 let offs = self.sec_bytes(SEC_GRID_CELL_OFF);
321 let stops = self.sec_bytes(SEC_GRID_STOPS);
322 (0..self.grid_cell_count() as usize)
323 .map(|c| {
324 let lo = ru32(offs, c * 4) as usize;
325 let hi = ru32(offs, (c + 1) * 4) as usize;
326 (ru32(ids, c * 4), (lo..hi).map(|k| ru32(stops, k * 4)).collect())
327 })
328 .collect()
329 }
330
331 /// Byte offset of route `r`'s shape blob in SHAPE_COORDS, or `None`.
332 pub fn route_shape_off(&self, r: u32) -> Option<usize> {
333 let idx = self.sec_bytes(SEC_ROUTE_SHAPE_IDX);
334 let route_count = self.route_count() as usize;
335 assert_eq!(idx.len(), (route_count + 1) * 4, "ROUTE_SHAPE_IDX size");
336 let off = ru32(idx, r as usize * 4);
337 if off == NONE {
338 return None;
339 }
340 let bound = ru32(idx, route_count * 4) as usize;
341 assert_eq!(bound, self.sec_bytes(SEC_SHAPE_COORDS).len(), "ROUTE_SHAPE_IDX bound");
342 assert!(off as usize + 4 <= bound, "shape offset {off} out of SHAPE_COORDS");
343 Some(off as usize)
344 }
345
346 /// Decode the whole polyline at byte offset `off` in SHAPE_COORDS.
347 pub fn shape_points(&self, off: usize) -> Vec<(i32, i32)> {
348 let s = self.sec_bytes(SEC_SHAPE_COORDS);
349 let n = ru32(s, off) as usize;
350 let mut pos = off + 4;
351 let (mut lat, mut lon) = (0i64, 0i64);
352 (0..n)
353 .map(|_| {
354 lat += zigzag(read_uvarint(s, &mut pos));
355 lon += zigzag(read_uvarint(s, &mut pos));
356 (lat as i32, lon as i32)
357 })
358 .collect()
359 }
360
361 /// Vertex index for ROUTE_STOPS entry `i` ([`NONE`] when unshaped).
362 pub fn route_stop_shape(&self, i: u32) -> u32 {
363 ru32(self.sec_bytes(SEC_ROUTE_STOP_SHAPE), i as usize * 4)
364 }
365
366 /// Nearest stop to `(lat, lon)` via the sparse spatial grid, searching ±1
367 /// cell exactly as the device does.
368 pub fn nearest(&self, lat: f64, lon: f64) -> Option<u32> {
369 let g = self.grid();
370 let lat_e7 = (lat * 1e7) as i64;
371 let lon_e7 = (lon * 1e7) as i64;
372 let row0 = ((lat_e7 - g.lat0_e7 as i64) / g.cell_e7 as i64).max(0);
373 let col0 = ((lon_e7 - g.lon0_e7 as i64) / g.cell_e7 as i64).max(0);
374 let ids = self.sec_bytes(SEC_GRID_CELL_IDS);
375 let offs = self.sec_bytes(SEC_GRID_CELL_OFF);
376 let stops = self.sec_bytes(SEC_GRID_STOPS);
377 let n_cells = ids.len() / 4;
378 let find = |cid: u32| -> Option<usize> {
379 let (mut lo, mut hi) = (0usize, n_cells);
380 while lo < hi {
381 let mid = (lo + hi) / 2;
382 let v = ru32(ids, mid * 4);
383 if v == cid {
384 return Some(mid);
385 } else if v < cid {
386 lo = mid + 1;
387 } else {
388 hi = mid;
389 }
390 }
391 None
392 };
393 let mut best = None;
394 let mut bestd = f64::MAX;
395 for dr in -1..=1 {
396 for dc in -1..=1 {
397 let r = row0 + dr;
398 let c = col0 + dc;
399 if r < 0 || c < 0 || c >= g.cols as i64 {
400 continue;
401 }
402 if let Some(ci) = find((r * g.cols as i64 + c) as u32) {
403 let s = ru32(offs, ci * 4) as usize;
404 let e = ru32(offs, (ci + 1) * 4) as usize;
405 for k in s..e {
406 let sid = ru32(stops, k * 4);
407 let (slat, slon) = self.stop_ll(sid);
408 let d = (slat - lat).powi(2) + (slon - lon).powi(2);
409 if d < bestd {
410 bestd = d;
411 best = Some(sid);
412 }
413 }
414 }
415 }
416 }
417 best
418 }
419}