Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

video.py 18 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
  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. 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
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...