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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Render RoboTrack point annotations on top of their source videos.

Expected layout:

    DATASET_ROOT/
      clip_id/
        video.mp4
        point_tracks.npz

Each NPZ must contain:

    trajs_2d:     (frames, tracks, 2) pixel coordinates
    visibility:   (frames, tracks) visibility scores
    query_frames: (tracks,) first/query frame for each track

The default output is ``point_track_vis.mp4`` in each clip directory. Existing
outputs are skipped unless ``--overwrite`` is supplied, so interrupted runs can
be resumed safely.
"""

from __future__ import annotations

import argparse
import colorsys
import os
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import shutil
import subprocess
import sys

import cv2
import numpy as np


DEFAULT_FFMPEG_CANDIDATES = (
    "/gpfs/projects/raivn/yunbos/.conda/envs/cotracker-perception/bin/ffmpeg",
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("dataset_root", type=Path, help="RoboTrack dataset directory")
    parser.add_argument("--video-name", default="video.mp4")
    parser.add_argument("--tracks-name", default="point_tracks.npz")
    parser.add_argument("--output-name", default="point_track_vis.mp4")
    parser.add_argument(
        "--trail-seconds",
        type=float,
        default=1.0,
        help="Length of the visible motion trail (default: 1.0)",
    )
    parser.add_argument(
        "--visibility-threshold",
        type=float,
        default=0.5,
        help="Scores above this value are drawn as visible (default: 0.5)",
    )
    parser.add_argument(
        "--crf",
        type=int,
        default=20,
        help="H.264 quality: lower is better/larger (default: 20)",
    )
    parser.add_argument(
        "--preset",
        default="veryfast",
        help="libx264 encoding preset (default: veryfast)",
    )
    parser.add_argument(
        "--workers",
        type=int,
        default=min(4, os.cpu_count() or 1),
        help="Parallel clips to render (default: up to 4)",
    )
    parser.add_argument(
        "--limit",
        type=int,
        help="Render only the first N clips (useful for testing)",
    )
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument(
        "--ffmpeg",
        type=Path,
        help="Path to ffmpeg; otherwise resolve it automatically",
    )
    return parser.parse_args()


def find_ffmpeg(explicit_path: Path | None) -> str:
    if explicit_path is not None:
        if not explicit_path.is_file():
            raise FileNotFoundError(f"ffmpeg does not exist: {explicit_path}")
        return str(explicit_path.resolve())

    on_path = shutil.which("ffmpeg")
    if on_path:
        return on_path

    for candidate in DEFAULT_FFMPEG_CANDIDATES:
        if Path(candidate).is_file():
            return candidate

    raise FileNotFoundError("Could not find ffmpeg; pass its path with --ffmpeg")


def track_colors(count: int) -> list[tuple[int, int, int]]:
    """Return visually separated, stable BGR colors."""
    colors = []
    golden_ratio = 0.618033988749895
    for index in range(count):
        hue = (0.07 + index * golden_ratio) % 1.0
        red, green, blue = colorsys.hsv_to_rgb(hue, 0.88, 1.0)
        colors.append((round(blue * 255), round(green * 255), round(red * 255)))
    return colors


def validate_tracks(
    npz_path: Path,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    with np.load(npz_path) as data:
        required = {"trajs_2d", "visibility", "query_frames"}
        missing = required.difference(data.files)
        if missing:
            raise ValueError(f"missing NPZ arrays: {', '.join(sorted(missing))}")
        trajectories = np.asarray(data["trajs_2d"], dtype=np.float32)
        visibility = np.asarray(data["visibility"], dtype=np.float32)
        query_frames = np.asarray(data["query_frames"], dtype=np.int64)

    if trajectories.ndim != 3 or trajectories.shape[-1] != 2:
        raise ValueError(f"trajs_2d must have shape (T, N, 2), got {trajectories.shape}")
    if visibility.shape != trajectories.shape[:2]:
        raise ValueError(
            f"visibility shape {visibility.shape} does not match {trajectories.shape[:2]}"
        )
    if query_frames.shape != (trajectories.shape[1],):
        raise ValueError(
            f"query_frames shape {query_frames.shape} does not match "
            f"({trajectories.shape[1]},)"
        )
    if np.any(query_frames < 0) or np.any(query_frames >= trajectories.shape[0]):
        raise ValueError("query_frames contains an index outside the video")
    return trajectories, visibility, query_frames


def visible_segments(
    points: np.ndarray, visible: np.ndarray
) -> list[np.ndarray]:
    """Split a short trajectory window into contiguous visible polylines."""
    segments: list[np.ndarray] = []
    start = None
    for index, is_visible in enumerate(visible):
        if is_visible and np.isfinite(points[index]).all():
            if start is None:
                start = index
        elif start is not None:
            if index - start >= 2:
                segments.append(points[start:index])
            start = None
    if start is not None and len(points) - start >= 2:
        segments.append(points[start:])
    return segments


def outlined_text(
    frame: np.ndarray,
    text: str,
    origin: tuple[int, int],
    font_scale: float,
    color: tuple[int, int, int],
    thickness: int,
) -> None:
    cv2.putText(
        frame,
        text,
        origin,
        cv2.FONT_HERSHEY_SIMPLEX,
        font_scale,
        (0, 0, 0),
        thickness + 3,
        cv2.LINE_AA,
    )
    cv2.putText(
        frame,
        text,
        origin,
        cv2.FONT_HERSHEY_SIMPLEX,
        font_scale,
        color,
        thickness,
        cv2.LINE_AA,
    )


def fit_text_to_width(
    text: str,
    max_width: int,
    font_scale: float,
    thickness: int,
) -> str:
    """Elide the middle of text while preserving its identifying suffix."""
    def width(candidate: str) -> int:
        size, _ = cv2.getTextSize(
            candidate, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness
        )
        return size[0]

    if width(text) <= max_width:
        return text
    for keep in range(len(text) - 1, 5, -1):
        prefix_length = (keep + 1) // 2
        suffix_length = keep // 2
        candidate = f"{text[:prefix_length]}...{text[-suffix_length:]}"
        if width(candidate) <= max_width:
            return candidate
    return "..."


def draw_overlay(
    frame: np.ndarray,
    frame_index: int,
    trajectories: np.ndarray,
    visibility: np.ndarray,
    query_frames: np.ndarray,
    colors: list[tuple[int, int, int]],
    trail_frames: int,
    visibility_threshold: float,
    clip_id: str,
) -> np.ndarray:
    height, width = frame.shape[:2]
    num_frames, num_tracks = trajectories.shape[:2]
    visible_now = visibility[frame_index] > visibility_threshold
    visible_now &= query_frames <= frame_index

    point_radius = max(4, round(min(width, height) / 120))
    point_outline = max(2, round(point_radius / 3))
    trail_width = max(2, round(point_radius / 2))
    font_scale = min(1.0, max(0.5, min(width, height) / 900))
    font_thickness = max(1, round(font_scale * 2))

    trail_layer = frame.copy()
    first_trail_frame = max(0, frame_index - trail_frames)
    for track_index in range(num_tracks):
        first = max(first_trail_frame, int(query_frames[track_index]))
        points = trajectories[first : frame_index + 1, track_index]
        visible = visibility[first : frame_index + 1, track_index] > visibility_threshold
        for segment in visible_segments(points, visible):
            rounded = np.rint(segment).astype(np.int32).reshape((-1, 1, 2))
            cv2.polylines(
                trail_layer,
                [rounded],
                isClosed=False,
                color=colors[track_index],
                thickness=trail_width,
                lineType=cv2.LINE_AA,
            )
    cv2.addWeighted(trail_layer, 0.72, frame, 0.28, 0.0, dst=frame)

    for track_index in range(num_tracks):
        if not visible_now[track_index]:
            continue
        point = trajectories[frame_index, track_index]
        if not np.isfinite(point).all():
            continue
        x, y = np.rint(point).astype(int)
        # Coordinates just outside the image can occur in hand-authored tracks.
        # Clipping keeps the renderer robust while still placing a marker at the edge.
        x = int(np.clip(x, 0, width - 1))
        y = int(np.clip(y, 0, height - 1))

        if frame_index == int(query_frames[track_index]):
            cv2.circle(
                frame,
                (x, y),
                point_radius + point_outline + 3,
                (255, 255, 255),
                point_outline,
                cv2.LINE_AA,
            )
        cv2.circle(
            frame,
            (x, y),
            point_radius + point_outline,
            (0, 0, 0),
            -1,
            cv2.LINE_AA,
        )
        cv2.circle(
            frame,
            (x, y),
            point_radius,
            colors[track_index],
            -1,
            cv2.LINE_AA,
        )
        label_x = min(width - 1, x + point_radius + 4)
        label_y = int(np.clip(y - point_radius - 2, 14, height - 2))
        outlined_text(
            frame,
            str(track_index),
            (label_x, label_y),
            font_scale * 0.78,
            colors[track_index],
            font_thickness,
        )

    active_count = int(np.count_nonzero(query_frames <= frame_index))
    clip_line = fit_text_to_width(
        f"clip: {clip_id}", width - 20, font_scale, font_thickness
    )
    stats_line = (
        f"frame {frame_index + 1}/{num_frames}   "
        f"visible {int(np.count_nonzero(visible_now))}/{active_count}   "
        f"tracks {num_tracks}"
    )
    clip_size, baseline = cv2.getTextSize(
        clip_line, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness
    )
    stats_size, _ = cv2.getTextSize(
        stats_line, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness
    )
    line_gap = max(5, round(font_scale * 6))
    header_height = clip_size[1] + stats_size[1] + baseline + line_gap + 18
    header_width = min(width, max(clip_size[0], stats_size[0]) + 20)
    header_layer = frame.copy()
    cv2.rectangle(header_layer, (0, 0), (header_width, header_height), (0, 0, 0), -1)
    cv2.addWeighted(header_layer, 0.62, frame, 0.38, 0.0, dst=frame)
    cv2.putText(
        frame,
        clip_line,
        (10, clip_size[1] + 7),
        cv2.FONT_HERSHEY_SIMPLEX,
        font_scale,
        (255, 255, 255),
        font_thickness,
        cv2.LINE_AA,
    )
    cv2.putText(
        frame,
        stats_line,
        (10, clip_size[1] + line_gap + stats_size[1] + 7),
        cv2.FONT_HERSHEY_SIMPLEX,
        font_scale,
        (255, 255, 255),
        font_thickness,
        cv2.LINE_AA,
    )
    return frame


def render_clip(
    clip_dir_string: str,
    video_name: str,
    tracks_name: str,
    output_name: str,
    trail_seconds: float,
    visibility_threshold: float,
    crf: int,
    preset: str,
    ffmpeg: str,
    overwrite: bool,
) -> tuple[str, str, str]:
    clip_dir = Path(clip_dir_string)
    video_path = clip_dir / video_name
    tracks_path = clip_dir / tracks_name
    output_path = clip_dir / output_name
    clip_id = clip_dir.name

    if output_path.exists() and not overwrite:
        return clip_id, "skipped", "already exists"

    trajectories, visibility, query_frames = validate_tracks(tracks_path)
    capture = cv2.VideoCapture(str(video_path))
    if not capture.isOpened():
        raise RuntimeError(f"could not open video: {video_path}")

    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = float(capture.get(cv2.CAP_PROP_FPS))
    reported_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    if width <= 0 or height <= 0 or fps <= 0:
        capture.release()
        raise ValueError(f"invalid video metadata: {width}x{height} at {fps} fps")
    if reported_frames > 0 and reported_frames != trajectories.shape[0]:
        capture.release()
        raise ValueError(
            f"video reports {reported_frames} frames but tracks have "
            f"{trajectories.shape[0]}"
        )

    temporary_path = output_path.with_name(
        f".{output_path.stem}.tmp-{os.getpid()}{output_path.suffix}"
    )
    command = [
        ffmpeg,
        "-hide_banner",
        "-loglevel",
        "error",
        "-y",
        "-f",
        "rawvideo",
        "-pixel_format",
        "bgr24",
        "-video_size",
        f"{width}x{height}",
        "-framerate",
        f"{fps:.8f}",
        "-i",
        "-",
        "-an",
        "-vf",
        "pad=ceil(iw/2)*2:ceil(ih/2)*2",
        "-c:v",
        "libx264",
        "-preset",
        preset,
        "-crf",
        str(crf),
        "-pix_fmt",
        "yuv420p",
        "-movflags",
        "+faststart",
        str(temporary_path),
    ]

    encoder = subprocess.Popen(
        command,
        stdin=subprocess.PIPE,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.PIPE,
    )
    frames_written = 0
    colors = track_colors(trajectories.shape[1])
    trail_frames = max(0, round(trail_seconds * fps))
    failure: Exception | None = None
    try:
        assert encoder.stdin is not None
        for frame_index in range(trajectories.shape[0]):
            ok, frame = capture.read()
            if not ok:
                raise RuntimeError(
                    f"video ended after {frames_written}/{trajectories.shape[0]} frames"
                )
            draw_overlay(
                frame,
                frame_index,
                trajectories,
                visibility,
                query_frames,
                colors,
                trail_frames,
                visibility_threshold,
                clip_id,
            )
            encoder.stdin.write(frame.tobytes())
            frames_written += 1
    except Exception as error:
        failure = error
    finally:
        capture.release()
        if encoder.stdin is not None:
            try:
                encoder.stdin.close()
            except BrokenPipeError:
                pass

    assert encoder.stderr is not None
    encoder_error = encoder.stderr.read().decode("utf-8", errors="replace").strip()
    return_code = encoder.wait()
    if failure is not None or return_code != 0:
        temporary_path.unlink(missing_ok=True)
        details = str(failure) if failure is not None else ""
        if encoder_error:
            details = f"{details}; ffmpeg: {encoder_error}".strip("; ")
        raise RuntimeError(details or f"ffmpeg exited with status {return_code}")

    if frames_written != trajectories.shape[0]:
        temporary_path.unlink(missing_ok=True)
        raise RuntimeError(
            f"wrote {frames_written} frames, expected {trajectories.shape[0]}"
        )
    os.replace(temporary_path, output_path)
    return clip_id, "rendered", f"{frames_written} frames"


def main() -> int:
    args = parse_args()
    dataset_root = args.dataset_root.resolve()
    if not dataset_root.is_dir():
        print(f"error: dataset root does not exist: {dataset_root}", file=sys.stderr)
        return 2
    if args.workers < 1:
        print("error: --workers must be at least 1", file=sys.stderr)
        return 2
    if args.trail_seconds < 0:
        print("error: --trail-seconds cannot be negative", file=sys.stderr)
        return 2
    if not 0 <= args.crf <= 51:
        print("error: --crf must be between 0 and 51", file=sys.stderr)
        return 2

    try:
        ffmpeg = find_ffmpeg(args.ffmpeg)
    except FileNotFoundError as error:
        print(f"error: {error}", file=sys.stderr)
        return 2

    clip_dirs = sorted(
        path
        for path in dataset_root.iterdir()
        if path.is_dir()
        and (path / args.video_name).is_file()
        and (path / args.tracks_name).is_file()
    )
    if args.limit is not None:
        if args.limit < 0:
            print("error: --limit cannot be negative", file=sys.stderr)
            return 2
        clip_dirs = clip_dirs[: args.limit]
    if not clip_dirs:
        print("No matching clip directories found.")
        return 0

    print(
        f"Rendering {len(clip_dirs)} clips from {dataset_root} with "
        f"{args.workers} worker(s)",
        flush=True,
    )
    print(f"ffmpeg: {ffmpeg}", flush=True)

    rendered = 0
    skipped = 0
    failures: list[tuple[str, str]] = []
    common_args = (
        args.video_name,
        args.tracks_name,
        args.output_name,
        args.trail_seconds,
        args.visibility_threshold,
        args.crf,
        args.preset,
        ffmpeg,
        args.overwrite,
    )
    with ProcessPoolExecutor(max_workers=args.workers) as executor:
        future_to_clip = {
            executor.submit(render_clip, str(clip_dir), *common_args): clip_dir.name
            for clip_dir in clip_dirs
        }
        for completed, future in enumerate(as_completed(future_to_clip), start=1):
            clip_id = future_to_clip[future]
            try:
                _, status, detail = future.result()
                if status == "rendered":
                    rendered += 1
                else:
                    skipped += 1
                print(
                    f"[{completed:>3}/{len(clip_dirs)}] {status:8} {clip_id} "
                    f"({detail})",
                    flush=True,
                )
            except Exception as error:
                failures.append((clip_id, str(error)))
                print(
                    f"[{completed:>3}/{len(clip_dirs)}] FAILED   {clip_id}: {error}",
                    file=sys.stderr,
                    flush=True,
                )

    print(
        f"Done: {rendered} rendered, {skipped} skipped, {len(failures)} failed.",
        flush=True,
    )
    if failures:
        print("Failures:", file=sys.stderr)
        for clip_id, error in failures:
            print(f"  {clip_id}: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())