File size: 3,516 Bytes
e302b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Lossless remux of this recorder's no-B-frame MP4 onto recorded arrival times.

Does not open devices. Original video stays untouched; output must be new.
The presentation origin is the first recorded camera frame, not capture start.
"""
import argparse
import csv
from fractions import Fraction
from pathlib import Path
import statistics

import av


def remux(source: Path, timestamps: Path, destination: Path) -> dict:
    if destination.exists():
        raise FileExistsError(destination)
    with timestamps.open() as stream:
        rows = list(csv.DictReader(stream))
    if len(rows) < 2 or [int(r["video_frame_index"]) for r in rows] != list(range(len(rows))):
        raise ValueError("expected at least two contiguous video-frame-index rows")
    hosts = [int(r["host_monotonic_ns"]) for r in rows]
    pts = [round((t - hosts[0]) / 1000) for t in hosts]
    if any(b <= a for a, b in zip(pts, pts[1:])):
        raise ValueError("timestamps must increase at microsecond resolution")
    durations = [b - a for a, b in zip(pts, pts[1:])]
    durations.append(round(statistics.median(durations)))
    # Verify packet count/order BEFORE opening output; this narrow remuxer does
    # not assume packet order equals frame order for arbitrary uploaded videos.
    with av.open(str(source)) as container:
        video = container.streams.video[0]
        if video.codec_context.has_b_frames:
            raise ValueError("B-frames are unsupported by this recorder-specific remuxer")
        packet_pts = [p.pts for p in container.demux(video) if p.size]
    if len(packet_pts) != len(rows) or any(p is None for p in packet_pts):
        raise ValueError("packet/frame count mismatch or missing packet PTS")
    if any(b <= a for a, b in zip(packet_pts, packet_pts[1:])):
        raise ValueError("packet presentation order is not strictly increasing")
    with av.open(str(source)) as container, av.open(str(destination), "w") as output:
        original = container.streams.video[0]
        stream = output.add_stream(template=original)
        stream.time_base = Fraction(1, 1_000_000)
        index = 0
        for packet in container.demux(original):
            if not packet.size:
                continue
            packet.pts = packet.dts = pts[index]
            packet.duration = durations[index]
            packet.time_base = Fraction(1, 1_000_000)
            packet.stream = stream
            output.mux(packet)
            index += 1
    with av.open(str(destination)) as check:
        decoded_pts = [float(f.pts * f.time_base) for f in check.decode(video=0)]
    if len(decoded_pts) != len(pts):
        raise ValueError("remux decoded frame count mismatch")
    max_error_us = max(abs(t * 1e6 - intended) for t, intended in zip(decoded_pts, pts))
    if max_error_us > 2:
        raise ValueError(f"container did not preserve frame timing: {max_error_us} us")
    return {"video": destination.name, "frames": len(pts),
            "first_frame_capture_time_sec": float(rows[0]["time_sec"]),
            "last_frame_pts_sec": decoded_pts[-1], "max_pts_error_us": max_error_us,
            "basis": "CSV host arrival times relative to first frame; codec packets copied without re-encoding"}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("capture", type=Path)
    args = parser.parse_args()
    print(remux(args.capture / "top.mp4", args.capture / "aligned_60hz.csv", args.capture / "top_timed.mp4"))