video.py 18 KB

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