video.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import gc
  2. import math
  3. import os
  4. import re
  5. import warnings
  6. from fractions import Fraction
  7. from typing import Any, Dict, List, Optional, Tuple, Union
  8. import numpy as np
  9. import torch
  10. from ..utils import _log_api_usage_once
  11. from . import _video_opt
  12. try:
  13. import av
  14. av.logging.set_level(av.logging.ERROR)
  15. if not hasattr(av.video.frame.VideoFrame, "pict_type"):
  16. av = ImportError(
  17. """\
  18. Your version of PyAV is too old for the necessary video operations in torchvision.
  19. If you are on Python 3.5, you will have to build from source (the conda-forge
  20. packages are not up-to-date). See
  21. https://github.com/mikeboers/PyAV#installation for instructions on how to
  22. install PyAV on your system.
  23. """
  24. )
  25. except ImportError:
  26. av = ImportError(
  27. """\
  28. PyAV is not installed, and is necessary for the video operations in torchvision.
  29. See https://github.com/mikeboers/PyAV#installation for instructions on how to
  30. install PyAV on your system.
  31. """
  32. )
  33. def _check_av_available() -> None:
  34. if isinstance(av, Exception):
  35. raise av
  36. def _av_available() -> bool:
  37. return not isinstance(av, Exception)
  38. # PyAV has some reference cycles
  39. _CALLED_TIMES = 0
  40. _GC_COLLECTION_INTERVAL = 10
  41. def write_video(
  42. filename: str,
  43. video_array: torch.Tensor,
  44. fps: float,
  45. video_codec: str = "libx264",
  46. options: Optional[Dict[str, Any]] = None,
  47. audio_array: Optional[torch.Tensor] = None,
  48. audio_fps: Optional[float] = None,
  49. audio_codec: Optional[str] = None,
  50. audio_options: Optional[Dict[str, Any]] = None,
  51. ) -> None:
  52. """
  53. Writes a 4d tensor in [T, H, W, C] format in a video file
  54. Args:
  55. filename (str): path where the video will be saved
  56. video_array (Tensor[T, H, W, C]): tensor containing the individual frames,
  57. as a uint8 tensor in [T, H, W, C] format
  58. fps (Number): video frames per second
  59. video_codec (str): the name of the video codec, i.e. "libx264", "h264", etc.
  60. options (Dict): dictionary containing options to be passed into the PyAV video stream
  61. audio_array (Tensor[C, N]): tensor containing the audio, where C is the number of channels
  62. and N is the number of samples
  63. audio_fps (Number): audio sample rate, typically 44100 or 48000
  64. audio_codec (str): the name of the audio codec, i.e. "mp3", "aac", etc.
  65. audio_options (Dict): dictionary containing options to be passed into the PyAV audio stream
  66. """
  67. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  68. _log_api_usage_once(write_video)
  69. _check_av_available()
  70. video_array = torch.as_tensor(video_array, dtype=torch.uint8).numpy()
  71. # PyAV does not support floating point numbers with decimal point
  72. # and will throw OverflowException in case this is not the case
  73. if isinstance(fps, float):
  74. fps = np.round(fps)
  75. with av.open(filename, mode="w") as container:
  76. stream = container.add_stream(video_codec, rate=fps)
  77. stream.width = video_array.shape[2]
  78. stream.height = video_array.shape[1]
  79. stream.pix_fmt = "yuv420p" if video_codec != "libx264rgb" else "rgb24"
  80. stream.options = options or {}
  81. if audio_array is not None:
  82. audio_format_dtypes = {
  83. "dbl": "<f8",
  84. "dblp": "<f8",
  85. "flt": "<f4",
  86. "fltp": "<f4",
  87. "s16": "<i2",
  88. "s16p": "<i2",
  89. "s32": "<i4",
  90. "s32p": "<i4",
  91. "u8": "u1",
  92. "u8p": "u1",
  93. }
  94. a_stream = container.add_stream(audio_codec, rate=audio_fps)
  95. a_stream.options = audio_options or {}
  96. num_channels = audio_array.shape[0]
  97. audio_layout = "stereo" if num_channels > 1 else "mono"
  98. audio_sample_fmt = container.streams.audio[0].format.name
  99. format_dtype = np.dtype(audio_format_dtypes[audio_sample_fmt])
  100. audio_array = torch.as_tensor(audio_array).numpy().astype(format_dtype)
  101. frame = av.AudioFrame.from_ndarray(audio_array, format=audio_sample_fmt, layout=audio_layout)
  102. frame.sample_rate = audio_fps
  103. for packet in a_stream.encode(frame):
  104. container.mux(packet)
  105. for packet in a_stream.encode():
  106. container.mux(packet)
  107. for img in video_array:
  108. frame = av.VideoFrame.from_ndarray(img, format="rgb24")
  109. frame.pict_type = "NONE"
  110. for packet in stream.encode(frame):
  111. container.mux(packet)
  112. # Flush stream
  113. for packet in stream.encode():
  114. container.mux(packet)
  115. def _read_from_stream(
  116. container: "av.container.Container",
  117. start_offset: float,
  118. end_offset: float,
  119. pts_unit: str,
  120. stream: "av.stream.Stream",
  121. stream_name: Dict[str, Optional[Union[int, Tuple[int, ...], List[int]]]],
  122. ) -> List["av.frame.Frame"]:
  123. global _CALLED_TIMES, _GC_COLLECTION_INTERVAL
  124. _CALLED_TIMES += 1
  125. if _CALLED_TIMES % _GC_COLLECTION_INTERVAL == _GC_COLLECTION_INTERVAL - 1:
  126. gc.collect()
  127. if pts_unit == "sec":
  128. # TODO: we should change all of this from ground up to simply take
  129. # sec and convert to MS in C++
  130. start_offset = int(math.floor(start_offset * (1 / stream.time_base)))
  131. if end_offset != float("inf"):
  132. end_offset = int(math.ceil(end_offset * (1 / stream.time_base)))
  133. else:
  134. warnings.warn("The pts_unit 'pts' gives wrong results. Please use pts_unit 'sec'.")
  135. frames = {}
  136. should_buffer = True
  137. max_buffer_size = 5
  138. if stream.type == "video":
  139. # DivX-style packed B-frames can have out-of-order pts (2 frames in a single pkt)
  140. # so need to buffer some extra frames to sort everything
  141. # properly
  142. extradata = stream.codec_context.extradata
  143. # overly complicated way of finding if `divx_packed` is set, following
  144. # https://github.com/FFmpeg/FFmpeg/commit/d5a21172283572af587b3d939eba0091484d3263
  145. if extradata and b"DivX" in extradata:
  146. # can't use regex directly because of some weird characters sometimes...
  147. pos = extradata.find(b"DivX")
  148. d = extradata[pos:]
  149. o = re.search(rb"DivX(\d+)Build(\d+)(\w)", d)
  150. if o is None:
  151. o = re.search(rb"DivX(\d+)b(\d+)(\w)", d)
  152. if o is not None:
  153. should_buffer = o.group(3) == b"p"
  154. seek_offset = start_offset
  155. # some files don't seek to the right location, so better be safe here
  156. seek_offset = max(seek_offset - 1, 0)
  157. if should_buffer:
  158. # FIXME this is kind of a hack, but we will jump to the previous keyframe
  159. # so this will be safe
  160. seek_offset = max(seek_offset - max_buffer_size, 0)
  161. try:
  162. # TODO check if stream needs to always be the video stream here or not
  163. container.seek(seek_offset, any_frame=False, backward=True, stream=stream)
  164. except av.AVError:
  165. # TODO add some warnings in this case
  166. # print("Corrupted file?", container.name)
  167. return []
  168. buffer_count = 0
  169. try:
  170. for _idx, frame in enumerate(container.decode(**stream_name)):
  171. frames[frame.pts] = frame
  172. if frame.pts >= end_offset:
  173. if should_buffer and buffer_count < max_buffer_size:
  174. buffer_count += 1
  175. continue
  176. break
  177. except av.AVError:
  178. # TODO add a warning
  179. pass
  180. # ensure that the results are sorted wrt the pts
  181. result = [frames[i] for i in sorted(frames) if start_offset <= frames[i].pts <= end_offset]
  182. if len(frames) > 0 and start_offset > 0 and start_offset not in frames:
  183. # if there is no frame that exactly matches the pts of start_offset
  184. # add the last frame smaller than start_offset, to guarantee that
  185. # we will have all the necessary data. This is most useful for audio
  186. preceding_frames = [i for i in frames if i < start_offset]
  187. if len(preceding_frames) > 0:
  188. first_frame_pts = max(preceding_frames)
  189. result.insert(0, frames[first_frame_pts])
  190. return result
  191. def _align_audio_frames(
  192. aframes: torch.Tensor, audio_frames: List["av.frame.Frame"], ref_start: int, ref_end: float
  193. ) -> torch.Tensor:
  194. start, end = audio_frames[0].pts, audio_frames[-1].pts
  195. total_aframes = aframes.shape[1]
  196. step_per_aframe = (end - start + 1) / total_aframes
  197. s_idx = 0
  198. e_idx = total_aframes
  199. if start < ref_start:
  200. s_idx = int((ref_start - start) / step_per_aframe)
  201. if end > ref_end:
  202. e_idx = int((ref_end - end) / step_per_aframe)
  203. return aframes[:, s_idx:e_idx]
  204. def read_video(
  205. filename: str,
  206. start_pts: Union[float, Fraction] = 0,
  207. end_pts: Optional[Union[float, Fraction]] = None,
  208. pts_unit: str = "pts",
  209. output_format: str = "THWC",
  210. ) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]]:
  211. """
  212. Reads a video from a file, returning both the video frames and the audio frames
  213. Args:
  214. filename (str): path to the video file
  215. start_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):
  216. The start presentation time of the video
  217. end_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):
  218. The end presentation time
  219. pts_unit (str, optional): unit in which start_pts and end_pts values will be interpreted,
  220. either 'pts' or 'sec'. Defaults to 'pts'.
  221. output_format (str, optional): The format of the output video tensors. Can be either "THWC" (default) or "TCHW".
  222. Returns:
  223. vframes (Tensor[T, H, W, C] or Tensor[T, C, H, W]): the `T` video frames
  224. aframes (Tensor[K, L]): the audio frames, where `K` is the number of channels and `L` is the number of points
  225. info (Dict): metadata for the video and audio. Can contain the fields video_fps (float) and audio_fps (int)
  226. """
  227. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  228. _log_api_usage_once(read_video)
  229. output_format = output_format.upper()
  230. if output_format not in ("THWC", "TCHW"):
  231. raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.")
  232. from torchvision import get_video_backend
  233. if not os.path.exists(filename):
  234. raise RuntimeError(f"File not found: {filename}")
  235. if get_video_backend() != "pyav":
  236. vframes, aframes, info = _video_opt._read_video(filename, start_pts, end_pts, pts_unit)
  237. else:
  238. _check_av_available()
  239. if end_pts is None:
  240. end_pts = float("inf")
  241. if end_pts < start_pts:
  242. raise ValueError(
  243. f"end_pts should be larger than start_pts, got start_pts={start_pts} and end_pts={end_pts}"
  244. )
  245. info = {}
  246. video_frames = []
  247. audio_frames = []
  248. audio_timebase = _video_opt.default_timebase
  249. try:
  250. with av.open(filename, metadata_errors="ignore") as container:
  251. if container.streams.audio:
  252. audio_timebase = container.streams.audio[0].time_base
  253. if container.streams.video:
  254. video_frames = _read_from_stream(
  255. container,
  256. start_pts,
  257. end_pts,
  258. pts_unit,
  259. container.streams.video[0],
  260. {"video": 0},
  261. )
  262. video_fps = container.streams.video[0].average_rate
  263. # guard against potentially corrupted files
  264. if video_fps is not None:
  265. info["video_fps"] = float(video_fps)
  266. if container.streams.audio:
  267. audio_frames = _read_from_stream(
  268. container,
  269. start_pts,
  270. end_pts,
  271. pts_unit,
  272. container.streams.audio[0],
  273. {"audio": 0},
  274. )
  275. info["audio_fps"] = container.streams.audio[0].rate
  276. except av.AVError:
  277. # TODO raise a warning?
  278. pass
  279. vframes_list = [frame.to_rgb().to_ndarray() for frame in video_frames]
  280. aframes_list = [frame.to_ndarray() for frame in audio_frames]
  281. if vframes_list:
  282. vframes = torch.as_tensor(np.stack(vframes_list))
  283. else:
  284. vframes = torch.empty((0, 1, 1, 3), dtype=torch.uint8)
  285. if aframes_list:
  286. aframes = np.concatenate(aframes_list, 1)
  287. aframes = torch.as_tensor(aframes)
  288. if pts_unit == "sec":
  289. start_pts = int(math.floor(start_pts * (1 / audio_timebase)))
  290. if end_pts != float("inf"):
  291. end_pts = int(math.ceil(end_pts * (1 / audio_timebase)))
  292. aframes = _align_audio_frames(aframes, audio_frames, start_pts, end_pts)
  293. else:
  294. aframes = torch.empty((1, 0), dtype=torch.float32)
  295. if output_format == "TCHW":
  296. # [T,H,W,C] --> [T,C,H,W]
  297. vframes = vframes.permute(0, 3, 1, 2)
  298. return vframes, aframes, info
  299. def _can_read_timestamps_from_packets(container: "av.container.Container") -> bool:
  300. extradata = container.streams[0].codec_context.extradata
  301. if extradata is None:
  302. return False
  303. if b"Lavc" in extradata:
  304. return True
  305. return False
  306. def _decode_video_timestamps(container: "av.container.Container") -> List[int]:
  307. if _can_read_timestamps_from_packets(container):
  308. # fast path
  309. return [x.pts for x in container.demux(video=0) if x.pts is not None]
  310. else:
  311. return [x.pts for x in container.decode(video=0) if x.pts is not None]
  312. def read_video_timestamps(filename: str, pts_unit: str = "pts") -> Tuple[List[int], Optional[float]]:
  313. """
  314. List the video frames timestamps.
  315. Note that the function decodes the whole video frame-by-frame.
  316. Args:
  317. filename (str): path to the video file
  318. pts_unit (str, optional): unit in which timestamp values will be returned
  319. either 'pts' or 'sec'. Defaults to 'pts'.
  320. Returns:
  321. pts (List[int] if pts_unit = 'pts', List[Fraction] if pts_unit = 'sec'):
  322. presentation timestamps for each one of the frames in the video.
  323. video_fps (float, optional): the frame rate for the video
  324. """
  325. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  326. _log_api_usage_once(read_video_timestamps)
  327. from torchvision import get_video_backend
  328. if get_video_backend() != "pyav":
  329. return _video_opt._read_video_timestamps(filename, pts_unit)
  330. _check_av_available()
  331. video_fps = None
  332. pts = []
  333. try:
  334. with av.open(filename, metadata_errors="ignore") as container:
  335. if container.streams.video:
  336. video_stream = container.streams.video[0]
  337. video_time_base = video_stream.time_base
  338. try:
  339. pts = _decode_video_timestamps(container)
  340. except av.AVError:
  341. warnings.warn(f"Failed decoding frames for file {filename}")
  342. video_fps = float(video_stream.average_rate)
  343. except av.AVError as e:
  344. msg = f"Failed to open container for {filename}; Caught error: {e}"
  345. warnings.warn(msg, RuntimeWarning)
  346. pts.sort()
  347. if pts_unit == "sec":
  348. pts = [x * video_time_base for x in pts]
  349. return pts, video_fps