import argparse from collections import deque from dataclasses import dataclass import json import math import os from pathlib import Path import queue import select import shutil import struct import subprocess import threading import time from typing import Optional import numpy as np API_VERSION = 1 class CodecError(RuntimeError): """Decode, protocol, FFmpeg, timeout or QP validation failure.""" @dataclass class Frame: index: int # zero based, in decoded/display order qp: int # decoded QP, never inferred from the filename rgb: Optional[np.ndarray] # uint8 [H,W,3], RGB; None in YUV-only mode mv: np.ndarray # float32 [H,W,2], raw quarter-luma-pixel units res: np.ndarray # float32 [H,W], decoded luma prediction residual yuv420p: Optional[np.ndarray] = None # uint8 [H*3//2,W], Y then U then V def filename(self, digits=5): return 'im{:0{}d}.png'.format(self.index + 1, digits) def _executable(value): text = os.fspath(value) resolved = shutil.which(text) if '/' not in text else text if not resolved or not os.access(resolved, os.X_OK) or not Path(resolved).is_file(): raise FileNotFoundError('executable unavailable: ' + text) return str(Path(resolved).resolve()) def _read_exact(pipe, count, timeout=None): data = bytearray(count) view = memoryview(data) position = 0 deadline = None if timeout is None else time.monotonic() + timeout while position < count: if deadline is not None: remaining = deadline - time.monotonic() if remaining <= 0 or not select.select([pipe], [], [], remaining)[0]: raise CodecError('timed out waiting for decoder metadata') chunk = os.read(pipe.fileno(), min(count-position, 1024*1024)) if not chunk: raise CodecError('truncated decoder/FFmpeg stream: expected {} bytes, received {}'.format(count, position)) view[position:position+len(chunk)] = chunk position += len(chunk) return data def _json_record(pipe, timeout=None): length = struct.unpack(' 51: raise CodecError('misaligned frame index or invalid QP') if self.expected_qp is not None and qp != self.expected_qp: raise CodecError('decoded QP {} differs from expected QP {}'.format(qp, self.expected_qp)) mv = np.frombuffer(_read_exact(pipe, pixels*8), dtype='