test_io.py 12.2 KB
Newer Older
1
import contextlib
2
import os
3
import sys
4
5
import tempfile

6
7
8
import pytest
import torch
import torchvision.io as io
9
from common_utils import assert_equal
10
from torchvision import get_video_backend
11

12
13
14

try:
    import av
15

16
17
    # Do a version test too
    io.video._check_av_available()
18
19
20
21
except ImportError:
    av = None


22
23
24
VIDEO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "videos")


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def _create_video_frames(num_frames, height, width):
    y, x = torch.meshgrid(torch.linspace(-2, 2, height), torch.linspace(-2, 2, width))
    data = []
    for i in range(num_frames):
        xc = float(i) / num_frames
        yc = 1 - float(i) / (2 * num_frames)
        d = torch.exp(-((x - xc) ** 2 + (y - yc) ** 2) / 2) * 255
        data.append(d.unsqueeze(2).repeat(1, 1, 3).byte())

    return torch.stack(data, 0)


@contextlib.contextmanager
def temp_video(num_frames, height, width, fps, lossless=False, video_codec=None, options=None):
    if lossless:
40
41
42
43
        if video_codec is not None:
            raise ValueError("video_codec can't be specified together with lossless")
        if options is not None:
            raise ValueError("options can't be specified together with lossless")
44
45
        video_codec = "libx264rgb"
        options = {"crf": "0"}
46
47

    if video_codec is None:
Francisco Massa's avatar
Francisco Massa committed
48
        if get_video_backend() == "pyav":
49
            video_codec = "libx264"
50
51
52
        else:
            # when video_codec is not set, we assume it is libx264rgb which accepts
            # RGB pixel formats as input instead of YUV
53
            video_codec = "libx264rgb"
54
55
56
57
    if options is None:
        options = {}

    data = _create_video_frames(num_frames, height, width)
58
    with tempfile.NamedTemporaryFile(suffix=".mp4") as f:
59
        f.close()
60
61
        io.write_video(f.name, data, fps=fps, video_codec=video_codec, options=options)
        yield f.name, data
62
    os.unlink(f.name)
63

Francisco Massa's avatar
Francisco Massa committed
64

65
66
67
@pytest.mark.skipif(
    get_video_backend() != "pyav" and not io._HAS_VIDEO_OPT, reason="video_reader backend not available"
)
68
69
@pytest.mark.skipif(av is None, reason="PyAV unavailable")
class TestVideo:
70
71
72
73
74
    # compression adds artifacts, thus we add a tolerance of
    # 6 in 0-255 range
    TOLERANCE = 6

    def test_write_read_video(self):
75
        with temp_video(10, 300, 300, 5, lossless=True) as (f_name, data):
Francisco Massa's avatar
Francisco Massa committed
76
            lv, _, info = io.read_video(f_name)
77
            assert_equal(data, lv)
78
            assert info["video_fps"] == 5
79

80
    @pytest.mark.skipif(not io._HAS_VIDEO_OPT, reason="video_reader backend is not chosen")
81
82
83
    def test_probe_video_from_file(self):
        with temp_video(10, 300, 300, 5) as (f_name, data):
            video_info = io._probe_video_from_file(f_name)
84
85
            assert pytest.approx(2, rel=0.0, abs=0.1) == video_info.video_duration
            assert pytest.approx(5, rel=0.0, abs=0.1) == video_info.video_fps
86

87
    @pytest.mark.skipif(not io._HAS_VIDEO_OPT, reason="video_reader backend is not chosen")
88
89
90
91
92
    def test_probe_video_from_memory(self):
        with temp_video(10, 300, 300, 5) as (f_name, data):
            with open(f_name, "rb") as fp:
                filebuffer = fp.read()
            video_info = io._probe_video_from_memory(filebuffer)
93
94
            assert pytest.approx(2, rel=0.0, abs=0.1) == video_info.video_duration
            assert pytest.approx(5, rel=0.0, abs=0.1) == video_info.video_fps
95

96
    def test_read_timestamps(self):
97
        with temp_video(10, 300, 300, 5) as (f_name, data):
Francisco Massa's avatar
Francisco Massa committed
98
            pts, _ = io.read_video_timestamps(f_name)
99
100
101
            # note: not all formats/codecs provide accurate information for computing the
            # timestamps. For the format that we use here, this information is available,
            # so we use it as a baseline
102
103
104
105
106
            with av.open(f_name) as container:
                stream = container.streams[0]
                pts_step = int(round(float(1 / (stream.average_rate * stream.time_base))))
                num_frames = int(round(float(stream.average_rate * stream.time_base * stream.duration)))
                expected_pts = [i * pts_step for i in range(num_frames)]
107

108
            assert pts == expected_pts
109

110
111
    @pytest.mark.parametrize("start", range(5))
    @pytest.mark.parametrize("offset", range(1, 4))
112
    def test_read_partial_video(self, start, offset):
113
        with temp_video(10, 300, 300, 5, lossless=True) as (f_name, data):
Francisco Massa's avatar
Francisco Massa committed
114
            pts, _ = io.read_video_timestamps(f_name)
115
116

            lv, _, _ = io.read_video(f_name, pts[start], pts[start + offset - 1])
117
            s_data = data[start : (start + offset)]
118
119
            assert len(lv) == offset
            assert_equal(s_data, lv)
120

Francisco Massa's avatar
Francisco Massa committed
121
            if get_video_backend() == "pyav":
122
123
                # for "video_reader" backend, we don't decode the closest early frame
                # when the given start pts is not matching any frame pts
Francisco Massa's avatar
Francisco Massa committed
124
                lv, _, _ = io.read_video(f_name, pts[4] + 1, pts[7])
125
                assert len(lv) == 4
126
                assert_equal(data[4:8], lv)
127

128
129
    @pytest.mark.parametrize("start", range(0, 80, 20))
    @pytest.mark.parametrize("offset", range(1, 4))
130
    def test_read_partial_video_bframes(self, start, offset):
131
        # do not use lossless encoding, to test the presence of B-frames
132
        options = {"bframes": "16", "keyint": "10", "min-keyint": "4"}
133
        with temp_video(100, 300, 300, 5, options=options) as (f_name, data):
Francisco Massa's avatar
Francisco Massa committed
134
            pts, _ = io.read_video_timestamps(f_name)
135
136

            lv, _, _ = io.read_video(f_name, pts[start], pts[start + offset - 1])
137
            s_data = data[start : (start + offset)]
138
139
            assert len(lv) == offset
            assert_equal(s_data, lv, rtol=0.0, atol=self.TOLERANCE)
140

141
            lv, _, _ = io.read_video(f_name, pts[4] + 1, pts[7])
Francisco Massa's avatar
Francisco Massa committed
142
            # TODO fix this
143
            if get_video_backend() == "pyav":
144
                assert len(lv) == 4
145
                assert_equal(data[4:8], lv, rtol=0.0, atol=self.TOLERANCE)
Francisco Massa's avatar
Francisco Massa committed
146
            else:
147
                assert len(lv) == 3
148
                assert_equal(data[5:8], lv, rtol=0.0, atol=self.TOLERANCE)
149

150
    def test_read_packed_b_frames_divx_file(self):
151
152
153
154
        name = "hmdb51_Turnk_r_Pippi_Michel_cartwheel_f_cm_np2_le_med_6.avi"
        f_name = os.path.join(VIDEO_DIR, name)
        pts, fps = io.read_video_timestamps(f_name)

155
156
        assert pts == sorted(pts)
        assert fps == 30
157

158
    def test_read_timestamps_from_packet(self):
159
        with temp_video(10, 300, 300, 5, video_codec="mpeg4") as (f_name, data):
Francisco Massa's avatar
Francisco Massa committed
160
            pts, _ = io.read_video_timestamps(f_name)
161
162
163
            # note: not all formats/codecs provide accurate information for computing the
            # timestamps. For the format that we use here, this information is available,
            # so we use it as a baseline
164
165
166
            with av.open(f_name) as container:
                stream = container.streams[0]
                # make sure we went through the optimized codepath
167
                assert b"Lavc" in stream.codec_context.extradata
168
169
170
                pts_step = int(round(float(1 / (stream.average_rate * stream.time_base))))
                num_frames = int(round(float(stream.average_rate * stream.time_base * stream.duration)))
                expected_pts = [i * pts_step for i in range(num_frames)]
171

172
            assert pts == expected_pts
173

174
175
    def test_read_video_pts_unit_sec(self):
        with temp_video(10, 300, 300, 5, lossless=True) as (f_name, data):
176
            lv, _, info = io.read_video(f_name, pts_unit="sec")
177

178
            assert_equal(data, lv)
179
180
            assert info["video_fps"] == 5
            assert info == {"video_fps": 5}
181
182
183

    def test_read_timestamps_pts_unit_sec(self):
        with temp_video(10, 300, 300, 5) as (f_name, data):
184
            pts, _ = io.read_video_timestamps(f_name, pts_unit="sec")
185

186
187
188
189
190
            with av.open(f_name) as container:
                stream = container.streams[0]
                pts_step = int(round(float(1 / (stream.average_rate * stream.time_base))))
                num_frames = int(round(float(stream.average_rate * stream.time_base * stream.duration)))
                expected_pts = [i * pts_step * stream.time_base for i in range(num_frames)]
191

192
            assert pts == expected_pts
193

194
195
    @pytest.mark.parametrize("start", range(5))
    @pytest.mark.parametrize("offset", range(1, 4))
196
    def test_read_partial_video_pts_unit_sec(self, start, offset):
197
        with temp_video(10, 300, 300, 5, lossless=True) as (f_name, data):
198
            pts, _ = io.read_video_timestamps(f_name, pts_unit="sec")
199

200
201
            lv, _, _ = io.read_video(f_name, pts[start], pts[start + offset - 1], pts_unit="sec")
            s_data = data[start : (start + offset)]
202
203
204
205
206
            assert len(lv) == offset
            assert_equal(s_data, lv)

            with av.open(f_name) as container:
                stream = container.streams[0]
207
208
209
                lv, _, _ = io.read_video(
                    f_name, int(pts[4] * (1.0 / stream.time_base) + 1) * stream.time_base, pts[7], pts_unit="sec"
                )
Francisco Massa's avatar
Francisco Massa committed
210
211
212
            if get_video_backend() == "pyav":
                # for "video_reader" backend, we don't decode the closest early frame
                # when the given start pts is not matching any frame pts
213
                assert len(lv) == 4
214
                assert_equal(data[4:8], lv)
215

216
    def test_read_video_corrupted_file(self):
217
218
        with tempfile.NamedTemporaryFile(suffix=".mp4") as f:
            f.write(b"This is not an mpg4 file")
219
            video, audio, info = io.read_video(f.name)
220
221
222
223
224
            assert isinstance(video, torch.Tensor)
            assert isinstance(audio, torch.Tensor)
            assert video.numel() == 0
            assert audio.numel() == 0
            assert info == {}
225
226

    def test_read_video_timestamps_corrupted_file(self):
227
228
        with tempfile.NamedTemporaryFile(suffix=".mp4") as f:
            f.write(b"This is not an mpg4 file")
229
            video_pts, video_fps = io.read_video_timestamps(f.name)
230
231
            assert video_pts == []
            assert video_fps is None
232

233
    @pytest.mark.skip(reason="Temporarily disabled due to new pyav")
234
235
    def test_read_video_partially_corrupted_file(self):
        with temp_video(5, 4, 4, 5, lossless=True) as (f_name, data):
236
            with open(f_name, "r+b") as f:
237
238
239
240
241
                size = os.path.getsize(f_name)
                bytes_to_overwrite = size // 10
                # seek to the middle of the file
                f.seek(5 * bytes_to_overwrite)
                # corrupt 10% of the file from the middle
242
                f.write(b"\xff" * bytes_to_overwrite)
243
            # this exercises the container.decode assertion check
244
            video, audio, info = io.read_video(f.name, pts_unit="sec")
245
            # check that size is not equal to 5, but 3
Francisco Massa's avatar
Francisco Massa committed
246
            # TODO fix this
247
            if get_video_backend() == "pyav":
248
                assert len(video) == 3
Francisco Massa's avatar
Francisco Massa committed
249
            else:
250
                assert len(video) == 4
251
            # but the valid decoded content is still correct
252
            assert_equal(video[:3], data[:3])
253
            # and the last few frames are wrong
254
            with pytest.raises(AssertionError):
255
                assert_equal(video, data)
256

257
    @pytest.mark.skipif(sys.platform == "win32", reason="temporarily disabled on Windows")
258
    def test_write_video_with_audio(self, tmpdir):
259
260
261
        f_name = os.path.join(VIDEO_DIR, "R6llTwEh07w.mp4")
        video_tensor, audio_tensor, info = io.read_video(f_name, pts_unit="sec")

262
263
264
265
266
267
        out_f_name = os.path.join(tmpdir, "testing.mp4")
        io.video.write_video(
            out_f_name,
            video_tensor,
            round(info["video_fps"]),
            video_codec="libx264rgb",
268
            options={"crf": "0"},
269
270
271
272
273
            audio_array=audio_tensor,
            audio_fps=info["audio_fps"],
            audio_codec="aac",
        )

274
        out_video_tensor, out_audio_tensor, out_info = io.read_video(out_f_name, pts_unit="sec")
275
276
277
278
279
280
281
282
283
284
285

        assert info["video_fps"] == out_info["video_fps"]
        assert_equal(video_tensor, out_video_tensor)

        audio_stream = av.open(f_name).streams.audio[0]
        out_audio_stream = av.open(out_f_name).streams.audio[0]

        assert info["audio_fps"] == out_info["audio_fps"]
        assert audio_stream.rate == out_audio_stream.rate
        assert pytest.approx(out_audio_stream.frames, rel=0.0, abs=1) == audio_stream.frames
        assert audio_stream.frame_size == out_audio_stream.frame_size
286

287
288
289
    # TODO add tests for audio


290
if __name__ == "__main__":
291
    pytest.main(__file__)