video_utils.py 15 KB

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