File size: 7,671 Bytes
94a4005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lossless media I/O, bounded by one frame; no resizing or automatic rotation."""
import hashlib
import io
import json
import subprocess
import time
from fractions import Fraction
from pathlib import Path

import av
import numpy as np
from PIL import Image


def rgb(path):
    with Image.open(path) as im:
        if im.mode not in ('RGB', 'L', 'P', 'RGBA'):
            raise ValueError(f'Unsupported source bit depth/mode {im.mode}: {path}')
        if (im.mode == 'RGBA' or 'transparency' in im.info) and im.convert('RGBA').getextrema()[3] != (255, 255):
            raise ValueError(f'Nonopaque source alpha cannot silently be discarded: {path}')
    with av.open(str(path)) as c:
        frames = list(c.decode(video=0))
        if len(frames) != 1 or any(x.bits > 8 for x in frames[0].format.components):
            raise ValueError(f'Expected one 8-bit image: {path}')
        return frames[0].to_ndarray(format='rgb24')


def mask(path):
    with Image.open(path) as im:
        a = np.asarray(im)
    if a.ndim != 2 or not np.isin(a, np.arange(9)).all():
        raise ValueError(f'Unexpected EgoHOS label palette/values: {path}')
    # Shared 0 means unassigned, so explicit source background 0 becomes 9.
    return np.where(a == 0, 9, a).astype(np.uint16)


def decode(path, labels=False):
    with av.open(str(path)) as c:
        for frame in c.decode(video=0):
            yield frame.to_ndarray(format='gray16le' if labels else 'rgb24')


def verify(path, sources, loader, labels=False):
    start = time.monotonic()
    it = iter(sources)
    hashes = []
    for frame in decode(path, labels):
        source = next(it, None)
        if source is None:
            raise ValueError(f'Extra video frame in {path}')
        original = loader(source)
        if not np.array_equal(original, frame):
            raise ValueError(f'Lossless round-trip mismatch at frame {len(hashes)}: {path}')
        hashes.append(hashlib.sha256(frame.tobytes()).hexdigest())
    if next(it, None) is not None or not hashes:
        raise ValueError(f'Missing video frames: {path}')
    return {'frames': len(hashes), 'all_decoded_frames_exact': True,
            'ordered_decoded_sha256': hashes, 'decode_verify_seconds': time.monotonic() - start}


def encode_ffmpeg(paths, target, loader, size, encoder, labels=False):
    pix = 'gray16le' if labels else 'rgb24'
    options = ['-c:v', 'ffv1', '-level', '3', '-pix_fmt', pix if labels else 'bgr0']
    if encoder == 'libx264rgb':
        options = ['-c:v', 'libx264rgb', '-crf', '0', '-preset', 'medium', '-g', '64', '-pix_fmt', 'rgb24']
    command = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', '-f', 'rawvideo',
               '-pixel_format', pix, '-video_size', f'{size[0]}x{size[1]}', '-framerate', '1',
               '-i', 'pipe:0', '-an', *options, str(target)]
    # stderr goes to a file, avoiding a full pipe deadlock on bad inputs.
    with target.with_suffix('.log').open('wb') as log:
        p = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=log)
        try:
            for path in paths:
                a = loader(path)
                if list(a.shape[1::-1]) != size:
                    raise ValueError(f'Changing image size: {path}')
                p.stdin.write(a.astype('<u2' if labels else 'u1', copy=False).tobytes())
            p.stdin.close()
            if p.wait() != 0:
                raise RuntimeError(target.with_suffix('.log').read_text())
        except BaseException:
            p.kill()
            p.wait()
            raise
    target.with_suffix('.log').unlink()
    return command


def encode_copy(paths, target):
    with av.open(str(paths[0])) as src, av.open(str(target), 'w', format='matroska') as dst:
        stream = dst.add_stream_from_template(src.streams.video[0])
        stream.time_base = Fraction(1, 1000)
        for i, path in enumerate(paths):
            packet = av.Packet(Path(path).read_bytes())
            packet.stream = stream
            packet.pts = packet.dts = i * 1000
            packet.duration = 1000
            packet.time_base = Fraction(1, 1000)
            dst.mux(packet)
    with av.open(str(target)) as c:
        actual = [hashlib.sha256(bytes(p)).hexdigest() for p in c.demux(video=0) if p.size]
    expected = [hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths]
    if actual != expected:
        raise ValueError('JPEG packets changed during remux')
    return {'all_jpeg_packets_exact': True, 'packet_count': len(actual), 'ordered_packet_sha256': actual}


def encode(paths, target, labels=False):
    target.parent.mkdir(parents=True, exist_ok=True)
    loader = mask if labels else rgb
    size = list(loader(paths[0]).shape[1::-1])
    candidates, failed = [], []
    choices = ['ffv1'] if labels else ['ffv1', 'libx264rgb']
    if not labels and all(Path(p).suffix.lower() in ('.jpg', '.jpeg') for p in paths):
        choices.insert(0, 'copy')
    for encoder in choices:
        path = target.with_name(target.stem + '.' + encoder + '.mkv')
        start = time.monotonic()
        try:
            extra = encode_copy(paths, path) if encoder == 'copy' else {'command': encode_ffmpeg(paths, path, loader, size, encoder, labels)}
            elapsed = time.monotonic() - start
            proof = verify(path, paths, loader, labels)
            candidates.append({'encoder': encoder, 'path': path, 'bytes': path.stat().st_size,
                               'encode_seconds': elapsed, **proof, **extra})
            if encoder == 'copy':
                break  # Contract prioritizes exact source packet copy.
        except (ValueError, RuntimeError, av.FFmpegError) as e:
            failed.append({'encoder': encoder, 'error': str(e)})
            path.unlink(missing_ok=True)
    if not candidates:
        raise RuntimeError(f'No exact lossless encoder candidate: {failed}')
    chosen = min(candidates, key=lambda x: x['bytes'])
    chosen['path'].replace(target)
    for c in candidates:
        c['path'].unlink(missing_ok=True)
        c.pop('path')
    with av.open(str(target)) as container:
        s = container.streams.video[0]
        actual = {'codec': s.codec_context.name, 'pixel_format': s.codec_context.format.name,
                  'encoded_size': [s.width, s.height]}
    enc = chosen['encoder']
    profile = ('mkv/uint16_ffv1/v1' if labels else {'copy': 'mkv/mjpeg_copy/v1',
               'ffv1': 'mkv/ffv1_rgb/v1', 'libx264rgb': 'mkv/h264_rgb_lossless/v1'}[enc])
    storage = {'profile': profile, **actual, 'storage_fps': 1, 'timebase_role': 'index_only',
               'source_lossy': False if labels else (True if all(Path(p).suffix.lower() in ('.jpg', '.jpeg') for p in paths) else 'unknown'),
               'decoder': {'name': 'PyAV', 'version': av.__version__,
                           'libraries': {k: list(v) for k, v in av.library_versions.items()},
                           'output': 'gray16le' if labels else 'rgb24', 'rotation': 'none',
                           'color_interpretation': 'libswscale source metadata/defaults; identical source/target decoder',
                           'source_color_space': 'unknown'},
               'encoder_parameters': {'name': enc, 'stream_copy': enc == 'copy',
                   'ffmpeg_version': subprocess.check_output(['ffmpeg', '-version'], text=True).splitlines()[0],
                   'crf': 0 if enc == 'libx264rgb' else None, 'gop': 64 if enc == 'libx264rgb' else None}}
    return storage, {'selected': enc, 'candidates': candidates, 'failed_candidates': failed,
                     'pixel_coverage': 'ALL frames, count and order', 'random_access': 'sequential decode from beginning'}