File size: 37,898 Bytes
394909b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
#!/usr/bin/env python3
"""Build a compact Foxglove-friendly rosbag from the raw dataset bags.

The raw bags are the source of truth. This script is only for visualization.
It keeps a small set of original topics, adds throttled compressed ToF heatmaps,
and can inject dynamic TF from odometry for Foxglove 3D view.
"""

from __future__ import annotations

import argparse
import glob
import math
import os
import struct
from pathlib import Path

cv2 = None
np = None


TOF_CASCADE_TOPIC = "/nlink_tofsensem_cascade"
TOF_FRAME0_TOPIC = "/nlink_tofsensem_frame0"
LIVOX_LIDAR_TOPIC = "/livox/lidar"
LIVOX_POINTCLOUD_TOPIC = "/foxglove/livox/points"

ODOM_CANDIDATE_TOPICS = (
    "/fusion_odometry/current_point_odom",
    "/fusion_odometry/lazy_point_odom",
    "/ekf_quat/ekf_odom",
    "/ekf/ekf_odom",
    "/Odometry",
    "/vrpn_client_node/crazy/pose",
)

COMPACT_COPY_TOPICS = (
    "/tf_static",
    "/fusion_odometry/current_point_odom",
    "/fusion_odometry/lazy_point_odom",
    "/ekf_quat/ekf_odom",
    "/mavros/imu/data",
    "/mavros/imu/data_raw",
    "/livox/imu",
    TOF_CASCADE_TOPIC,
    TOF_FRAME0_TOPIC,
)


def import_ros_deps():
    try:
        import genpy
        import rosbag
        from geometry_msgs.msg import PoseStamped, TransformStamped
        from nav_msgs.msg import Path as RosPath
        from sensor_msgs.msg import CompressedImage, Image, PointCloud2, PointField
        from tf2_msgs.msg import TFMessage
    except ImportError as exc:
        raise RuntimeError(
            "ROS1 Python dependencies are not available. Run this script inside a ROS1 environment "
            "that can import rosbag, geometry_msgs, sensor_msgs, and tf2_msgs."
        ) from exc
    return genpy, rosbag, PoseStamped, TransformStamped, RosPath, CompressedImage, Image, PointCloud2, PointField, TFMessage


def import_visual_deps():
    global cv2, np
    try:
        import cv2 as cv2_module
        import numpy as np_module
    except ImportError as exc:
        raise RuntimeError(
            "Visualization dependencies are not available. Install python3-opencv and numpy "
            "inside the ROS1 environment used to run this script."
        ) from exc
    cv2 = cv2_module
    np = np_module


def is_valid_stamp(stamp) -> bool:
    return stamp is not None and hasattr(stamp, "to_sec") and stamp.to_sec() > 0.0


def select_time(stamp, fallback_time):
    return stamp if is_valid_stamp(stamp) else fallback_time


def parse_topic_csv(text: str) -> list[str]:
    if not text:
        return []
    return [item.strip() for item in text.split(",") if item.strip()]


def bag_stem(path: str) -> str:
    name = Path(path).name
    return name[:-4] if name.endswith(".bag") else name


class RateLimiter:
    def __init__(self, hz: float):
        self.period = 0.0 if hz <= 0.0 else 1.0 / float(hz)
        self.next_time = None

    def allow(self, stamp) -> bool:
        if self.period <= 0.0:
            return True
        if not is_valid_stamp(stamp):
            return True
        now = stamp.to_sec()
        if self.next_time is None or now >= self.next_time:
            self.next_time = now + self.period
            return True
        return False


class TofHeatmapRenderer:
    def __init__(
        self,
        compressed_image_cls,
        raw_image_cls,
        max_nodes: int,
        grid_size: int,
        cell_px: int,
        min_distance_mm: float,
        max_distance_mm: float,
        valid_status: int,
        colormap_name: str,
        output_format: str,
        jpeg_quality: int,
        draw_distance_text: bool,
        show_tables: bool,
        include_overview_image: bool,
        include_node_images: bool,
        overview_topic: str,
        node_topic_prefix: str,
    ):
        self.CompressedImage = compressed_image_cls
        self.Image = raw_image_cls
        self.max_nodes = max(1, int(max_nodes))
        self.grid_size = int(grid_size)
        self.cell_px = int(cell_px)
        self.min_distance_mm = float(min_distance_mm)
        self.max_distance_mm = float(max_distance_mm)
        self.valid_status = int(valid_status)
        self.colormap = getattr(cv2, colormap_name, cv2.COLORMAP_TURBO)
        self.output_format = output_format
        self.jpeg_quality = int(jpeg_quality)
        self.draw_distance_text = bool(draw_distance_text)
        self.show_tables = bool(show_tables)
        self.include_overview_image = bool(include_overview_image)
        self.include_node_images = bool(include_node_images)
        self.overview_topic = overview_topic
        self.node_topic_prefix = node_topic_prefix
        self.latest_frame0_panels = {}

    @staticmethod
    def get_nodes(msg) -> list:
        if hasattr(msg, "nodes"):
            return list(msg.nodes)
        if hasattr(msg, "node"):
            return list(msg.node)
        return []

    def reshape_or_pad(self, values, fill_value: float = 0.0) -> np.ndarray:
        target = self.grid_size * self.grid_size
        data = list(values[:target])
        if len(data) < target:
            data.extend([fill_value] * (target - len(data)))
        return np.array(data, dtype=np.float32).reshape(self.grid_size, self.grid_size)

    def render_numeric_table(self, grid, title: str, cell_w: int = 44, cell_h: int = 20) -> np.ndarray:
        rows, cols = grid.shape
        header_h = 24
        width = cols * cell_w
        height = header_h + rows * cell_h
        image = np.full((height, width, 3), 248, dtype=np.uint8)

        cv2.putText(image, title, (5, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (20, 20, 20), 1, cv2.LINE_AA)
        for row in range(rows + 1):
            y = header_h + row * cell_h
            cv2.line(image, (0, y), (width, y), (180, 180, 180), 1)
        for col in range(cols + 1):
            x = col * cell_w
            cv2.line(image, (x, header_h), (x, height), (180, 180, 180), 1)

        for row in range(rows):
            for col in range(cols):
                text = str(int(grid[row, col]))
                x = col * cell_w + 3
                y = header_h + row * cell_h + 14
                cv2.putText(image, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.34, (30, 30, 30), 1, cv2.LINE_AA)
        return image

    def render_node(self, node_id: int, pixels, stamp) -> np.ndarray:
        distances = [float(getattr(pixel, "dis", 0.0)) for pixel in pixels]
        statuses = [int(getattr(pixel, "dis_status", 255)) for pixel in pixels]
        strengths = [int(getattr(pixel, "signal_strength", 0)) for pixel in pixels]

        dis = self.reshape_or_pad(distances, fill_value=0.0)
        status = self.reshape_or_pad(statuses, fill_value=255).astype(np.int32)
        strength = self.reshape_or_pad(strengths, fill_value=0).astype(np.int32)
        valid = np.logical_and(status == self.valid_status, dis > 0.0)

        clipped = np.clip(dis, self.min_distance_mm, self.max_distance_mm)
        scale = max(1e-6, self.max_distance_mm - self.min_distance_mm)
        normalized = ((clipped - self.min_distance_mm) / scale * 255.0).astype(np.uint8)
        heat = cv2.applyColorMap(normalized, self.colormap)
        heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB)
        heat[~valid] = np.array([88, 88, 88], dtype=np.uint8)

        tile_size = self.grid_size * self.cell_px
        tile = cv2.resize(heat, (tile_size, tile_size), interpolation=cv2.INTER_NEAREST)
        for idx in range(self.grid_size + 1):
            offset = idx * self.cell_px
            cv2.line(tile, (offset, 0), (offset, tile.shape[0]), (255, 255, 255), 1)
            cv2.line(tile, (0, offset), (tile.shape[1], offset), (255, 255, 255), 1)

        if self.draw_distance_text:
            for row in range(self.grid_size):
                for col in range(self.grid_size):
                    text = str(int(dis[row, col]))
                    x = col * self.cell_px + 3
                    y = row * self.cell_px + int(self.cell_px * 0.65)
                    color = (255, 255, 255) if valid[row, col] else (220, 220, 220)
                    cv2.putText(tile, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.32, color, 1, cv2.LINE_AA)

        body = tile
        if self.show_tables:
            status_table = self.render_numeric_table(status, "dis_status")
            strength_table = self.render_numeric_table(strength, "signal_strength")
            table_w = max(status_table.shape[1], strength_table.shape[1])

            def pad_width(image, width):
                if image.shape[1] == width:
                    return image
                pad = np.full((image.shape[0], width - image.shape[1], 3), 248, dtype=np.uint8)
                return np.concatenate([image, pad], axis=1)

            status_table = pad_width(status_table, table_w)
            strength_table = pad_width(strength_table, table_w)
            table_gap = np.full((8, table_w, 3), 245, dtype=np.uint8)
            tables = np.concatenate([status_table, table_gap, strength_table], axis=0)

            content_h = max(tile.shape[0], tables.shape[0])
            tile_pad = np.full((content_h, tile.shape[1], 3), 245, dtype=np.uint8)
            table_pad = np.full((content_h, tables.shape[1], 3), 245, dtype=np.uint8)
            tile_pad[:tile.shape[0], :tile.shape[1], :] = tile
            table_pad[:tables.shape[0], :tables.shape[1], :] = tables
            gap = np.full((content_h, 10, 3), 245, dtype=np.uint8)
            body = np.concatenate([tile_pad, gap, table_pad], axis=1)

        header_h = 32
        panel = np.full((header_h + body.shape[0], body.shape[1], 3), 245, dtype=np.uint8)
        valid_ratio = float(np.count_nonzero(valid)) / float(valid.size) if valid.size else 0.0
        title = "node {}  dis(mm) heatmap  valid {:.0f}%".format(node_id, valid_ratio * 100.0)
        if is_valid_stamp(stamp):
            title += "  t={:.2f}".format(stamp.to_sec())
        cv2.putText(panel, title, (6, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (20, 20, 20), 1, cv2.LINE_AA)
        panel[header_h:, :, :] = body
        return panel

    @staticmethod
    def render_overview(node_panels):
        if not node_panels:
            return np.full((260, 420, 3), 245, dtype=np.uint8)

        cols = min(3, len(node_panels))
        rows = int(math.ceil(len(node_panels) / float(cols)))
        gap = 12
        top = 38
        tile_h = max(panel.shape[0] for panel in node_panels)
        tile_w = max(panel.shape[1] for panel in node_panels)
        canvas_h = top + rows * tile_h + max(0, rows - 1) * gap + 12
        canvas_w = cols * tile_w + max(0, cols - 1) * gap + 12
        canvas = np.full((canvas_h, canvas_w, 3), 245, dtype=np.uint8)
        cv2.putText(
            canvas,
            "TOFSense-M cascade heatmap",
            (6, 25),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.72,
            (20, 20, 20),
            2,
            cv2.LINE_AA,
        )
        for idx, panel in enumerate(node_panels):
            row = idx // cols
            col = idx % cols
            y = top + row * (tile_h + gap)
            x = 6 + col * (tile_w + gap)
            canvas[y:y + panel.shape[0], x:x + panel.shape[1], :] = panel
        return canvas

    def to_ros_image(self, image_rgb: np.ndarray, stamp):
        if self.output_format == "raw":
            msg = self.Image()
            if is_valid_stamp(stamp):
                msg.header.stamp = stamp
            msg.height = image_rgb.shape[0]
            msg.width = image_rgb.shape[1]
            msg.encoding = "rgb8"
            msg.is_bigendian = 0
            msg.step = msg.width * 3
            msg.data = np.ascontiguousarray(image_rgb).tobytes()
            return msg

        msg = self.CompressedImage()
        if is_valid_stamp(stamp):
            msg.header.stamp = stamp
        image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
        if self.output_format == "png":
            ok, encoded = cv2.imencode(".png", image_bgr, [cv2.IMWRITE_PNG_COMPRESSION, 3])
            msg.format = "png"
        else:
            ok, encoded = cv2.imencode(".jpg", image_bgr, [cv2.IMWRITE_JPEG_QUALITY, self.jpeg_quality])
            msg.format = "jpeg"
        if not ok:
            raise RuntimeError("failed to encode ToF heatmap")
        msg.data = encoded.tobytes()
        return msg

    def consume_cascade(self, msg, fallback_time) -> list[tuple[str, object, object]]:
        stamp = fallback_time
        if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
            stamp = select_time(msg.header.stamp, fallback_time)

        node_panels = []
        node_outputs = []
        for idx, node in enumerate(self.get_nodes(msg)[:self.max_nodes]):
            node_id = int(getattr(node, "id", idx))
            panel = self.render_node(node_id, list(getattr(node, "pixels", [])), stamp)
            node_panels.append(panel)
            if self.include_node_images:
                node_outputs.append((
                    self.node_topic_prefix + str(node_id),
                    self.to_ros_image(panel, stamp),
                    select_time(stamp, fallback_time),
                ))

        outputs = []
        if self.include_overview_image:
            overview = self.render_overview(node_panels)
            outputs.append((self.overview_topic, self.to_ros_image(overview, stamp), select_time(stamp, fallback_time)))
        outputs.extend(node_outputs)
        return outputs

    def consume_frame0(self, msg, fallback_time) -> list[tuple[str, object, object]]:
        stamp = fallback_time
        if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
            stamp = select_time(msg.header.stamp, fallback_time)

        node_id = int(getattr(msg, "id", 0))
        panel = self.render_node(node_id, list(getattr(msg, "pixels", [])), stamp)
        self.latest_frame0_panels[node_id] = panel

        ordered_ids = sorted(self.latest_frame0_panels.keys())[:self.max_nodes]
        outputs = []
        if self.include_overview_image:
            overview = self.render_overview([self.latest_frame0_panels[item] for item in ordered_ids])
            outputs.append((self.overview_topic, self.to_ros_image(overview, stamp), select_time(stamp, fallback_time)))
        if self.include_node_images:
            outputs.append((self.node_topic_prefix + str(node_id), self.to_ros_image(panel, stamp), select_time(stamp, fallback_time)))
        return outputs


class Converter:
    def __init__(self, args):
        self.args = args
        import_visual_deps()
        (
            self.genpy,
            self.rosbag,
            self.PoseStamped,
            self.TransformStamped,
            self.RosPath,
            self.CompressedImage,
            self.Image,
            self.PointCloud2,
            self.PointField,
            self.TFMessage,
        ) = import_ros_deps()
        self.input_bag = Path(args.input_bag).resolve()
        self.output_bag = self.resolve_output_bag()
        self.tof_limiter = RateLimiter(args.tof_rate_hz)
        self.tf_limiter = RateLimiter(args.tf_rate_hz)
        self.path_limiter = RateLimiter(args.path_rate_hz)
        self.odom_path = None
        self.copy_topics = self.resolve_copy_topics()
        self.renderer = TofHeatmapRenderer(
            compressed_image_cls=self.CompressedImage,
            raw_image_cls=self.Image,
            max_nodes=args.tof_max_nodes,
            grid_size=args.tof_grid_size,
            cell_px=args.tof_cell_px,
            min_distance_mm=args.tof_min_dis,
            max_distance_mm=args.tof_max_dis,
            valid_status=args.tof_valid_status,
            colormap_name=args.tof_colormap,
            output_format=args.tof_output_format,
            jpeg_quality=args.tof_jpeg_quality,
            draw_distance_text=args.tof_draw_distance_text,
            show_tables=args.tof_show_tables,
            include_overview_image=args.tof_image_mode in ("overview", "both"),
            include_node_images=args.tof_image_mode in ("nodes", "both"),
            overview_topic=args.tof_overview_topic,
            node_topic_prefix=args.tof_node_topic_prefix,
        )

    def resolve_output_bag(self) -> Path:
        if self.args.output_bag:
            output = Path(self.args.output_bag).resolve()
        else:
            output_dir = Path(self.args.output_dir).resolve() if self.args.output_dir else self.input_bag.parent / "foxglove"
            output = output_dir / (bag_stem(str(self.input_bag)) + "_foxglove_compact.bag")
        if output == self.input_bag:
            raise RuntimeError("output bag path must be different from input bag path")
        output.parent.mkdir(parents=True, exist_ok=True)
        if output.exists():
            if self.args.force:
                output.unlink()
            else:
                raise RuntimeError("output bag already exists: {} (use --force)".format(output))
        return output

    def resolve_copy_topics(self) -> set[str]:
        mode = self.args.copy_mode
        if mode == "none":
            topics = set()
        elif mode == "compact":
            topics = set(COMPACT_COPY_TOPICS)
        elif mode == "custom":
            topics = set()
        else:
            topics = None

        if topics is not None:
            topics.update(parse_topic_csv(self.args.copy_topics))
            topics.update(parse_topic_csv(self.args.keep_topics))
        return topics

    def choose_topic(self, topic_info, requested, candidates, label):
        if requested and requested != "auto":
            if requested not in topic_info:
                raise RuntimeError("{} topic not found in bag: {}".format(label, requested))
            return requested
        for topic in candidates:
            if topic in topic_info:
                return topic
        return None

    def build_tf_from_pose(self, msg, bag_time):
        if hasattr(msg, "pose") and hasattr(msg.pose, "pose"):
            pose = msg.pose.pose
            stamp = select_time(msg.header.stamp, bag_time)
            parent = self.args.tf_parent_frame or getattr(msg.header, "frame_id", "") or "map"
        elif hasattr(msg, "pose"):
            pose = msg.pose
            stamp = select_time(msg.header.stamp, bag_time)
            parent = self.args.tf_parent_frame or getattr(msg.header, "frame_id", "") or "map"
        else:
            return None, None

        transform = self.TransformStamped()
        transform.header.stamp = stamp
        transform.header.frame_id = parent
        transform.child_frame_id = self.args.tf_child_frame
        transform.transform.translation.x = pose.position.x
        transform.transform.translation.y = pose.position.y
        transform.transform.translation.z = pose.position.z
        transform.transform.rotation.x = pose.orientation.x
        transform.transform.rotation.y = pose.orientation.y
        transform.transform.rotation.z = pose.orientation.z
        transform.transform.rotation.w = pose.orientation.w
        return self.TFMessage(transforms=[transform]), stamp

    def build_path_from_odometry(self, msg, bag_time):
        if hasattr(msg, "pose") and hasattr(msg.pose, "pose"):
            pose = msg.pose.pose
            stamp = select_time(msg.header.stamp, bag_time)
        elif hasattr(msg, "pose"):
            pose = msg.pose
            stamp = select_time(msg.header.stamp, bag_time)
        else:
            return None, None

        frame_id = self.args.path_frame
        if frame_id == "auto":
            frame_id = self.args.tf_parent_frame or getattr(msg.header, "frame_id", "") or "odom"

        if self.odom_path is None:
            self.odom_path = self.RosPath()
            self.odom_path.header.frame_id = frame_id

        pose_msg = self.PoseStamped()
        pose_msg.header.stamp = stamp
        pose_msg.header.frame_id = frame_id
        pose_msg.pose = pose
        self.odom_path.poses.append(pose_msg)

        if self.args.path_max_poses > 0 and len(self.odom_path.poses) > self.args.path_max_poses:
            self.odom_path.poses = self.odom_path.poses[-self.args.path_max_poses:]

        self.odom_path.header.stamp = stamp
        self.odom_path.header.frame_id = frame_id
        return self.odom_path, stamp

    def build_pointcloud2_from_livox(self, msg, bag_time):
        stamp = bag_time
        frame_id = "livox_frame"
        if hasattr(msg, "header"):
            stamp = select_time(getattr(msg.header, "stamp", None), bag_time)
            frame_id = getattr(msg.header, "frame_id", "") or frame_id

        points = []
        for point in getattr(msg, "points", []):
            x = float(getattr(point, "x", 0.0))
            y = float(getattr(point, "y", 0.0))
            z = float(getattr(point, "z", 0.0))
            if not self.args.livox_keep_zero_points and x == 0.0 and y == 0.0 and z == 0.0:
                continue
            points.append((
                x,
                y,
                z,
                float(getattr(point, "reflectivity", 0)),
                int(getattr(point, "line", 0)) & 0xFF,
                int(getattr(point, "tag", 0)) & 0xFF,
                int(getattr(point, "offset_time", 0)) & 0xFFFFFFFF,
            ))

        cloud = self.PointCloud2()
        cloud.header.stamp = stamp
        cloud.header.frame_id = frame_id
        cloud.height = 1
        cloud.width = len(points)
        cloud.fields = [
            self.PointField(name="x", offset=0, datatype=self.PointField.FLOAT32, count=1),
            self.PointField(name="y", offset=4, datatype=self.PointField.FLOAT32, count=1),
            self.PointField(name="z", offset=8, datatype=self.PointField.FLOAT32, count=1),
            self.PointField(name="intensity", offset=12, datatype=self.PointField.FLOAT32, count=1),
            self.PointField(name="line", offset=16, datatype=self.PointField.UINT8, count=1),
            self.PointField(name="tag", offset=17, datatype=self.PointField.UINT8, count=1),
            self.PointField(name="offset_time", offset=20, datatype=self.PointField.UINT32, count=1),
        ]
        cloud.is_bigendian = False
        cloud.point_step = 24
        cloud.row_step = cloud.point_step * cloud.width
        cloud.is_dense = False

        packer = struct.Struct("<ffffBBxxI")
        data = bytearray(cloud.row_step)
        for idx, point in enumerate(points):
            packer.pack_into(data, idx * cloud.point_step, *point)
        cloud.data = bytes(data)
        return cloud, stamp

    def output_compression(self):
        if self.args.bag_compression == "none":
            return "none"
        return self.args.bag_compression

    def resolve_time_window(self, in_bag):
        if self.args.start_offset_sec is None and self.args.duration_sec is None:
            return None, None

        bag_start = float(in_bag.get_start_time())
        bag_end = float(in_bag.get_end_time())
        start_offset = float(self.args.start_offset_sec or 0.0)
        start_sec = bag_start + max(0.0, start_offset)
        if self.args.duration_sec is None:
            end_sec = bag_end
        else:
            end_sec = min(bag_end, start_sec + max(0.0, float(self.args.duration_sec)))
        if start_sec >= end_sec:
            raise RuntimeError("empty time window: start={} end={}".format(start_sec, end_sec))
        return self.genpy.Time.from_sec(start_sec), self.genpy.Time.from_sec(end_sec)

    def write_static_tf_for_window(self, in_bag, out_bag, window_start):
        if window_start is None:
            return 0
        if self.copy_topics is not None and "/tf_static" not in self.copy_topics:
            return 0
        written = 0
        for _, msg, _ in in_bag.read_messages(topics=["/tf_static"]):
            out_bag.write("/tf_static", msg, t=window_start)
            written += 1
        return written

    def resolve_livox_calibration_path(self):
        if not self.args.inject_livox_static_tf:
            return None
        calib_path = Path(self.args.livox_calibration)
        if not calib_path.is_absolute():
            calib_path = Path(__file__).resolve().parents[1] / calib_path
        if not calib_path.is_file():
            raise RuntimeError("Livox calibration file not found: {}".format(calib_path))
        return calib_path

    def load_livox_static_transform(self, stamp):
        calib_path = self.resolve_livox_calibration_path()
        if calib_path is None:
            return None
        try:
            import yaml
        except ImportError as exc:
            raise RuntimeError("PyYAML is required to read Livox calibration: {}".format(calib_path)) from exc

        with calib_path.open("r", encoding="utf-8") as stream:
            calib = yaml.safe_load(stream) or {}

        parent = calib.get("parent_frame")
        child = calib.get("child_frame")
        translation = calib.get("translation_xyz_m")
        rotation = calib.get("rotation_xyzw")
        if not parent or not child or translation is None or rotation is None:
            raise RuntimeError(
                "Livox calibration must define parent_frame, child_frame, translation_xyz_m, and rotation_xyzw: {}".format(
                    calib_path
                )
            )
        if len(translation) != 3 or len(rotation) != 4:
            raise RuntimeError("invalid Livox calibration vector length: {}".format(calib_path))

        transform = self.TransformStamped()
        transform.header.stamp = stamp or self.genpy.Time(0)
        transform.header.frame_id = str(parent)
        transform.child_frame_id = str(child)
        transform.transform.translation.x = float(translation[0])
        transform.transform.translation.y = float(translation[1])
        transform.transform.translation.z = float(translation[2])
        transform.transform.rotation.x = float(rotation[0])
        transform.transform.rotation.y = float(rotation[1])
        transform.transform.rotation.z = float(rotation[2])
        transform.transform.rotation.w = float(rotation[3])
        return self.TFMessage(transforms=[transform])

    def write_livox_static_tf(self, out_bag, window_start):
        if self.copy_topics is not None and "/tf_static" not in self.copy_topics:
            return 0
        tf_msg = self.load_livox_static_transform(window_start)
        if tf_msg is None:
            return 0
        out_bag.write("/tf_static", tf_msg, t=window_start or self.genpy.Time(0))
        return 1

    def convert(self):
        if not self.input_bag.is_file():
            raise RuntimeError("input bag does not exist: {}".format(self.input_bag))

        processed = 0
        copied = 0
        tof_images = 0
        tf_inserted = 0
        livox_converted = 0
        path_inserted = 0

        with self.rosbag.Bag(str(self.input_bag), "r") as in_bag:
            window_start, window_end = self.resolve_time_window(in_bag)
            topic_info = in_bag.get_type_and_topic_info().topics
            tof_topic = self.choose_topic(
                topic_info,
                self.args.tof_input_topic,
                (TOF_CASCADE_TOPIC, TOF_FRAME0_TOPIC),
                "ToF",
            )
            odom_topic = self.choose_topic(topic_info, self.args.odom_input_topic, ODOM_CANDIDATE_TOPICS, "odometry")
            livox_topic = self.choose_topic(
                topic_info,
                self.args.livox_input_topic,
                (LIVOX_LIDAR_TOPIC,),
                "Livox lidar",
            ) if self.args.convert_livox_pointcloud2 else None

            read_topics = None
            if self.copy_topics is not None:
                read_topics = set(topic for topic in self.copy_topics if topic in topic_info)
                if tof_topic:
                    read_topics.add(tof_topic)
                if self.args.inject_dynamic_tf and odom_topic:
                    read_topics.add(odom_topic)
                if livox_topic:
                    read_topics.add(livox_topic)
                read_topics = sorted(read_topics)

            print("[INFO] input bag: {}".format(self.input_bag))
            print("[INFO] output bag: {}".format(self.output_bag))
            print("[INFO] copy mode: {}".format(self.args.copy_mode))
            print("[INFO] ToF topic: {}".format(tof_topic or "not found"))
            print("[INFO] ToF image mode: {} format={} rate={}Hz".format(
                self.args.tof_image_mode, self.args.tof_output_format, self.args.tof_rate_hz
            ))
            print("[INFO] odometry topic for TF: {}".format(odom_topic or "not found"))
            print("[INFO] odometry Path: {}".format(
                "{} -> {}".format(odom_topic, self.args.odom_path_topic) if odom_topic and self.args.write_odom_path else "disabled/not found"
            ))
            print("[INFO] Livox PointCloud2: {}".format(
                "{} -> {}".format(livox_topic, self.args.livox_pointcloud_topic) if livox_topic else "disabled/not found"
            ))
            print("[INFO] Livox static TF calibration: {}".format(
                self.resolve_livox_calibration_path() if self.args.inject_livox_static_tf else "disabled"
            ))
            if window_start is not None:
                print("[INFO] time window: {:.3f} -> {:.3f} ({:.3f}s)".format(
                    window_start.to_sec(), window_end.to_sec(), window_end.to_sec() - window_start.to_sec()
                ))

            with self.rosbag.Bag(str(self.output_bag), "w", compression=self.output_compression()) as out_bag:
                copied += self.write_static_tf_for_window(in_bag, out_bag, window_start)
                copied += self.write_livox_static_tf(out_bag, window_start)

                for topic, msg, bag_time in in_bag.read_messages(
                    topics=read_topics,
                    start_time=window_start,
                    end_time=window_end,
                ):
                    processed += 1

                    if self.copy_topics is None or topic in self.copy_topics:
                        out_bag.write(topic, msg, t=bag_time)
                        copied += 1

                    if self.args.inject_dynamic_tf and odom_topic and topic == odom_topic and self.tf_limiter.allow(bag_time):
                        tf_msg, tf_time = self.build_tf_from_pose(msg, bag_time)
                        if tf_msg is not None:
                            out_bag.write(self.args.tf_topic, tf_msg, t=tf_time)
                            tf_inserted += 1

                    if self.args.write_odom_path and odom_topic and topic == odom_topic:
                        path_msg, path_time = self.build_path_from_odometry(msg, bag_time)
                        if path_msg is not None and self.path_limiter.allow(path_time):
                            out_bag.write(self.args.odom_path_topic, path_msg, t=path_time)
                            path_inserted += 1

                    if livox_topic and topic == livox_topic:
                        cloud, cloud_time = self.build_pointcloud2_from_livox(msg, bag_time)
                        out_bag.write(self.args.livox_pointcloud_topic, cloud, t=cloud_time)
                        livox_converted += 1

                    if tof_topic and topic == tof_topic and self.args.tof_image_mode != "none" and self.tof_limiter.allow(bag_time):
                        if topic == TOF_CASCADE_TOPIC or hasattr(msg, "nodes") or hasattr(msg, "node"):
                            outputs = self.renderer.consume_cascade(msg, bag_time)
                        else:
                            outputs = self.renderer.consume_frame0(msg, bag_time)
                        for out_topic, out_msg, out_time in outputs:
                            out_bag.write(out_topic, out_msg, t=out_time)
                            tof_images += 1

                    if processed % 10000 == 0:
                        print("[RUNNING] processed={} copied={} tof_images={} tf={} path={} livox_pc2={}".format(
                            processed, copied, tof_images, tf_inserted, path_inserted, livox_converted
                        ))

        input_size = self.input_bag.stat().st_size
        output_size = self.output_bag.stat().st_size
        ratio = float(output_size) / float(input_size) if input_size else 0.0
        print("[DONE] processed={} copied={} tof_images={} tf={} path={} livox_pc2={}".format(
            processed, copied, tof_images, tf_inserted, path_inserted, livox_converted
        ))
        print("[DONE] input_size={:.2f} GB output_size={:.2f} GB ratio={:.3f}".format(
            input_size / 1e9, output_size / 1e9, ratio
        ))


def parse_args():
    parser = argparse.ArgumentParser(description="Create a compact Foxglove visualization rosbag.")
    parser.add_argument("--input-bag", required=True, help="Input ROS1 bag")
    parser.add_argument("--output-bag", default=None, help="Output ROS1 bag")
    parser.add_argument("--output-dir", default=None, help="Output directory when --output-bag is omitted")
    parser.add_argument("--force", action="store_true", help="Overwrite output bag")
    parser.add_argument("--start-offset-sec", type=float, default=None, help="Start offset from input bag start")
    parser.add_argument("--duration-sec", type=float, default=None, help="Maximum duration to convert")

    parser.add_argument(
        "--copy-mode",
        choices=("compact", "all", "none", "custom"),
        default="compact",
        help="Original topic copy policy. compact avoids camera/lidar by default.",
    )
    parser.add_argument("--copy-topics", default="", help="Comma-separated extra original topics to copy")
    parser.add_argument(
        "--keep-topics",
        default="",
        help="Alias for --copy-topics. Use with --copy-mode custom to keep exactly the listed original topics.",
    )
    parser.add_argument("--bag-compression", choices=("none", "bz2", "lz4"), default="bz2")

    parser.add_argument("--tof-input-topic", default="auto")
    parser.add_argument("--tof-image-mode", choices=("overview", "nodes", "both", "none"), default="overview")
    parser.add_argument("--tof-output-format", choices=("jpeg", "png", "raw"), default="jpeg")
    parser.add_argument(
        "--tof-rate-hz",
        type=float,
        default=15.0,
        help="Visualization image rate. 15 matches TOFSense-M 8x8 nominal rate; 0 disables throttling.",
    )
    parser.add_argument("--tof-overview-topic", default="/foxglove/tof/overview/compressed")
    parser.add_argument("--tof-node-topic-prefix", default="/foxglove/tof/node_")
    parser.add_argument("--tof-max-nodes", type=int, default=6)
    parser.add_argument("--tof-grid-size", type=int, default=8)
    parser.add_argument("--tof-cell-px", type=int, default=28)
    parser.add_argument("--tof-min-dis", type=float, default=0.0)
    parser.add_argument("--tof-max-dis", type=float, default=5000.0)
    parser.add_argument("--tof-valid-status", type=int, default=0)
    parser.add_argument("--tof-colormap", default="COLORMAP_TURBO")
    parser.add_argument("--tof-jpeg-quality", type=int, default=82)
    parser.add_argument("--tof-draw-distance-text", dest="tof_draw_distance_text", action="store_true")
    parser.add_argument("--tof-hide-distance-text", dest="tof_draw_distance_text", action="store_false")
    parser.set_defaults(tof_draw_distance_text=True)
    parser.add_argument("--tof-show-tables", dest="tof_show_tables", action="store_true")
    parser.add_argument("--tof-hide-tables", dest="tof_show_tables", action="store_false")
    parser.set_defaults(tof_show_tables=True)

    parser.add_argument("--convert-livox-pointcloud2", dest="convert_livox_pointcloud2", action="store_true")
    parser.add_argument("--no-convert-livox-pointcloud2", dest="convert_livox_pointcloud2", action="store_false")
    parser.set_defaults(convert_livox_pointcloud2=True)
    parser.add_argument("--livox-input-topic", default="auto")
    parser.add_argument("--livox-pointcloud-topic", default=LIVOX_POINTCLOUD_TOPIC)
    parser.add_argument("--livox-keep-zero-points", action="store_true")
    parser.add_argument("--inject-livox-static-tf", dest="inject_livox_static_tf", action="store_true")
    parser.add_argument("--no-inject-livox-static-tf", dest="inject_livox_static_tf", action="store_false")
    parser.set_defaults(inject_livox_static_tf=True)
    parser.add_argument(
        "--livox-calibration",
        default="calibration/robot_v1_template/livox_to_base.yaml",
        help="YAML file with parent_frame, child_frame, translation_xyz_m, and rotation_xyzw.",
    )

    parser.add_argument("--inject-dynamic-tf", dest="inject_dynamic_tf", action="store_true")
    parser.add_argument("--no-inject-dynamic-tf", dest="inject_dynamic_tf", action="store_false")
    parser.set_defaults(inject_dynamic_tf=True)
    parser.add_argument("--odom-input-topic", default="auto")
    parser.add_argument("--tf-rate-hz", type=float, default=10.0, help="0 disables TF throttling")
    parser.add_argument("--tf-topic", default="/tf")
    parser.add_argument("--tf-parent-frame", default="map")
    parser.add_argument("--tf-child-frame", default="base_link")
    parser.add_argument("--write-odom-path", dest="write_odom_path", action="store_true")
    parser.add_argument("--no-write-odom-path", dest="write_odom_path", action="store_false")
    parser.set_defaults(write_odom_path=True)
    parser.add_argument("--odom-path-topic", default="/foxglove/odom/path")
    parser.add_argument("--path-rate-hz", type=float, default=10.0, help="0 writes path at every odometry message")
    parser.add_argument("--path-frame", default="auto", help="Path frame. auto uses --tf-parent-frame, then odometry frame.")
    parser.add_argument("--path-max-poses", type=int, default=0, help="0 keeps the full path")
    return parser.parse_args()


def main():
    args = parse_args()
    Converter(args).convert()


if __name__ == "__main__":
    main()