video_utils.py 12.9 KB
Newer Older
1
2
import bisect
import math
3
4
from fractions import Fraction

5
import torch
6
from torchvision.io import (
7
    _probe_video_from_file,
8
    _read_video_from_file,
9
10
11
    _read_video_timestamps_from_file,
    read_video,
    read_video_timestamps,
12
)
13

14
15
from .utils import tqdm

16

17
18
19
20
21
22
23
24
25
26
27
28
def pts_convert(pts, timebase_from, timebase_to, round_func=math.floor):
    """convert pts between different time bases
    Args:
        pts: presentation timestamp, float
        timebase_from: original timebase. Fraction
        timebase_to: new timebase. Fraction
        round_func: rounding function.
    """
    new_pts = Fraction(pts, 1) * timebase_from / timebase_to
    return round_func(new_pts)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def unfold(tensor, size, step, dilation=1):
    """
    similar to tensor.unfold, but with the dilation
    and specialized for 1d tensors

    Returns all consecutive windows of `size` elements, with
    `step` between windows. The distance between each element
    in a window is given by `dilation`.
    """
    assert tensor.dim() == 1
    o_stride = tensor.stride(0)
    numel = tensor.numel()
    new_stride = (step * o_stride, dilation * o_stride)
    new_size = ((numel - (dilation * (size - 1) + 1)) // step + 1, size)
    if new_size[0] < 1:
        new_size = (0, size)
    return torch.as_strided(tensor, new_size, new_stride)


48
49
50
51
52
class _DummyDataset(object):
    """
    Dummy dataset used for DataLoader in VideoClips.
    Defined at top level so it can be pickled when forking.
    """
53

54
55
56
57
58
59
60
61
62
63
    def __init__(self, x):
        self.x = x

    def __len__(self):
        return len(self.x)

    def __getitem__(self, idx):
        return read_video_timestamps(self.x[idx])


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class VideoClips(object):
    """
    Given a list of video files, computes all consecutive subvideos of size
    `clip_length_in_frames`, where the distance between each subvideo in the
    same video is defined by `frames_between_clips`.
    If `frame_rate` is specified, it will also resample all the videos to have
    the same frame rate, and the clips will refer to this frame rate.

    Creating this instance the first time is time-consuming, as it needs to
    decode all the videos in `video_paths`. It is recommended that you
    cache the results after instantiation of the class.

    Recreating the clips for different clip lengths is fast, and can be done
    with the `compute_clips` method.

    Arguments:
        video_paths (List[str]): paths to the video files
        clip_length_in_frames (int): size of a clip in number of frames
        frames_between_clips (int): step (in frames) between each clip
        frame_rate (int, optional): if specified, it will resample the video
            so that it has `frame_rate`, and then the clips will be defined
            on the resampled video
ekosman's avatar
ekosman committed
86
87
        num_workers (int): how many subprocesses to use for data loading.
            0 means that the data will be loaded in the main process. (default: 0)
88
    """
89
90
91
92
93
94
95
96
97
98
99
100

    def __init__(
        self,
        video_paths,
        clip_length_in_frames=16,
        frames_between_clips=1,
        frame_rate=None,
        _precomputed_metadata=None,
        num_workers=0,
        _video_width=0,
        _video_height=0,
        _video_min_dimension=0,
101
        _video_max_dimension=0,
102
103
104
        _audio_samples=0,
        _audio_channels=0,
    ):
105

106
        self.video_paths = video_paths
107
        self.num_workers = num_workers
108
109

        # these options are not valid for pyav backend
110
111
112
        self._video_width = _video_width
        self._video_height = _video_height
        self._video_min_dimension = _video_min_dimension
113
        self._video_max_dimension = _video_max_dimension
114
        self._audio_samples = _audio_samples
115
        self._audio_channels = _audio_channels
ekosman's avatar
ekosman committed
116

117
118
119
120
        if _precomputed_metadata is None:
            self._compute_frame_pts()
        else:
            self._init_from_metadata(_precomputed_metadata)
121
122
        self.compute_clips(clip_length_in_frames, frames_between_clips, frame_rate)

123
124
125
    def _collate_fn(self, x):
        return x

126
127
    def _compute_frame_pts(self):
        self.video_pts = []
128
        self.video_fps = []
129
130
131
132

        # strategy: use a DataLoader to parallelize read_video_timestamps
        # so need to create a dummy dataset first
        import torch.utils.data
133

134
        dl = torch.utils.data.DataLoader(
135
            _DummyDataset(self.video_paths),
136
            batch_size=16,
137
            num_workers=self.num_workers,
138
139
            collate_fn=self._collate_fn,
        )
140
141
142
143

        with tqdm(total=len(dl)) as pbar:
            for batch in dl:
                pbar.update(1)
144
145
146
147
                clips, fps = list(zip(*batch))
                clips = [torch.as_tensor(c) for c in clips]
                self.video_pts.extend(clips)
                self.video_fps.extend(fps)
148

149
    def _init_from_metadata(self, metadata):
150
        self.video_paths = metadata["video_paths"]
151
152
        assert len(self.video_paths) == len(metadata["video_pts"])
        self.video_pts = metadata["video_pts"]
153
154
        assert len(self.video_paths) == len(metadata["video_fps"])
        self.video_fps = metadata["video_fps"]
155
156
157
158
159
160

    @property
    def metadata(self):
        _metadata = {
            "video_paths": self.video_paths,
            "video_pts": self.video_pts,
161
            "video_fps": self.video_fps,
162
        }
163
        return _metadata
164
165
166
167

    def subset(self, indices):
        video_paths = [self.video_paths[i] for i in indices]
        video_pts = [self.video_pts[i] for i in indices]
168
        video_fps = [self.video_fps[i] for i in indices]
169
        metadata = {
170
            "video_paths": video_paths,
171
            "video_pts": video_pts,
172
            "video_fps": video_fps,
173
        }
174
175
176
177
178
179
180
181
182
183
        return type(self)(
            video_paths,
            self.num_frames,
            self.step,
            self.frame_rate,
            _precomputed_metadata=metadata,
            num_workers=self.num_workers,
            _video_width=self._video_width,
            _video_height=self._video_height,
            _video_min_dimension=self._video_min_dimension,
184
            _video_max_dimension=self._video_max_dimension,
185
186
187
            _audio_samples=self._audio_samples,
            _audio_channels=self._audio_channels,
        )
188

189
190
    @staticmethod
    def compute_clips_for_video(video_pts, num_frames, step, fps, frame_rate):
191
192
193
194
        if fps is None:
            # if for some reason the video doesn't have fps (because doesn't have a video stream)
            # set the fps to 1. The value doesn't matter, because video_pts is empty anyway
            fps = 1
195
196
197
        if frame_rate is None:
            frame_rate = fps
        total_frames = len(video_pts) * (float(frame_rate) / fps)
198
199
200
        idxs = VideoClips._resample_video_idx(
            int(math.floor(total_frames)), fps, frame_rate
        )
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        video_pts = video_pts[idxs]
        clips = unfold(video_pts, num_frames, step)
        if isinstance(idxs, slice):
            idxs = [idxs] * len(clips)
        else:
            idxs = unfold(idxs, num_frames, step)
        return clips, idxs

    def compute_clips(self, num_frames, step, frame_rate=None):
        """
        Compute all consecutive sequences of clips from video_pts.
        Always returns clips of size `num_frames`, meaning that the
        last few frames in a video can potentially be dropped.

        Arguments:
            num_frames (int): number of frames for the clip
            step (int): distance between two clips
        """
        self.num_frames = num_frames
        self.step = step
        self.frame_rate = frame_rate
        self.clips = []
        self.resampling_idxs = []
224
        for video_pts, fps in zip(self.video_pts, self.video_fps):
225
226
227
            clips, idxs = self.compute_clips_for_video(
                video_pts, num_frames, step, fps, frame_rate
            )
228
229
            self.clips.append(clips)
            self.resampling_idxs.append(idxs)
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
        clip_lengths = torch.as_tensor([len(v) for v in self.clips])
        self.cumulative_sizes = clip_lengths.cumsum(0).tolist()

    def __len__(self):
        return self.num_clips()

    def num_videos(self):
        return len(self.video_paths)

    def num_clips(self):
        """
        Number of subclips that are available in the video list.
        """
        return self.cumulative_sizes[-1]

    def get_clip_location(self, idx):
        """
        Converts a flattened representation of the indices into a video_idx, clip_idx
        representation.
        """
        video_idx = bisect.bisect_right(self.cumulative_sizes, idx)
        if video_idx == 0:
            clip_idx = idx
        else:
            clip_idx = idx - self.cumulative_sizes[video_idx - 1]
        return video_idx, clip_idx

    @staticmethod
    def _resample_video_idx(num_frames, original_fps, new_fps):
        step = float(original_fps) / new_fps
        if step.is_integer():
            # optimization: if step is integer, don't need to perform
            # advanced indexing
            step = int(step)
            return slice(None, None, step)
        idxs = torch.arange(num_frames, dtype=torch.float32) * step
        idxs = idxs.floor().to(torch.int64)
        return idxs

    def get_clip(self, idx):
        """
        Gets a subclip from a list of videos.

        Arguments:
            idx (int): index of the subclip. Must be between 0 and num_clips().

        Returns:
            video (Tensor)
            audio (Tensor)
            info (Dict)
            video_idx (int): index of the video in `video_paths`
        """
        if idx >= self.num_clips():
283
284
285
286
            raise IndexError(
                "Index {} out of range "
                "({} number of clips)".format(idx, self.num_clips())
            )
287
288
289
        video_idx, clip_idx = self.get_clip_location(idx)
        video_path = self.video_paths[video_idx]
        clip_pts = self.clips[video_idx][clip_idx]
290

291
        from torchvision import get_video_backend
292

293
294
295
296
297
298
299
300
301
        backend = get_video_backend()

        if backend == "pyav":
            # check for invalid options
            if self._video_width != 0:
                raise ValueError("pyav backend doesn't support _video_width != 0")
            if self._video_height != 0:
                raise ValueError("pyav backend doesn't support _video_height != 0")
            if self._video_min_dimension != 0:
302
303
304
                raise ValueError(
                    "pyav backend doesn't support _video_min_dimension != 0"
                )
305
306
307
308
            if self._video_max_dimension != 0:
                raise ValueError(
                    "pyav backend doesn't support _video_max_dimension != 0"
                )
309
310
311
312
            if self._audio_samples != 0:
                raise ValueError("pyav backend doesn't support _audio_samples != 0")

        if backend == "pyav":
313
314
315
316
            start_pts = clip_pts[0].item()
            end_pts = clip_pts[-1].item()
            video, audio, info = read_video(video_path, start_pts, end_pts)
        else:
317
            info = _probe_video_from_file(video_path)
318
            video_fps = info.video_fps
319
            audio_fps = None
320
321
322
323
324
325

            video_start_pts = clip_pts[0].item()
            video_end_pts = clip_pts[-1].item()

            audio_start_pts, audio_end_pts = 0, -1
            audio_timebase = Fraction(0, 1)
326
327
328
329
330
331
332
            video_timebase = Fraction(
                info.video_timebase.numerator, info.video_timebase.denominator
            )
            if info.has_audio:
                audio_timebase = Fraction(
                    info.audio_timebase.numerator, info.audio_timebase.denominator
                )
333
                audio_start_pts = pts_convert(
334
                    video_start_pts, video_timebase, audio_timebase, math.floor
335
336
                )
                audio_end_pts = pts_convert(
337
                    video_end_pts, video_timebase, audio_timebase, math.ceil
338
                )
339
                audio_fps = info.audio_sample_rate
340
341
            video, audio, info = _read_video_from_file(
                video_path,
342
343
344
                video_width=self._video_width,
                video_height=self._video_height,
                video_min_dimension=self._video_min_dimension,
345
                video_max_dimension=self._video_max_dimension,
346
                video_pts_range=(video_start_pts, video_end_pts),
347
                video_timebase=video_timebase,
348
                audio_samples=self._audio_samples,
349
                audio_channels=self._audio_channels,
350
351
352
                audio_pts_range=(audio_start_pts, audio_end_pts),
                audio_timebase=audio_timebase,
            )
353
354
355
356
357

            info = {"video_fps": video_fps}
            if audio_fps is not None:
                info["audio_fps"] = audio_fps

358
359
360
361
362
363
        if self.frame_rate is not None:
            resampling_idx = self.resampling_idxs[video_idx][clip_idx]
            if isinstance(resampling_idx, torch.Tensor):
                resampling_idx = resampling_idx - resampling_idx[0]
            video = video[resampling_idx]
            info["video_fps"] = self.frame_rate
364
365
366
        assert len(video) == self.num_frames, "{} x {}".format(
            video.shape, self.num_frames
        )
367
        return video, audio, info, video_idx