File size: 20,354 Bytes
d4159be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Native Rerun UI backed by delivered MP4/SKQ1/gzip files, with no RRD export.

Video stays compressed in the viewer. Geometry and sensor images are bounded,
replaceable current-frame values; only small timeline metadata spans the episode.
"""
from collections import OrderedDict
import gzip
import json
import os
from pathlib import Path
import queue
import socket
import subprocess
import threading
import time
import traceback

import cv2
import h5py
import numpy as np
import rerun as rr

from compact_mano import CompactMano
from joint_axes import JointAxes
from customer_library import CACHE, discover, location, register, set_initial_cursor, store_id, write_json, validate_display_cache
from loom_viewer import ROOT, CAMERAS, EDGES, HEAD_VERTICES, HEAD_FACES, HEAD_EDGES, contact_mask, layout
from mano_display import vertex_normals
from tactile_display import CurrentFrameRenderer, particles
from viewer_control import ViewerControl
from world_trails import RollingTrail, COLORS


def compressed_json(path):
    return json.loads(gzip.decompress(Path(path).read_bytes()))


def rotation_xyzw(q):
    x, y, z, w = q / np.linalg.norm(q)
    return np.array([[1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
                     [2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
                     [2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)]])


class CompactEpisode:
    def __init__(self, item, url):
        self.item = item
        self.ep = Path(item['local'])
        self.cache = Path(item['mesh_cache']).parent
        validate_display_cache(self.cache, item['frames'], item['inputs'])
        world = compressed_json(self.cache / 'display-v1/world.json.gz')
        self.times = np.asarray(world['timestamps'])
        self.times_ns = np.rint(self.times * 1e9).astype(np.int64)
        self.frames = np.arange(len(self.times), dtype=np.int64)
        self.world = {key: np.asarray([frame[key] for frame in world['frames']], dtype=float)
                      for key in ['head', 'headQ', 'left', 'right']}
        self.tactile = {s: np.asarray(v) for s, v in
                        compressed_json(self.cache / 'display-v1/tactile.json.gz').items()}
        self.mano = CompactMano(item['mesh_cache'])
        self.joint_axes = JointAxes(self.ep)
        self.depth_file = h5py.File(self.ep / 'head_depth/head_depth.h5', 'r')
        self.depth = self.depth_file['depth']
        with h5py.File(self.ep / 'imu/head_imu.h5', 'r') as handle:
            self.imu = handle['aligned/orientation'][:]
        self.trails = {s: RollingTrail(self.world['head'] if s == 'head' else self.world[s][:, 0], self.times)
                       for s in ['head', 'left', 'right']}
        camera = json.loads((self.ep / 'meta/devices/cameras/head_RGB.json').read_text())
        extrinsics = json.loads((self.ep / 'meta/devices/extrinsics.json').read_text())
        self.rgb_to_left = np.asarray(next(t['matrix'] for t in extrinsics['transforms']
                                         if t['from_frame'] == 'head_RGB' and t['to_frame'] == 'head_gray_left'))
        self.k = np.asarray(camera['intrinsics']['K'], dtype=float)
        self.distortion = np.asarray(camera['intrinsics']['distortion'], dtype=float)
        self.rec = rr.RecordingStream(item['application'], recording_id=item['episode'], send_properties=False,
                                      batcher_config=rr.ChunkBatcherConfig(flush_tick=.008))
        self.rec.connect_grpc(url)
        self.last_frame = None
        self.render_count = 0
        self.render_seconds = 0.0
        self.video_bytes = 0
        self.video_frames = {}
        self.tactile_renderers = {side: CurrentFrameRenderer(side, values.shape[1])
                                 for side, values in self.tactile.items()}
        self.skeleton_initialized = False

    def indexes(self, selected=None):
        selected = slice(None) if selected is None else selected
        return [rr.TimeColumn('time', duration=self.times[selected]),
                rr.TimeColumn('frame', sequence=self.frames[selected])]

    def log(self, path, value):
        self.rec.log(path, value, static=True)

    def prepare(self):
        self.rec.send_recording_name(self.item['episode'])
        self.log('data/video/head_RGB/__loading', rr.EncodedImage.from_fields(clear_unset=True))
        self.log('data/world', rr.ViewCoordinates.RIGHT_HAND_Z_UP)
        for camera in CAMERAS:
            path = self.ep / 'camera' / f'{camera}.mp4'
            asset = rr.AssetVideo(path=path)
            timestamps = asset.read_frame_timestamps_nanos()
            if len(timestamps) != len(self.times):
                raise ValueError(f'Video frame count mismatch: {camera}')
            self.video_frames[camera] = len(timestamps)
            self.video_bytes += path.stat().st_size
            entity = 'data/video/' + camera
            self.log(entity, asset)
            self.rec.send_columns(entity, indexes=self.indexes(),
                                  columns=rr.VideoFrameReference.columns_nanos(timestamps))
        # Mark actual delivered frames independently of demand-loaded geometry/pixels.
        for path in ['data/world/head', 'data/depth/image']:
            self.rec.send_columns(path, indexes=self.indexes(),
                                  columns=rr.TextLog.columns(text=[''] * len(self.times)))
        for axis, values in zip('xyzw', self.imu.T):
            self.rec.send_columns('data/imu/' + axis, indexes=self.indexes(),
                                  columns=rr.Scalars.columns(scalars=values))
        for side, label in [('left', '01 Left Tactile'), ('right', '02 Right Tactile')]:
            values = self.tactile[side]
            self.log('__tactile/' + side + '/layout', rr.TextDocument(json.dumps(
                particles(side, values.shape[1]), ensure_ascii=False, separators=(',', ':'))))
            mask = contact_mask(values, side)
            # Keep the same custom STREAMS paths used by the native UI.
            path = '01\\ Tactile/' + label.replace(' ', '\\ ')
            self.log(path, rr.TextDocument('Visible tactile ADC > 0; blank means no contact.'))
            if mask.any():
                color = [255, 155, 45] if side == 'left' else [70, 190, 255]
                self.rec.send_columns(path, indexes=self.indexes(mask), columns=rr.TextLog.columns(
                    text=['Tactile contact'] * int(mask.sum()), color=[color] * int(mask.sum())))
        actions = json.loads((self.ep / 'annotations/auto_actions.json').read_text(encoding='utf-8')).get('actions', [])
        for index, action in enumerate(actions):
            if not isinstance(action.get('start'), (int, float)) or not isinstance(action.get('end'), (int, float)):
                continue
            mask = (self.frames >= action['start']) & (self.frames <= action['end'])
            if mask.any():
                self.rec.send_columns(f'02\\ Actions/{index+1:02d}', indexes=self.indexes(mask),
                                      columns=rr.TextLog.columns(text=[action.get('label', '')] * int(mask.sum())))
        self.render(1)
        self.rec.flush()

    def projection(self, frame, side):
        points = self.world[side][frame]
        q = self.world['headQ'][frame]
        head = self.world['head'][frame]
        uv = np.full((len(points), 2), np.nan)
        if not np.isfinite(q).all() or not np.isfinite(head).all() or np.linalg.norm(q) < 1e-8:
            return uv
        left = (points - head) @ rotation_xyzw(q)
        rgb = (left - self.rgb_to_left[:3, 3]) @ self.rgb_to_left[:3, :3]
        valid = np.isfinite(rgb).all(axis=1) & (rgb[:, 2] > .001)
        if valid.any():
            projected, _ = cv2.projectPoints(rgb[valid], np.zeros(3), np.zeros(3), self.k, self.distortion)
            uv[valid] = projected.reshape(-1, 2)
        return uv

    def render(self, frame):
        if frame == self.last_frame:
            return
        started = time.perf_counter()
        meshes = self.mano.frame(frame)
        for side, color in [('left', [255, 145, 45]), ('right', [70, 190, 255])]:
            mesh = meshes[side]
            if mesh is not None and mesh['transform'] is not None:
                transform = mesh['transform']
                if 'world_vertices' not in mesh:
                    mesh['world_vertices'] = mesh['vertices'] @ transform[:3, :3].T + transform[:3, 3]
                    mesh['normals'] = vertex_normals(mesh['world_vertices'], mesh['faces'])
                # Constant topology is small and reused; no frame geometry is written to disk.
                self.log(f'data/world/{side}/mano', rr.Mesh3D(vertex_positions=mesh['world_vertices'],
                    vertex_normals=mesh['normals'], triangle_indices=mesh['faces'], albedo_factor=color,
                    face_rendering=rr.components.MeshFaceRendering.DoubleSided))
            else:
                self.log(f'data/world/{side}/mano', rr.Mesh3D.from_fields(clear_unset=True))
            positions = self.world[side][frame]
            valid = np.isfinite(positions).all(axis=1)
            prefix = 'L' if side == 'left' else 'R'
            bone_color = [255, 224, 160] if side == 'left' else [165, 235, 255]
            for joint, position in enumerate(positions):
                path = f'data/world/{side}/skeleton/joints/{prefix}{joint:02d}'
                if not self.skeleton_initialized:
                    self.log(path, rr.Points3D.from_fields(radii=.0045, colors=bone_color,
                                                         labels=[f'{prefix}{joint:02d}'], show_labels=False))
                self.log(path, rr.Points3D.from_fields(positions=[position] if valid[joint] else []))
            lines = [positions[[a, b]] for a, b in EDGES if valid[a] and valid[b]]
            self.log(f'data/world/{side}/skeleton/bones', rr.LineStrips3D(lines, radii=.002, colors=bone_color))
            axes, axis_colors = self.joint_axes.frame(side, frame, positions)
            self.log(f'data/world/{side}/skeleton/axes',
                     rr.LineStrips3D(axes, radii=.0008, colors=axis_colors))
            values = self.tactile[side][frame]
            self.log('__tactile/' + side + '/adc', rr.TextDocument(json.dumps(
                dict(frame=int(self.frames[frame]), values=values.tolist()), separators=(',', ':'))))
            tactile_image, changed = self.tactile_renderers[side].render(values)
            if changed:
                self.log(f'data/tactile/{side}/adc', rr.Image(tactile_image))
            uv = self.projection(frame, side)
            valid = np.isfinite(uv).all(axis=1)
            self.log(f'data/video/head_RGB/mocap_overlay/{side}/joints',
                     rr.Points2D(uv[valid], colors=color, radii=4.4))
            self.log(f'data/video/head_RGB/mocap_overlay/{side}/bones',
                     rr.LineStrips2D([uv[[a, b]] for a, b in EDGES if valid[a] and valid[b]], colors=color, radii=2.4))
        head, q = self.world['head'][frame], self.world['headQ'][frame]
        if np.isfinite(head).all() and np.isfinite(q).all() and np.linalg.norm(q) > 1e-8:
            vertices = HEAD_VERTICES @ rotation_xyzw(q).T + head
            self.log('data/world/head/model', rr.Mesh3D(vertex_positions=vertices,
                      triangle_indices=HEAD_FACES, albedo_factor=[232, 238, 246, 75]))
            self.log('data/world/head/outline', rr.LineStrips3D([vertices[[a, b]] for a, b in HEAD_EDGES],
                      colors=[255, 255, 255], radii=.0008))
        else:
            self.log('data/world/head/model', rr.Mesh3D.from_fields(clear_unset=True))
            self.log('data/world/head/outline', rr.LineStrips3D.from_fields(clear_unset=True))
        for side, trail in self.trails.items():
            self.log('data/world/trails/' + side, rr.LineStrips3D(trail.window(frame),
                      radii=rr.Radius.ui_points(.75), colors=COLORS[side]))
        # Preserve numeric depth inspection: read only this HDF5 frame, never render an entire clip.
        self.log('data/depth/image', rr.DepthImage(self.depth[frame][::4, ::4], meter=1000, depth_range=[0, 3000]))
        self.log('__compact/current_frame', rr.TextDocument(str(int(self.frames[frame]))))
        self.last_frame = frame
        self.skeleton_initialized = True
        self.render_count += 1
        self.render_seconds += time.perf_counter() - started

    def frame_at(self, cursor):
        value = cursor.get('time', {}).get('time', 0)
        if cursor.get('timeline', {}).get('name') == 'frame':
            return int(np.clip(value, 0, len(self.frames) - 1))
        return int(np.clip(np.searchsorted(self.times_ns, value, side='right') - 1, 0, len(self.frames) - 1))

    def close(self):
        self.rec.disconnect()
        self.depth_file.close()


class PlaybackObserver:
    """Receive native cursor notifications on loopback without querying all recordings."""
    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(('127.0.0.1', 0))
        self.socket.settimeout(.2)
        self.port = self.socket.getsockname()[1]
        self.stopped = threading.Event()
        self.latest = None
        self.error = None
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.thread.start()

    def run(self):
        try:
            while not self.stopped.is_set():
                try:
                    message, sender = self.socket.recvfrom(8192)
                except socket.timeout:
                    continue
                if sender[0] == '127.0.0.1':
                    try:
                        state = json.loads(message)
                        if isinstance(state.get('recordings'), list) and state.get('active_store_id'):
                            self.latest = (time.monotonic(), state)
                    except (ValueError, AttributeError):
                        continue
        except Exception as error:
            if not self.stopped.is_set():
                self.error = error

    def close(self):
        self.stopped.set()
        self.socket.close()
        self.thread.join(timeout=2)


def serve(data_root, scene=None):
    items, problems = discover(data_root, scene)
    if problems:
        raise RuntimeError(f'{len(problems)} invalid source episodes; see catalog.json')
    for item in items:
        base = Path(item['mesh_cache']).parent / 'display-v1'
        for file in ['manifest.json', 'world.json.gz', 'tactile.json.gz']:
            if not (base / file).is_file():
                raise FileNotFoundError(base / file)
    with socket.socket() as listener:
        listener.bind(('127.0.0.1', 0))
        port = listener.getsockname()[1]
    url = f'rerun+http://127.0.0.1:{port}/proxy'
    observer = PlaybackObserver()
    viewer_log = (CACHE / 'viewer.log').open('w', encoding='utf-8')
    viewer = subprocess.Popen([str(ROOT / 'native-player/rerun.exe'), '--bind', '127.0.0.1',
                               '--port', str(port), '--memory-limit', '80%'],
                              env=dict(os.environ, PATH=str(ROOT / 'native-player') + os.pathsep + os.environ['PATH'],
                                       LOOMG2_CURSOR_PORT=str(observer.port)),
                              stdout=viewer_log, stderr=viewer_log, creationflags=subprocess.CREATE_NO_WINDOW)
    control = None
    resident = OrderedDict()
    current = None
    initialized = set()
    last_status = 0
    try:
        control = ViewerControl(port)
        applications = set()
        for item in items:
            register(item, url)
            if item['application'] not in applications:
                rec = rr.RecordingStream(item['application'], recording_id=item['episode'], send_properties=False)
                rec.connect_grpc(url)
                rec.send_blueprint(layout(native_video=True))
                rec.flush()
                rec.disconnect()
                applications.add(item['application'])
        control.call('rerun_set_location', dict(location=location(items[0])))
        # Discard cursor packets from catalog registration, which briefly selects each scene.
        observer.latest = (time.monotonic(), control.call('rerun_get_state'))
        lookup = {store_id(item): item for item in items}
        write_json(CACHE / 'session.json', dict(port=port, viewer_pid=viewer.pid, loader_pid=os.getpid(),
                   count=len(items), source=str(data_root), mode='compact-read-only'))
        print('COMPACT LIBRARY', len(items), 'episodes; no RRD export', flush=True)
        cursor_ready_after = 0
        while viewer.poll() is None:
            started = time.monotonic()
            if observer.error:
                try:
                    viewer.wait(timeout=2)
                    break
                except subprocess.TimeoutExpired:
                    raise observer.error
            if observer.latest is None:
                time.sleep(.01)
                continue
            observed_at, state = observer.latest
            active = state.get('active_store_id')
            item = lookup.get(active)
            recording = next((r for r in state.get('recordings', []) if r['store_id'] == active), None)
            if item:
                key = item['key']
                if current != key:
                    previous = resident.get(current)
                    if previous:
                        control.call('rerun_set_time_cursor', dict(store_id=store_id(previous.item), play_state='PLAY_STATE_PAUSED'))
                    current = key
                    if key not in resident:
                        begin = time.perf_counter()
                        episode = CompactEpisode(item, url)
                        try:
                            episode.prepare()
                        except Exception:
                            episode.close()
                            raise
                        resident[key] = episode
                        print('COMPACT OPEN', key, round(time.perf_counter() - begin, 3), 'seconds', flush=True)
                    else:
                        resident.move_to_end(key)
                        print('COMPACT REUSE', key, flush=True)
                    if key not in initialized:
                        set_initial_cursor(control, item)
                        cursor_ready_after = time.monotonic()
                        initialized.add(key)
                        recording = None
                    # Keep recent compressed assets; switching never creates a disk cache.
                    while len(resident) > 4 or (len(resident) > 1 and sum(e.video_bytes for e in resident.values()) > 1024**3):
                        old_key, old = resident.popitem(last=False)
                        old.close()
                        control.call('rerun_close', dict(store_ids=dict(store_ids=[store_id(old.item)])))
                        register(old.item, url)
                        control.call('rerun_set_location', dict(location=location(item)))
                        initialized.discard(old_key)
                    last_status = 0
                episode = resident[key]
                if recording and observed_at > cursor_ready_after:
                    episode.render(episode.frame_at(recording.get('current_time', {})))
                if time.monotonic() - last_status > 1:
                    write_json(CACHE / 'status.json', dict(state='ready', episode=key, source='compact-original',
                        resident=list(resident), frame=episode.last_frame, segments_resident=len(episode.mano.segments),
                        segments_read=episode.mano.segments_read, render_count=episode.render_count,
                        mean_render_ms=round(1000 * episode.render_seconds / max(1, episode.render_count), 2),
                        video_bytes=episode.video_bytes, generated_rrd_bytes=0))
                    last_status = time.monotonic()
            playing = recording and recording.get('play_state') == 'PLAY_STATE_PLAYING'
            time.sleep(max(.001, (1/60 if playing else .035) - (time.monotonic() - started)))
    finally:
        if observer:
            observer.close()
        for episode in resident.values():
            episode.close()
        if control:
            control.close()
        viewer_log.close()