File size: 22,113 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
 
f877698
 
fb3460f
 
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
 
 
 
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from __future__ import annotations

import concurrent.futures
import hashlib
import json
import multiprocessing
import time
import traceback
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import numpy as np
from scipy.spatial.transform import Rotation

from agt.data.camera import exposure_midpoint

from . import scene_store as store

RECIPE_ID = 'lidar_dggt_single_v2'
LABEL_NAME = 'lidar_depth'
LABEL_DIR = Path('labels') / RECIPE_ID
FILE = 'depth.h5'
SOURCE = 'waymo'
DOWNSAMPLE = 4
TRAIN_GRID = (518, 294)
SOURCE_SIZE = (1920, 1080)
WAYMO_CROP_TOP = 100
WAYMO_TOP = 1
WAYMO_LASERS = (1, 2, 3, 4, 5)
WAYMO_SPIN_US = 100_000
DGGT_COMMIT = 'a3276d2bbe4cbb03bcc117830b1836110a27adeb'
DGGT_REFERENCE = (f'xiaomi-research/dggt@{DGGT_COMMIT} datasets/waymo/waymo_preprocess_.py L333-424, L686-736, '
                  'L740-806; datasets/dataset.py L14-34 (resize_flow)')
RESIZE_RULE = ('nearest to 518x294 at load, as DGGT resize_flow: torch F.interpolate(mode="nearest"), source index '
               'floor(i * h / 294) per row and floor(j * w / 518) per column')
COMPONENTS = ('lidar', 'lidar_pose', 'lidar_calibration', 'vehicle_pose')


def label_grid() -> tuple[int, int]:
    width, height = SOURCE_SIZE
    return width // DOWNSAMPLE, height // DOWNSAMPLE


def recipe() -> dict[str, Any]:
    width, height = label_grid()
    rules = {
        'recipe_id': RECIPE_ID, 'source': SOURCE, 'reference': DGGT_REFERENCE,
        'source_size': list(SOURCE_SIZE), 'grid': [width, height], 'downsample': DOWNSAMPLE,
        'scan': ('the scan of the same frame: lidar rows with key.frame_timestamp_micros = the camera row; scan midpoint = '
                 f'frame timestamp + {WAYMO_SPIN_US // 2} us (TOP 10 Hz)'),
        'points': ('DGGT convert_range_image_to_point_cloud_flow, ri_index=0: range_image_return1 of the 5 lasers, '
                   'range > 0; inclination = beam_inclination.values or compute_inclination(min, max), reversed; '
                   'azimuth = ((W..1 - 0.5) / W * 2 - 1) * pi - atan2(R10, R00); TOP: per-pixel range-image pose '
                   '(Rz Ry Rx, xyz) then inverse vehicle_pose of the frame; other lasers: vehicle frame as stored'),
        'camera': ('exposure-midpoint camera_to_world of frames.jsonl (slerp / lerp of pose_start and pose_end); '
                   'world -> camera with scipy Rotation.inv().apply(p - t)'),
        'intrinsics': ('camera.json calibration.native (Waymo corner origin = pixel edges): [[f_u, 0, c_u], [0, f_v, c_v - 100]] '
                       'with each entry /= 1920 / 480 or 1080 / 270 (DGGT)'),
        'projection': ('z > 0, uv = (K p)_xy / (z + 1e-6), 0 <= u < w, 0 <= v < h, floor, np.add.at mean of camera z per '
                       'cell, 0 = no point, float32'),
        'depth_semantics': 'camera axial z (OpenCV camera: x right, y down, z forward), metres; 0 = no LiDAR point',
        'resize_rule': RESIZE_RULE, 'dtype': 'float32',
    }
    return {**rules, 'sha256': hashlib.sha256(json.dumps(rules, sort_keys=True).encode()).hexdigest()}


def exposure_mid_us(frame: dict) -> float:
    return (int(frame['timestamp_start_us']) + int(frame['timestamp_end_us'])) / 2


def edge_matrix(fx: float, fy: float, cx_edge: float, cy_edge: float) -> np.ndarray:
    return np.array([[fx, 0., cx_edge], [0., fy, cy_edge], [0., 0., 1.]], np.float64)


def scale_to_grid(K_edge: np.ndarray, source_size: tuple[int, int], grid: tuple[int, int]) -> np.ndarray:
    K = np.array(K_edge, np.float64)
    (W, H), (w, h) = source_size, grid
    K[0, 0] /= W / w
    K[1, 1] /= H / h
    K[0, 2] /= W / w
    K[1, 2] /= H / h
    return K


def grid_matrix_from_centres(fx: float, fy: float, cx: float, cy: float, size: tuple[int, int],
                             grid: tuple[int, int]) -> np.ndarray:
    return scale_to_grid(edge_matrix(fx, fy, cx + .5, cy + .5), size, grid)


def to_camera(points_world: np.ndarray, camera_to_world: np.ndarray) -> np.ndarray:
    pose = np.asarray(camera_to_world, np.float64)
    return Rotation.from_matrix(pose[:3, :3]).inv().apply(np.asarray(points_world, np.float64) - pose[:3, 3])


def transform(matrix: np.ndarray, points: np.ndarray) -> np.ndarray:
    matrix = np.asarray(matrix, np.float64)
    return np.asarray(points, np.float64) @ matrix[:3, :3].T + matrix[:3, 3]


def project_mean_z(xyz, K_edge, width, height):
    order = np.flatnonzero(np.isfinite(xyz).all(1) & (xyz[:, 2] > 0))
    good = xyz[order]
    projected = good @ K_edge.T
    uv = projected[:, :2] / (projected[:, 2:3] + 1e-6)
    inside = (uv[:, 0] >= 0) & (uv[:, 0] < width) & (uv[:, 1] >= 0) & (uv[:, 1] < height)
    pix = uv[inside].astype(np.int32)
    z = projected[inside, 2]
    sums = np.zeros((height, width), np.float64)
    counts = np.zeros((height, width), np.uint32)
    np.add.at(sums, (pix[:, 1], pix[:, 0]), z)
    np.add.at(counts, (pix[:, 1], pix[:, 0]), 1)
    depth = np.divide(sums, counts, out=np.zeros_like(sums), where=counts > 0)
    return depth.astype(np.float32), counts, len(z)


@dataclass
class FrameLabel:
    depth: np.ndarray
    scan_mid_us: float
    scan_id: int
    points_scan: int
    points_in_grid: int
    extra: dict[str, Any] = field(default_factory=dict)


def empty_label(grid: tuple[int, int], **extra) -> FrameLabel:
    return FrameLabel(np.zeros((grid[1], grid[0]), np.float32), float('nan'), -1, 0, 0, dict(extra))


def waymo_inclination(values, minimum: float, maximum: float, height: int) -> np.ndarray:
    if values is None or len(values) == 0:
        values = (.5 + np.arange(height, dtype=np.float64)) / height * (maximum - minimum) + minimum
    values = np.asarray(values, np.float64)
    if len(values) != height:
        raise ValueError(f'{len(values)} beam inclinations for {height} rows')
    return values[::-1]


def waymo_azimuth(extrinsic: np.ndarray, width: int) -> np.ndarray:
    az_correction = np.arctan2(extrinsic[1, 0], extrinsic[0, 0])
    ratios = (np.arange(width, 0, -1, dtype=np.float64) - .5) / width
    return (ratios * 2. - 1.) * np.pi - az_correction


def rotation_rpy(roll, pitch, yaw) -> np.ndarray:
    cr, sr, cp, sp, cy, sy = np.cos(roll), np.sin(roll), np.cos(pitch), np.sin(pitch), np.cos(yaw), np.sin(yaw)
    out = np.empty(np.shape(roll) + (3, 3), np.float64)
    out[..., 0, 0] = cy * cp
    out[..., 0, 1] = cy * sp * sr - sy * cr
    out[..., 0, 2] = cy * sp * cr + sy * sr
    out[..., 1, 0] = sy * cp
    out[..., 1, 1] = sy * sp * sr + cy * cr
    out[..., 1, 2] = sy * sp * cr - cy * sr
    out[..., 2, 0] = -sp
    out[..., 2, 1] = cp * sr
    out[..., 2, 2] = cp * cr
    return out


def waymo_range_image_points(ranges: np.ndarray, extrinsic: np.ndarray, inclination: np.ndarray,
                             pixel_pose: np.ndarray | None = None, frame_pose: np.ndarray | None = None):
    ranges = np.asarray(ranges, np.float64)
    height, width = ranges.shape
    mask = ranges > 0
    azimuth = waymo_azimuth(extrinsic, width)
    rows, cols = np.nonzero(mask)
    r = ranges[rows, cols]
    az, incl = azimuth[cols], np.asarray(inclination, np.float64)[rows]
    cos_incl = np.cos(incl)
    sensor = np.stack([np.cos(az) * cos_incl * r, np.sin(az) * cos_incl * r, np.sin(incl) * r], -1)
    vehicle = transform(extrinsic, sensor)
    if pixel_pose is not None:
        if frame_pose is None:
            raise ValueError('frame_pose must be set when pixel_pose is set')
        pose = np.asarray(pixel_pose, np.float64)[rows, cols]
        rotation = rotation_rpy(pose[:, 0], pose[:, 1], pose[:, 2])
        world = np.einsum('nij,nj->ni', rotation, vehicle) + pose[:, 3:6]
        vehicle = transform(np.linalg.inv(np.asarray(frame_pose, np.float64)), world)
    return vehicle, mask


def waymo_component(raw: Path, split: str, component: str, segment: str) -> Path:
    return Path(raw) / split / component / f'{segment}.parquet'


def waymo_grid_matrix(camera: dict, grid: tuple[int, int]) -> np.ndarray:
    c = camera['calibration']
    native = c['native']
    if tuple(native['resolution']) != (1920, 1280) or c['crop']['rows_removed_top'] != WAYMO_CROP_TOP:
        raise ValueError('unexpected Waymo native resolution or crop')
    if not native['pixel_coordinates'].startswith('origin_top_left_corner'):
        raise ValueError('Waymo native intrinsics must be corner-origin')
    K = scale_to_grid(edge_matrix(native['f_u'], native['f_v'], native['c_u'], native['c_v'] - WAYMO_CROP_TOP),
                      SOURCE_SIZE, grid)
    fx, fy = c['focal_length_pixels']
    cx, cy = c['principal_point_pixels']
    check = grid_matrix_from_centres(fx, fy, cx, cy, tuple(camera['resolution']), grid)
    if not np.allclose(K, check, rtol=0, atol=1e-9):
        raise AssertionError(f'Waymo quarter K {K.tolist()} != 518x294 camera.json {check.tolist()}')
    return K


class WaymoScene:
    extra_fields = {'lasers': np.int8}

    def __init__(self, raw: Path, scene_dir: Path):
        self.raw, self.scene_dir = Path(raw), Path(scene_dir)
        camera = json.loads((self.scene_dir / 'camera.json').read_text())
        self.segment, self.split = camera['source']['segment'], camera['source']['split']
        self.grid = label_grid()
        self.K = waymo_grid_matrix(camera, self.grid)
        self.local_from_global = np.linalg.inv(np.asarray(camera['world_frame']['world_from_local_waymo_global'], np.float64))
        self.paths = {c: waymo_component(self.raw, self.split, c, self.segment) for c in COMPONENTS}
        self._read_calibration()
        self._read_vehicle_poses()

    def _read_calibration(self):
        import pyarrow.parquet as pq
        p = '[LiDARCalibrationComponent].'
        table = pq.ParquetFile(str(self.paths['lidar_calibration'])).read().to_pydict()
        if set(table['key.segment_context_name']) != {self.segment}:
            raise ValueError(f'{self.segment}: lidar_calibration of another segment')
        self.calibration = {}
        for i, laser in enumerate(table['key.laser_name']):
            self.calibration[int(laser)] = {
                'extrinsic': np.asarray(table[p + 'extrinsic.transform'][i], np.float64).reshape(4, 4),
                'values': table[p + 'beam_inclination.values'][i],
                'min': float(table[p + 'beam_inclination.min'][i]), 'max': float(table[p + 'beam_inclination.max'][i])}
        if sorted(self.calibration) != list(WAYMO_LASERS):
            raise ValueError(f'{self.segment}: lasers {sorted(self.calibration)}')

    def _read_vehicle_poses(self):
        import pyarrow.parquet as pq
        table = pq.ParquetFile(str(self.paths['vehicle_pose'])).read(
            columns=['key.frame_timestamp_micros', '[VehiclePoseComponent].world_from_vehicle.transform']).to_pydict()
        self.vehicle_pose = {int(t): np.asarray(m, np.float64).reshape(4, 4) for t, m in zip(
            table['key.frame_timestamp_micros'], table['[VehiclePoseComponent].world_from_vehicle.transform'])}

    def frame_points(self, ranges: dict[int, np.ndarray], top_pose: np.ndarray, timestamp: int) -> np.ndarray:
        frame_pose = self.vehicle_pose[timestamp]
        out = []
        for laser in WAYMO_LASERS:
            c = self.calibration[laser]
            image = ranges[laser]
            inclination = waymo_inclination(c['values'], c['min'], c['max'], image.shape[0])
            if laser == WAYMO_TOP:
                points, _ = waymo_range_image_points(image[..., 0], c['extrinsic'], inclination, top_pose, frame_pose)
            else:
                points, _ = waymo_range_image_points(image[..., 0], c['extrinsic'], inclination)
            out.append(points)
        return np.concatenate(out)

    def local_points(self, vehicle_points: np.ndarray, timestamp: int) -> np.ndarray:
        return transform(self.local_from_global @ self.vehicle_pose[timestamp], vehicle_points)

    def iter_scans(self, wanted: set[int]):
        import pyarrow.parquet as pq
        pr, lr = '[LiDARPoseComponent].range_image_return1.', '[LiDARComponent].range_image_return1.'
        poses = {}
        handle = pq.ParquetFile(str(self.paths['lidar_pose']))
        for group in range(handle.num_row_groups):
            table = handle.read_row_group(group, columns=['key.frame_timestamp_micros', 'key.laser_name',
                                                          pr + 'values', pr + 'shape'])
            stamps = table.column('key.frame_timestamp_micros').to_pylist()
            lasers = table.column('key.laser_name').to_pylist()
            for i, (t, laser) in enumerate(zip(stamps, lasers)):
                if laser == WAYMO_TOP and int(t) in wanted:
                    shape = table.column(pr + 'shape')[i].as_py()
                    poses[int(t)] = table.column(pr + 'values')[i].values.to_numpy(zero_copy_only=False).reshape(shape)
            del table
        handle = pq.ParquetFile(str(self.paths['lidar']))
        pending: dict[int, dict[int, np.ndarray]] = {}
        for group in range(handle.num_row_groups):
            table = handle.read_row_group(group, columns=['key.frame_timestamp_micros', 'key.laser_name',
                                                          lr + 'values', lr + 'shape'])
            stamps = table.column('key.frame_timestamp_micros').to_pylist()
            lasers = table.column('key.laser_name').to_pylist()
            for i, (t, laser) in enumerate(zip(stamps, lasers)):
                t = int(t)
                if t not in wanted:
                    continue
                shape = table.column(lr + 'shape')[i].as_py()
                pending.setdefault(t, {})[int(laser)] = table.column(lr + 'values')[i].values.to_numpy(
                    zero_copy_only=False).reshape(shape)
                if len(pending[t]) == len(WAYMO_LASERS) and t in poses:
                    yield t, pending.pop(t), poses.pop(t)
            del table
        for t, images in pending.items():
            yield t, images, poses.get(t)

    def label_all(self, frames: list[dict]) -> list[FrameLabel]:
        by_stamp = {int(f['frame_timestamp_us']): i for i, f in enumerate(frames)}
        if len(by_stamp) != len(frames):
            raise ValueError(f'{self.segment}: repeated frame timestamps')
        out: list[FrameLabel | None] = [None] * len(frames)
        for stamp, images, top_pose in self.iter_scans(set(by_stamp)):
            i = by_stamp[stamp]
            if top_pose is None or len(images) != len(WAYMO_LASERS) or stamp not in self.vehicle_pose:
                out[i] = empty_label(self.grid, lasers=len(images))
                continue
            vehicle = self.frame_points(images, top_pose, stamp)
            cam = to_camera(self.local_points(vehicle, stamp), exposure_midpoint(frames[i]))
            depth, _, kept = project_mean_z(cam, self.K, self.grid[0], self.grid[1])
            out[i] = FrameLabel(depth, float(stamp + WAYMO_SPIN_US // 2), stamp, len(vehicle), kept,
                                {'lasers': len(WAYMO_LASERS)})
        return [o if o is not None else empty_label(self.grid, lasers=0) for o in out]


def write_depth_h5(path: Path, *, depth: np.ndarray, frame_indices, timestamp_mid_us, scan_mid_us, scan_id,
                   points_scan, points_in_grid, K_grid: np.ndarray, extra: dict[str, np.ndarray], attrs: dict) -> str:
    import h5py
    depth = np.asarray(depth, np.float32)
    frame_indices = np.asarray(frame_indices, np.int64)
    if depth.ndim != 3 or len(depth) != len(frame_indices) or np.any(np.diff(frame_indices) <= 0):
        raise ValueError('depth must be (T, h, w) with strictly increasing frame indices')
    mid = np.asarray(timestamp_mid_us, np.float64)
    scan_mid = np.asarray(scan_mid_us, np.float64)
    valid_fraction = (depth > 0).reshape(len(depth), -1).mean(1)
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name(path.name + '.tmp')
    with h5py.File(temp, 'w') as f:
        f.create_dataset('depth', data=depth, chunks=(1,) + depth.shape[1:], compression='gzip', compression_opts=4,
                         shuffle=True)
        f['frame_indices'] = frame_indices
        f['timestamp_mid_us'] = mid
        f['scan_mid_us'] = scan_mid
        f['scan_time_offset_us'] = scan_mid - mid
        f['scan_id'] = np.asarray(scan_id, np.int64)
        f['valid_fraction'] = valid_fraction.astype(np.float64)
        f['points_scan'] = np.asarray(points_scan, np.int64)
        f['points_in_grid'] = np.asarray(points_in_grid, np.int64)
        f['K_grid_pixel_edges'] = np.asarray(K_grid, np.float64)
        for name, values in extra.items():
            f[name] = values
        for key, value in attrs.items():
            f.attrs[key] = value if isinstance(value, (str, int, float, np.integer, np.floating)) else json.dumps(
                value, sort_keys=True)
    temp.replace(path)
    return store.sha256_file(path)


def read_jsonl(path: Path) -> list[dict]:
    return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]


def summarise(depth: np.ndarray, offsets_us: np.ndarray, missing: int) -> dict:
    valid = depth > 0
    fraction = valid.reshape(len(depth), -1).mean(1)
    return {'frames': int(len(depth)), 'frames_without_scan': int(missing),
            'valid_fraction_mean': float(fraction.mean()), 'frames_with_zero_valid': int((fraction == 0).sum())}


def label_scene(data_root: Path, raw: Path, scene: str) -> dict:
    started = time.monotonic()
    data_root = Path(data_root)
    rules = recipe()
    target = data_root / LABEL_DIR / SOURCE / scene
    marker = target / 'complete.json'
    try:
        if marker.is_file() and (target / FILE).is_file():
            record = json.loads(marker.read_text())
            if record.get('recipe_sha256') == rules['sha256'] and store.sha256_file(target / FILE) == record['files'][FILE]:
                return {'scene': scene, 'status': 'skipped'}
        scene_dir = data_root / 'scenes' / SOURCE / scene
        labeler = WaymoScene(Path(raw), scene_dir)
        frames = read_jsonl(scene_dir / 'frames.jsonl')
        if [f['frame_index'] for f in frames] != list(range(len(frames))):
            raise ValueError(f'{scene}: frame_index is not 0..T-1')
        labels = labeler.label_all(frames)
        depth = np.stack([lab.depth for lab in labels])
        mid = np.asarray([exposure_mid_us(f) for f in frames], np.float64)
        scan_mid = np.asarray([lab.scan_mid_us for lab in labels], np.float64)
        missing = int(np.isnan(scan_mid).sum())
        extra = {name: np.asarray([lab.extra.get(name, 0) for lab in labels], dtype)
                 for name, dtype in labeler.extra_fields.items()}
        camera = json.loads((scene_dir / 'camera.json').read_text())
        attrs = {'label_name': LABEL_NAME, 'recipe_id': RECIPE_ID, 'recipe_sha256': rules['sha256'],
                 'recipe': rules, 'source': SOURCE, 'scene_id': scene, 'camera_id': camera['camera_id'],
                 'grid_width': labeler.grid[0], 'grid_height': labeler.grid[1],
                 'grid': f'{labeler.grid[0]}x{labeler.grid[1]}', 'source_size': list(SOURCE_SIZE),
                 'train_grid': list(TRAIN_GRID), 'resize_rule': RESIZE_RULE, 'dggt_reference': DGGT_REFERENCE,
                 'depth_semantics': rules['depth_semantics'], 'frames': len(frames), 'frames_without_scan': missing}
        marker.unlink(missing_ok=True)
        digest = write_depth_h5(target / FILE, depth=depth, frame_indices=[f['frame_index'] for f in frames],
                                timestamp_mid_us=mid, scan_mid_us=scan_mid, scan_id=[lab.scan_id for lab in labels],
                                points_scan=[lab.points_scan for lab in labels],
                                points_in_grid=[lab.points_in_grid for lab in labels], K_grid=labeler.K,
                                extra=extra, attrs=attrs)
        summary = summarise(depth, scan_mid - mid, missing)
        record = {'recipe_id': RECIPE_ID, 'recipe_sha256': rules['sha256'], 'source': SOURCE, 'scene_id': scene,
                  'files': {FILE: digest}, 'bytes': (target / FILE).stat().st_size, 'frames': len(frames),
                  'summary': summary, 'seconds': round(time.monotonic() - started, 1)}
        store.atomic_text(marker, json.dumps(record, indent=1, sort_keys=True) + '\n')
        return {'scene': scene, 'status': 'written', **summary, 'seconds': record['seconds']}
    except Exception as exc:
        return {'scene': scene, 'status': 'failed', 'error': repr(exc), 'traceback': traceback.format_exc()}


def write_manifest(data_root: Path) -> Path:
    width, height = label_grid()
    path = Path(data_root) / LABEL_DIR / 'label_manifest.json'
    manifest = {'schema': 'amodaldrive_label_manifest_v1', 'name': LABEL_NAME, 'label_id': RECIPE_ID, 'file': FILE,
                'sources': {SOURCE: {'recipe_id': RECIPE_ID, 'recipe': recipe(), 'source': SOURCE,
                                     'layout': f'{LABEL_DIR}/{SOURCE}/<scene>/{{{FILE}, complete.json}}',
                                     'grid': {'width': width, 'height': height, 'source_size': list(SOURCE_SIZE)},
                                     'resize_rule': RESIZE_RULE}}}
    store.atomic_text(path, json.dumps(manifest, indent=1, sort_keys=True) + '\n')
    return path


def generate(data_root: Path, raw: Path, scenes: list[str], workers: int = 4) -> int:
    write_manifest(data_root)
    failed = 0
    with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, min(workers, len(scenes) or 1)),
                                                mp_context=multiprocessing.get_context('spawn')) as pool:
        futures = [pool.submit(label_scene, str(data_root), str(raw), s) for s in scenes]
        for future in futures:
            res = future.result()
            failed += res['status'] == 'failed'
            print(json.dumps({k: res.get(k) for k in ('scene', 'status', 'frames', 'valid_fraction_mean', 'seconds', 'error')}),
                  flush=True)
            if res['status'] == 'failed':
                print(res['traceback'], flush=True)
    return failed