"""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('