video_utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import bisect
  2. import math
  3. import warnings
  4. from fractions import Fraction
  5. from typing import Any, Dict, List, Optional, Callable, Union, Tuple, TypeVar, cast
  6. import torch
  7. from torchvision.io import (
  8. _probe_video_from_file,
  9. _read_video_from_file,
  10. read_video,
  11. read_video_timestamps,
  12. )
  13. from .utils import tqdm
  14. T = TypeVar("T")
  15. def pts_convert(pts: int, timebase_from: Fraction, timebase_to: Fraction, round_func: Callable = math.floor) -> int:
  16. """convert pts between different time bases
  17. Args:
  18. pts: presentation timestamp, float
  19. timebase_from: original timebase. Fraction
  20. timebase_to: new timebase. Fraction
  21. round_func: rounding function.
  22. """
  23. new_pts = Fraction(pts, 1) * timebase_from / timebase_to
  24. return round_func(new_pts)
  25. def unfold(tensor: torch.Tensor, size: int, step: int, dilation: int = 1) -> torch.Tensor:
  26. """
  27. similar to tensor.unfold, but with the dilation
  28. and specialized for 1d tensors
  29. Returns all consecutive windows of `size` elements, with
  30. `step` between windows. The distance between each element
  31. in a window is given by `dilation`.
  32. """
  33. if tensor.dim() != 1:
  34. raise ValueError(f"tensor should have 1 dimension instead of {tensor.dim()}")
  35. o_stride = tensor.stride(0)
  36. numel = tensor.numel()
  37. new_stride = (step * o_stride, dilation * o_stride)
  38. new_size = ((numel - (dilation * (size - 1) + 1)) // step + 1, size)
  39. if new_size[0] < 1:
  40. new_size = (0, size)
  41. return torch.as_strided(tensor, new_size, new_stride)
  42. class _VideoTimestampsDataset:
  43. """
  44. Dataset used to parallelize the reading of the timestamps
  45. of a list of videos, given their paths in the filesystem.
  46. Used in VideoClips and defined at top level so it can be
  47. pickled when forking.
  48. """
  49. def __init__(self, video_paths: List[str]) -> None:
  50. self.video_paths = video_paths
  51. def __len__(self) -> int:
  52. return len(self.video_paths)
  53. def __getitem__(self, idx: int) -> Tuple[List[int], Optional[float]]:
  54. return read_video_timestamps(self.video_paths[idx])
  55. def _collate_fn(x: T) -> T:
  56. """
  57. Dummy collate function to be used with _VideoTimestampsDataset
  58. """
  59. return x
  60. class VideoClips:
  61. """
  62. Given a list of video files, computes all consecutive subvideos of size
  63. `clip_length_in_frames`, where the distance between each subvideo in the
  64. same video is defined by `frames_between_clips`.
  65. If `frame_rate` is specified, it will also resample all the videos to have
  66. the same frame rate, and the clips will refer to this frame rate.
  67. Creating this instance the first time is time-consuming, as it needs to
  68. decode all the videos in `video_paths`. It is recommended that you
  69. cache the results after instantiation of the class.
  70. Recreating the clips for different clip lengths is fast, and can be done
  71. with the `compute_clips` method.
  72. Args:
  73. video_paths (List[str]): paths to the video files
  74. clip_length_in_frames (int): size of a clip in number of frames
  75. frames_between_clips (int): step (in frames) between each clip
  76. frame_rate (int, optional): if specified, it will resample the video
  77. so that it has `frame_rate`, and then the clips will be defined
  78. on the resampled video
  79. num_workers (int): how many subprocesses to use for data loading.
  80. 0 means that the data will be loaded in the main process. (default: 0)
  81. output_format (str): The format of the output video tensors. Can be either "THWC" (default) or "TCHW".
  82. """
  83. def __init__(
  84. self,
  85. video_paths: List[str],
  86. clip_length_in_frames: int = 16,
  87. frames_between_clips: int = 1,
  88. frame_rate: Optional[int] = None,
  89. _precomputed_metadata: Optional[Dict[str, Any]] = None,
  90. num_workers: int = 0,
  91. _video_width: int = 0,
  92. _video_height: int = 0,
  93. _video_min_dimension: int = 0,
  94. _video_max_dimension: int = 0,
  95. _audio_samples: int = 0,
  96. _audio_channels: int = 0,
  97. output_format: str = "THWC",
  98. ) -> None:
  99. self.video_paths = video_paths
  100. self.num_workers = num_workers
  101. # these options are not valid for pyav backend
  102. self._video_width = _video_width
  103. self._video_height = _video_height
  104. self._video_min_dimension = _video_min_dimension
  105. self._video_max_dimension = _video_max_dimension
  106. self._audio_samples = _audio_samples
  107. self._audio_channels = _audio_channels
  108. self.output_format = output_format.upper()
  109. if self.output_format not in ("THWC", "TCHW"):
  110. raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.")
  111. if _precomputed_metadata is None:
  112. self._compute_frame_pts()
  113. else:
  114. self._init_from_metadata(_precomputed_metadata)
  115. self.compute_clips(clip_length_in_frames, frames_between_clips, frame_rate)
  116. def _compute_frame_pts(self) -> None:
  117. self.video_pts = []
  118. self.video_fps = []
  119. # strategy: use a DataLoader to parallelize read_video_timestamps
  120. # so need to create a dummy dataset first
  121. import torch.utils.data
  122. dl: torch.utils.data.DataLoader = torch.utils.data.DataLoader(
  123. _VideoTimestampsDataset(self.video_paths), # type: ignore[arg-type]
  124. batch_size=16,
  125. num_workers=self.num_workers,
  126. collate_fn=_collate_fn,
  127. )
  128. with tqdm(total=len(dl)) as pbar:
  129. for batch in dl:
  130. pbar.update(1)
  131. clips, fps = list(zip(*batch))
  132. # we need to specify dtype=torch.long because for empty list,
  133. # torch.as_tensor will use torch.float as default dtype. This
  134. # happens when decoding fails and no pts is returned in the list.
  135. clips = [torch.as_tensor(c, dtype=torch.long) for c in clips]
  136. self.video_pts.extend(clips)
  137. self.video_fps.extend(fps)
  138. def _init_from_metadata(self, metadata: Dict[str, Any]) -> None:
  139. self.video_paths = metadata["video_paths"]
  140. assert len(self.video_paths) == len(metadata["video_pts"])
  141. self.video_pts = metadata["video_pts"]
  142. assert len(self.video_paths) == len(metadata["video_fps"])
  143. self.video_fps = metadata["video_fps"]
  144. @property
  145. def metadata(self) -> Dict[str, Any]:
  146. _metadata = {
  147. "video_paths": self.video_paths,
  148. "video_pts": self.video_pts,
  149. "video_fps": self.video_fps,
  150. }
  151. return _metadata
  152. def subset(self, indices: List[int]) -> "VideoClips":
  153. video_paths = [self.video_paths[i] for i in indices]
  154. video_pts = [self.video_pts[i] for i in indices]
  155. video_fps = [self.video_fps[i] for i in indices]
  156. metadata = {
  157. "video_paths": video_paths,
  158. "video_pts": video_pts,
  159. "video_fps": video_fps,
  160. }
  161. return type(self)(
  162. video_paths,
  163. self.num_frames,
  164. self.step,
  165. self.frame_rate,
  166. _precomputed_metadata=metadata,
  167. num_workers=self.num_workers,
  168. _video_width=self._video_width,
  169. _video_height=self._video_height,
  170. _video_min_dimension=self._video_min_dimension,
  171. _video_max_dimension=self._video_max_dimension,
  172. _audio_samples=self._audio_samples,
  173. _audio_channels=self._audio_channels,
  174. )
  175. @staticmethod
  176. def compute_clips_for_video(
  177. video_pts: torch.Tensor, num_frames: int, step: int, fps: int, frame_rate: Optional[int] = None
  178. ) -> Tuple[torch.Tensor, Union[List[slice], torch.Tensor]]:
  179. if fps is None:
  180. # if for some reason the video doesn't have fps (because doesn't have a video stream)
  181. # set the fps to 1. The value doesn't matter, because video_pts is empty anyway
  182. fps = 1
  183. if frame_rate is None:
  184. frame_rate = fps
  185. total_frames = len(video_pts) * (float(frame_rate) / fps)
  186. _idxs = VideoClips._resample_video_idx(int(math.floor(total_frames)), fps, frame_rate)
  187. video_pts = video_pts[_idxs]
  188. clips = unfold(video_pts, num_frames, step)
  189. if not clips.numel():
  190. warnings.warn(
  191. "There aren't enough frames in the current video to get a clip for the given clip length and "
  192. "frames between clips. The video (and potentially others) will be skipped."
  193. )
  194. idxs: Union[List[slice], torch.Tensor]
  195. if isinstance(_idxs, slice):
  196. idxs = [_idxs] * len(clips)
  197. else:
  198. idxs = unfold(_idxs, num_frames, step)
  199. return clips, idxs
  200. def compute_clips(self, num_frames: int, step: int, frame_rate: Optional[int] = None) -> None:
  201. """
  202. Compute all consecutive sequences of clips from video_pts.
  203. Always returns clips of size `num_frames`, meaning that the
  204. last few frames in a video can potentially be dropped.
  205. Args:
  206. num_frames (int): number of frames for the clip
  207. step (int): distance between two clips
  208. frame_rate (int, optional): The frame rate
  209. """
  210. self.num_frames = num_frames
  211. self.step = step
  212. self.frame_rate = frame_rate
  213. self.clips = []
  214. self.resampling_idxs = []
  215. for video_pts, fps in zip(self.video_pts, self.video_fps):
  216. clips, idxs = self.compute_clips_for_video(video_pts, num_frames, step, fps, frame_rate)
  217. self.clips.append(clips)
  218. self.resampling_idxs.append(idxs)
  219. clip_lengths = torch.as_tensor([len(v) for v in self.clips])
  220. self.cumulative_sizes = clip_lengths.cumsum(0).tolist()
  221. def __len__(self) -> int:
  222. return self.num_clips()
  223. def num_videos(self) -> int:
  224. return len(self.video_paths)
  225. def num_clips(self) -> int:
  226. """
  227. Number of subclips that are available in the video list.
  228. """
  229. return self.cumulative_sizes[-1]
  230. def get_clip_location(self, idx: int) -> Tuple[int, int]:
  231. """
  232. Converts a flattened representation of the indices into a video_idx, clip_idx
  233. representation.
  234. """
  235. video_idx = bisect.bisect_right(self.cumulative_sizes, idx)
  236. if video_idx == 0:
  237. clip_idx = idx
  238. else:
  239. clip_idx = idx - self.cumulative_sizes[video_idx - 1]
  240. return video_idx, clip_idx
  241. @staticmethod
  242. def _resample_video_idx(num_frames: int, original_fps: int, new_fps: int) -> Union[slice, torch.Tensor]:
  243. step = float(original_fps) / new_fps
  244. if step.is_integer():
  245. # optimization: if step is integer, don't need to perform
  246. # advanced indexing
  247. step = int(step)
  248. return slice(None, None, step)
  249. idxs = torch.arange(num_frames, dtype=torch.float32) * step
  250. idxs = idxs.floor().to(torch.int64)
  251. return idxs
  252. def get_clip(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any], int]:
  253. """
  254. Gets a subclip from a list of videos.
  255. Args:
  256. idx (int): index of the subclip. Must be between 0 and num_clips().
  257. Returns:
  258. video (Tensor)
  259. audio (Tensor)
  260. info (Dict)
  261. video_idx (int): index of the video in `video_paths`
  262. """
  263. if idx >= self.num_clips():
  264. raise IndexError(f"Index {idx} out of range ({self.num_clips()} number of clips)")
  265. video_idx, clip_idx = self.get_clip_location(idx)
  266. video_path = self.video_paths[video_idx]
  267. clip_pts = self.clips[video_idx][clip_idx]
  268. from torchvision import get_video_backend
  269. backend = get_video_backend()
  270. if backend == "pyav":
  271. # check for invalid options
  272. if self._video_width != 0:
  273. raise ValueError("pyav backend doesn't support _video_width != 0")
  274. if self._video_height != 0:
  275. raise ValueError("pyav backend doesn't support _video_height != 0")
  276. if self._video_min_dimension != 0:
  277. raise ValueError("pyav backend doesn't support _video_min_dimension != 0")
  278. if self._video_max_dimension != 0:
  279. raise ValueError("pyav backend doesn't support _video_max_dimension != 0")
  280. if self._audio_samples != 0:
  281. raise ValueError("pyav backend doesn't support _audio_samples != 0")
  282. if backend == "pyav":
  283. start_pts = clip_pts[0].item()
  284. end_pts = clip_pts[-1].item()
  285. video, audio, info = read_video(video_path, start_pts, end_pts)
  286. else:
  287. _info = _probe_video_from_file(video_path)
  288. video_fps = _info.video_fps
  289. audio_fps = None
  290. video_start_pts = cast(int, clip_pts[0].item())
  291. video_end_pts = cast(int, clip_pts[-1].item())
  292. audio_start_pts, audio_end_pts = 0, -1
  293. audio_timebase = Fraction(0, 1)
  294. video_timebase = Fraction(_info.video_timebase.numerator, _info.video_timebase.denominator)
  295. if _info.has_audio:
  296. audio_timebase = Fraction(_info.audio_timebase.numerator, _info.audio_timebase.denominator)
  297. audio_start_pts = pts_convert(video_start_pts, video_timebase, audio_timebase, math.floor)
  298. audio_end_pts = pts_convert(video_end_pts, video_timebase, audio_timebase, math.ceil)
  299. audio_fps = _info.audio_sample_rate
  300. video, audio, _ = _read_video_from_file(
  301. video_path,
  302. video_width=self._video_width,
  303. video_height=self._video_height,
  304. video_min_dimension=self._video_min_dimension,
  305. video_max_dimension=self._video_max_dimension,
  306. video_pts_range=(video_start_pts, video_end_pts),
  307. video_timebase=video_timebase,
  308. audio_samples=self._audio_samples,
  309. audio_channels=self._audio_channels,
  310. audio_pts_range=(audio_start_pts, audio_end_pts),
  311. audio_timebase=audio_timebase,
  312. )
  313. info = {"video_fps": video_fps}
  314. if audio_fps is not None:
  315. info["audio_fps"] = audio_fps
  316. if self.frame_rate is not None:
  317. resampling_idx = self.resampling_idxs[video_idx][clip_idx]
  318. if isinstance(resampling_idx, torch.Tensor):
  319. resampling_idx = resampling_idx - resampling_idx[0]
  320. video = video[resampling_idx]
  321. info["video_fps"] = self.frame_rate
  322. assert len(video) == self.num_frames, f"{video.shape} x {self.num_frames}"
  323. if self.output_format == "TCHW":
  324. # [T,H,W,C] --> [T,C,H,W]
  325. video = video.permute(0, 3, 1, 2)
  326. return video, audio, info, video_idx
  327. def __getstate__(self) -> Dict[str, Any]:
  328. video_pts_sizes = [len(v) for v in self.video_pts]
  329. # To be back-compatible, we convert data to dtype torch.long as needed
  330. # because for empty list, in legacy implementation, torch.as_tensor will
  331. # use torch.float as default dtype. This happens when decoding fails and
  332. # no pts is returned in the list.
  333. video_pts = [x.to(torch.int64) for x in self.video_pts]
  334. # video_pts can be an empty list if no frames have been decoded
  335. if video_pts:
  336. video_pts = torch.cat(video_pts) # type: ignore[assignment]
  337. # avoid bug in https://github.com/pytorch/pytorch/issues/32351
  338. # TODO: Revert it once the bug is fixed.
  339. video_pts = video_pts.numpy() # type: ignore[attr-defined]
  340. # make a copy of the fields of self
  341. d = self.__dict__.copy()
  342. d["video_pts_sizes"] = video_pts_sizes
  343. d["video_pts"] = video_pts
  344. # delete the following attributes to reduce the size of dictionary. They
  345. # will be re-computed in "__setstate__()"
  346. del d["clips"]
  347. del d["resampling_idxs"]
  348. del d["cumulative_sizes"]
  349. # for backwards-compatibility
  350. d["_version"] = 2
  351. return d
  352. def __setstate__(self, d: Dict[str, Any]) -> None:
  353. # for backwards-compatibility
  354. if "_version" not in d:
  355. self.__dict__ = d
  356. return
  357. video_pts = torch.as_tensor(d["video_pts"], dtype=torch.int64)
  358. video_pts = torch.split(video_pts, d["video_pts_sizes"], dim=0)
  359. # don't need this info anymore
  360. del d["video_pts_sizes"]
  361. d["video_pts"] = video_pts
  362. self.__dict__ = d
  363. # recompute attributes "clips", "resampling_idxs" and other derivative ones
  364. self.compute_clips(self.num_frames, self.step, self.frame_rate)