AGT / code /agt /data /video.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
4.24 kB
from __future__ import annotations
from pathlib import Path
import numpy as np
class VideoSource:
def __init__(self, path, *, thread_count=2, thread_type=None, expected_frames=None):
self.path = Path(path)
if not self.path.is_file():
raise FileNotFoundError(str(self.path))
self.thread_count, self.thread_type = thread_count, thread_type
self.expected_frames = expected_frames
self._container = self._stream = None
self._pts = self._keyframe = self._index_of = None
def _open(self):
import av
container = av.open(str(self.path))
stream = container.streams.video[0]
if self.thread_type:
stream.thread_type = self.thread_type
if self.thread_count:
stream.thread_count = self.thread_count
return container, stream
def close(self):
if self._container is not None:
self._container.close()
self._container = self._stream = None
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def _ensure_index(self):
if self._pts is not None:
return
container, stream = self._open()
try:
pts, dts, key = [], [], []
for packet in container.demux(stream):
if packet.pts is None:
continue
pts.append(int(packet.pts)); key.append(bool(packet.is_keyframe))
dts.append(int(packet.dts) if packet.dts is not None else int(packet.pts))
finally:
container.close()
order = np.argsort(np.asarray(pts, dtype=np.int64), kind='stable')
self._pts = np.asarray(pts, dtype=np.int64)[order]
self._dts = np.asarray(dts, dtype=np.int64)[order]
self._keyframe = np.asarray(key, dtype=bool)[order]
if not self._keyframe[0]:
raise ValueError(f'{self.path}: first frame is not a keyframe')
if len(np.unique(self._pts)) != len(self._pts):
raise ValueError(f'{self.path}: duplicate packet pts')
if self.expected_frames is not None and len(self._pts) != self.expected_frames:
raise ValueError(f'{self.path}: {len(self._pts)} packets, expected {self.expected_frames} frames')
self._index_of = {int(p): i for i, p in enumerate(self._pts)}
@property
def frame_count(self) -> int:
self._ensure_index(); return int(len(self._pts))
def decode_native(self, indices, *, allow_seek=True) -> dict:
wanted = sorted({int(i) for i in indices})
if not wanted:
raise ValueError('Empty frame selection')
self._ensure_index()
if wanted[0] < 0 or wanted[-1] >= len(self._pts):
raise IndexError(f'{self.path}: frames {wanted[0]}..{wanted[-1]} outside 0..{len(self._pts)-1}')
if self._container is None:
self._container, self._stream = self._open()
container, stream = self._container, self._stream
keyframes = np.flatnonzero(self._keyframe)
k = int(keyframes[np.searchsorted(keyframes, wanted[0], side='right') - 1]) if allow_seek else 0
while True:
container.seek(int(self._dts[k]), backward=True, any_frame=False, stream=stream)
out, wanted_set, last = {}, set(wanted), wanted[-1]
for frame in container.decode(stream):
if frame.pts is None:
continue
index = self._index_of.get(int(frame.pts))
if index is None:
raise ValueError(f'{self.path}: decoded frame pts {frame.pts} not in packet index')
if index in wanted_set:
out[index] = frame.to_ndarray(format='rgb24')
if index >= last:
break
if set(out) == wanted_set:
return out
if k == 0:
raise ValueError(f'{self.path}: missing frames {sorted(wanted_set - set(out))} even from the start')
k = int(keyframes[np.searchsorted(keyframes, k, side='left') - 1])
self.close(); self._container, self._stream = self._open(); container, stream = self._container, self._stream