forked from meta-pytorch/torchcodec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_encoders.py
More file actions
2021 lines (1809 loc) · 77.9 KB
/
Copy pathtest_encoders.py
File metadata and controls
2021 lines (1809 loc) · 77.9 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import json
import os
import platform
import re
import subprocess
import sys
from functools import partial
from pathlib import Path
import pytest
import torch
from torchcodec import ffmpeg_major_version
from torchcodec.decoders import AudioDecoder, VideoDecoder
from torchcodec.encoders import AudioEncoder, VideoEncoder
from torchcodec.encoders._multi_stream_encoder import StreamingEncoder
from .utils import (
assert_tensor_close_on_at_least,
get_ffmpeg_minor_version,
in_fbcode,
IN_GITHUB_CI,
IS_WINDOWS,
NASA_AUDIO_MP3,
NASA_AUDIO_MP3_44100,
NASA_VIDEO,
needs_ffmpeg_cli,
psnr,
SINE_MONO_S32,
TEST_SRC_2_720P,
TestContainerFile,
)
IS_WINDOWS_WITH_FFMPEG_LE_70 = IS_WINDOWS and (
ffmpeg_major_version < 7
or (ffmpeg_major_version == 7 and get_ffmpeg_minor_version() == 0)
)
@pytest.fixture
def with_ffmpeg_debug_logs():
# Fixture that sets the ffmpeg logs to DEBUG mode
previous_log_level = os.environ.get("TORCHCODEC_FFMPEG_LOG_LEVEL", "QUIET")
os.environ["TORCHCODEC_FFMPEG_LOG_LEVEL"] = "DEBUG"
yield
os.environ["TORCHCODEC_FFMPEG_LOG_LEVEL"] = previous_log_level
def validate_frames_properties(*, actual: Path, expected: Path):
# actual and expected are files containing encoded audio data. We call
# `ffprobe` on both, and assert that the frame properties match (pts,
# duration, etc.)
# non-exhaustive list of the props we want to test for:
required_props = (
"pts",
"pts_time",
"sample_fmt",
"nb_samples",
"channels",
"duration",
"duration_time",
)
show_entries = "frame=" + ",".join(required_props)
frames_actual, frames_expected = (
json.loads(
subprocess.run(
[
"ffprobe",
"-v",
"error",
"-hide_banner",
"-select_streams",
"a:0",
"-show_frames",
"-show_entries",
show_entries,
"-of",
"json",
f"{f}",
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
).stdout
)["frames"]
for f in (actual, expected)
)
# frames_actual and frames_expected are both a list of dicts, each dict
# corresponds to a frame and each key-value pair corresponds to a frame
# property like pts, nb_samples, etc., similar to the AVFrame fields.
assert isinstance(frames_actual, list)
assert all(isinstance(d, dict) for d in frames_actual)
assert len(frames_actual) > 3 # arbitrary sanity check
assert len(frames_actual) == len(frames_expected)
for frame_index, (d_actual, d_expected) in enumerate(
zip(frames_actual, frames_expected)
):
if ffmpeg_major_version >= 6:
assert all(required_prop in d_expected for required_prop in required_props)
for prop in d_expected:
if prop == "pkt_pos":
# pkt_pos is the position of the packet *in bytes* in its
# stream. We don't always match FFmpeg exactly on this,
# typically on compressed formats like mp3. It's probably
# because we are not writing the exact same headers, or
# something like this. In any case, this doesn't seem to be
# critical.
continue
assert (
d_actual[prop] == d_expected[prop]
), f"\nComparing: {actual}\nagainst reference: {expected},\nthe {prop} property is different at frame {frame_index}:"
class TestAudioEncoder:
def decode(self, source) -> torch.Tensor:
if isinstance(source, TestContainerFile):
source = str(source.path)
return AudioDecoder(source).get_all_samples()
def test_bad_input(self):
with pytest.raises(ValueError, match="Expected samples to be a Tensor"):
AudioEncoder(samples=123, sample_rate=32_000)
with pytest.raises(ValueError, match="Expected 1D or 2D samples"):
AudioEncoder(samples=torch.rand(3, 4, 5), sample_rate=32_000)
with pytest.raises(ValueError, match="Expected float32 samples"):
AudioEncoder(
samples=torch.rand(10, 10, dtype=torch.float64), sample_rate=32_000
)
with pytest.raises(ValueError, match="sample_rate = 0 must be > 0"):
AudioEncoder(samples=torch.rand(10, 10), sample_rate=0)
encoder = AudioEncoder(samples=torch.rand(2, 100), sample_rate=32_000)
bad_path = "/bad/path.mp3"
with pytest.raises(
RuntimeError,
match=f"avio_open failed. The destination file is {bad_path}, make sure it's a valid path",
):
encoder.to_file(dest=bad_path)
bad_extension = "output.bad_extension"
with pytest.raises(RuntimeError, match="check the desired extension"):
encoder.to_file(dest=bad_extension)
bad_format = "bad_format"
with pytest.raises(
RuntimeError,
match=re.escape(f"Check the desired format? Got format={bad_format}"),
):
encoder.to_tensor(format=bad_format)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_bad_input_parametrized(self, method, tmp_path):
if method == "to_file":
valid_params = dict(dest=str(tmp_path / "output.mp3"))
elif method == "to_tensor":
valid_params = dict(format="mp3")
elif method == "to_file_like":
valid_params = dict(file_like=io.BytesIO(), format="mp3")
else:
raise ValueError(f"Unknown method: {method}")
decoder = AudioEncoder(self.decode(NASA_AUDIO_MP3).data, sample_rate=10)
avcodec_open2_failed_msg = "avcodec_open2 failed: Invalid argument"
with pytest.raises(
RuntimeError,
match=(
avcodec_open2_failed_msg
if IS_WINDOWS_WITH_FFMPEG_LE_70
else "invalid sample rate=10"
),
):
getattr(decoder, method)(**valid_params)
decoder = AudioEncoder(
self.decode(NASA_AUDIO_MP3).data, sample_rate=NASA_AUDIO_MP3.sample_rate
)
with pytest.raises(
RuntimeError,
match=(
avcodec_open2_failed_msg
if IS_WINDOWS_WITH_FFMPEG_LE_70
else "invalid sample rate=10"
),
):
getattr(decoder, method)(sample_rate=10, **valid_params)
with pytest.raises(
RuntimeError,
match=(
avcodec_open2_failed_msg
if IS_WINDOWS_WITH_FFMPEG_LE_70
else "invalid sample rate=99999999"
),
):
getattr(decoder, method)(sample_rate=99999999, **valid_params)
with pytest.raises(RuntimeError, match="bit_rate=-1 must be >= 0"):
getattr(decoder, method)(**valid_params, bit_rate=-1)
bad_num_channels = 10
decoder = AudioEncoder(torch.rand(bad_num_channels, 20), sample_rate=16_000)
with pytest.raises(
RuntimeError, match=f"Trying to encode {bad_num_channels} channels"
):
getattr(decoder, method)(**valid_params)
decoder = AudioEncoder(
self.decode(NASA_AUDIO_MP3).data, sample_rate=NASA_AUDIO_MP3.sample_rate
)
for num_channels in (0, 3):
match = (
avcodec_open2_failed_msg
if IS_WINDOWS_WITH_FFMPEG_LE_70
else re.escape(
f"Desired number of channels ({num_channels}) is not supported"
)
)
with pytest.raises(RuntimeError, match=match):
getattr(decoder, method)(**valid_params, num_channels=num_channels)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
@pytest.mark.parametrize(
"format",
[
pytest.param(
"wav",
marks=pytest.mark.skipif(
ffmpeg_major_version == 4,
reason="Swresample with FFmpeg 4 doesn't work on wav files",
),
),
"flac",
],
)
def test_round_trip(self, method, format, tmp_path):
# Check that decode(encode(samples)) == samples on lossless formats
asset = NASA_AUDIO_MP3
source_samples = self.decode(asset).data
encoder = AudioEncoder(source_samples, sample_rate=asset.sample_rate)
if method == "to_file":
encoded_path = str(tmp_path / f"output.{format}")
encoded_source = encoded_path
encoder.to_file(dest=encoded_path)
elif method == "to_tensor":
encoded_source = encoder.to_tensor(format=format)
assert encoded_source.dtype == torch.uint8
assert encoded_source.ndim == 1
elif method == "to_file_like":
file_like = io.BytesIO()
encoder.to_file_like(file_like, format=format)
encoded_source = file_like.getvalue()
else:
raise ValueError(f"Unknown method: {method}")
rtol, atol = (0, 1e-4) if format == "wav" else (None, None)
torch.testing.assert_close(
self.decode(encoded_source).data, source_samples, rtol=rtol, atol=atol
)
@needs_ffmpeg_cli
@pytest.mark.parametrize("asset", (NASA_AUDIO_MP3, SINE_MONO_S32))
@pytest.mark.parametrize("bit_rate", (None, 0, 44_100, 999_999_999))
@pytest.mark.parametrize("num_channels", (None, 1, 2))
@pytest.mark.parametrize("sample_rate", (8_000, 32_000))
@pytest.mark.parametrize(
"format",
[
# TODO: https://github.com/pytorch/torchcodec/issues/837
pytest.param(
"mp3",
marks=pytest.mark.skipif(
IS_WINDOWS and ffmpeg_major_version <= 5,
reason="Encoding mp3 on Windows is weirdly buggy",
),
),
pytest.param(
"wav",
marks=pytest.mark.skipif(
ffmpeg_major_version == 4,
reason="Swresample with FFmpeg 4 doesn't work on wav files",
),
),
"flac",
],
)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_against_cli(
self,
asset,
bit_rate,
num_channels,
sample_rate,
format,
method,
tmp_path,
capfd,
with_ffmpeg_debug_logs,
):
# Encodes samples with our encoder and with the FFmpeg CLI, and checks
# that both decoded outputs are equal
encoded_by_ffmpeg = tmp_path / f"ffmpeg_output.{format}"
subprocess.run(
["ffmpeg", "-i", str(asset.path)]
+ (["-b:a", f"{bit_rate}"] if bit_rate is not None else [])
+ (["-ac", f"{num_channels}"] if num_channels is not None else [])
+ ["-ar", f"{sample_rate}"]
+ [
str(encoded_by_ffmpeg),
],
capture_output=True,
check=True,
)
encoder = AudioEncoder(self.decode(asset).data, sample_rate=asset.sample_rate)
params = dict(
bit_rate=bit_rate, num_channels=num_channels, sample_rate=sample_rate
)
if method == "to_file":
encoded_by_us = tmp_path / f"output.{format}"
encoder.to_file(dest=str(encoded_by_us), **params)
elif method == "to_tensor":
encoded_by_us = encoder.to_tensor(format=format, **params)
elif method == "to_file_like":
file_like = io.BytesIO()
encoder.to_file_like(file_like, format=format, **params)
encoded_by_us = file_like.getvalue()
else:
raise ValueError(f"Unknown method: {method}")
captured = capfd.readouterr()
if format == "wav":
assert "Timestamps are unset in a packet" not in captured.err
if format == "mp3":
assert "Queue input is backward in time" not in captured.err
if format in ("flac", "wav"):
assert "Encoder did not produce proper pts" not in captured.err
if format in ("flac", "mp3"):
assert "Application provided invalid" not in captured.err
assert_close = torch.testing.assert_close
if sample_rate != asset.sample_rate:
if platform.machine().lower() == "aarch64":
rtol, atol = 0, 1e-2
else:
rtol, atol = 0, 1e-3
if sys.platform == "darwin":
assert_close = partial(assert_tensor_close_on_at_least, percentage=99)
elif format == "wav":
rtol, atol = 0, 1e-4
elif format == "mp3" and asset is SINE_MONO_S32 and num_channels == 2:
# Not sure why, this one needs slightly higher tol. With default
# tolerances, the check fails on ~1% of the samples, so that's
# probably fine. It might be that the FFmpeg CLI doesn't rely on
# libswresample for converting channels?
rtol, atol = 0, 1e-3
else:
rtol, atol = None, None
if IS_WINDOWS_WITH_FFMPEG_LE_70 and format == "mp3":
# We're getting a "Could not open input file" on Windows mp3 files when decoding.
# TODO: https://github.com/pytorch/torchcodec/issues/837
return
samples_by_us = self.decode(encoded_by_us)
samples_by_ffmpeg = self.decode(encoded_by_ffmpeg)
assert_close(
samples_by_us.data,
samples_by_ffmpeg.data,
rtol=rtol,
atol=atol,
)
assert samples_by_us.pts_seconds == samples_by_ffmpeg.pts_seconds
assert samples_by_us.duration_seconds == samples_by_ffmpeg.duration_seconds
assert samples_by_us.sample_rate == samples_by_ffmpeg.sample_rate
if method == "to_file":
validate_frames_properties(actual=encoded_by_us, expected=encoded_by_ffmpeg)
@pytest.mark.parametrize("asset", (NASA_AUDIO_MP3, SINE_MONO_S32))
@pytest.mark.parametrize("bit_rate", (None, 0, 44_100, 999_999_999))
@pytest.mark.parametrize("num_channels", (None, 1, 2))
@pytest.mark.parametrize(
"format",
[
# TODO: https://github.com/pytorch/torchcodec/issues/837
pytest.param(
"mp3",
marks=pytest.mark.skipif(
IS_WINDOWS and ffmpeg_major_version <= 5,
reason="Encoding mp3 on Windows is weirdly buggy",
),
),
pytest.param(
"wav",
marks=pytest.mark.skipif(
ffmpeg_major_version == 4,
reason="Swresample with FFmpeg 4 doesn't work on wav files",
),
),
"flac",
],
)
@pytest.mark.parametrize("method", ("to_tensor", "to_file_like"))
def test_against_to_file(
self, asset, bit_rate, num_channels, format, tmp_path, method
):
encoder = AudioEncoder(self.decode(asset).data, sample_rate=asset.sample_rate)
params = dict(bit_rate=bit_rate, num_channels=num_channels)
encoded_file = tmp_path / f"output.{format}"
encoder.to_file(dest=encoded_file, **params)
if method == "to_tensor":
encoded_output = encoder.to_tensor(
format=format, bit_rate=bit_rate, num_channels=num_channels
)
elif method == "to_file_like":
file_like = io.BytesIO()
encoder.to_file_like(
file_like, format=format, bit_rate=bit_rate, num_channels=num_channels
)
encoded_output = file_like.getvalue()
else:
raise ValueError(f"Unknown method: {method}")
if not (IS_WINDOWS_WITH_FFMPEG_LE_70 and format == "mp3"):
# We're getting a "Could not open input file" on Windows mp3 files when decoding.
# TODO: https://github.com/pytorch/torchcodec/issues/837
torch.testing.assert_close(
self.decode(encoded_file).data, self.decode(encoded_output).data
)
def test_encode_to_tensor_long_output(self):
# Check that we support re-allocating the output tensor when the encoded
# data is large.
samples = torch.rand(1, int(1e7))
encoded_tensor = AudioEncoder(samples, sample_rate=16_000).to_tensor(
format="flac", bit_rate=44_000
)
# Note: this should be in sync with its C++ counterpart for the test to
# be meaningful.
INITIAL_TENSOR_SIZE = 10_000_000
assert encoded_tensor.numel() > INITIAL_TENSOR_SIZE
torch.testing.assert_close(self.decode(encoded_tensor).data, samples)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_contiguity(self, method, tmp_path):
# Ensure that 2 waveforms with the same values are encoded in the same
# way, regardless of their memory layout. Here we encode 2 equal
# waveforms, one is row-aligned while the other is column-aligned.
num_samples = 10_000 # per channel
contiguous_samples = torch.rand(2, num_samples).contiguous()
assert contiguous_samples.stride() == (num_samples, 1)
non_contiguous_samples = contiguous_samples.T.contiguous().T
assert non_contiguous_samples.stride() == (1, 2)
torch.testing.assert_close(
contiguous_samples, non_contiguous_samples, rtol=0, atol=0
)
def encode_to_tensor(samples):
params = dict(bit_rate=44_000)
if method == "to_file":
dest = str(tmp_path / "output.flac")
AudioEncoder(samples, sample_rate=16_000).to_file(dest=dest, **params)
with open(dest, "rb") as f:
return torch.frombuffer(f.read(), dtype=torch.uint8)
elif method == "to_tensor":
return AudioEncoder(samples, sample_rate=16_000).to_tensor(
format="flac", **params
)
elif method == "to_file_like":
file_like = io.BytesIO()
AudioEncoder(samples, sample_rate=16_000).to_file_like(
file_like, format="flac", **params
)
return torch.frombuffer(file_like.getvalue(), dtype=torch.uint8)
else:
raise ValueError(f"Unknown method: {method}")
encoded_from_contiguous = encode_to_tensor(contiguous_samples)
encoded_from_non_contiguous = encode_to_tensor(non_contiguous_samples)
torch.testing.assert_close(
encoded_from_contiguous, encoded_from_non_contiguous, rtol=0, atol=0
)
@pytest.mark.parametrize("num_channels_input", (1, 2))
@pytest.mark.parametrize("num_channels_output", (1, 2, None))
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_num_channels(
self, num_channels_input, num_channels_output, method, tmp_path
):
# We just check that the num_channels parameter is respected.
# Correctness is checked in other tests (like test_against_cli())
sample_rate = 16_000
source_samples = torch.rand(num_channels_input, 1_000)
format = "flac"
encoder = AudioEncoder(source_samples, sample_rate=sample_rate)
params = dict(num_channels=num_channels_output)
if method == "to_file":
encoded_path = str(tmp_path / f"output.{format}")
encoded_source = encoded_path
encoder.to_file(dest=encoded_path, **params)
elif method == "to_tensor":
encoded_source = encoder.to_tensor(format=format, **params)
elif method == "to_file_like":
file_like = io.BytesIO()
encoder.to_file_like(file_like, format=format, **params)
encoded_source = file_like.getvalue()
else:
raise ValueError(f"Unknown method: {method}")
if num_channels_output is None:
num_channels_output = num_channels_input
assert self.decode(encoded_source).data.shape[0] == num_channels_output
def test_1d_samples(self):
# smoke test making sure 1D samples are supported
samples_1d, sample_rate = torch.rand(1000), 16_000
samples_2d = samples_1d[None, :]
torch.testing.assert_close(
AudioEncoder(samples_1d, sample_rate=sample_rate).to_tensor("wav"),
AudioEncoder(samples_2d, sample_rate=sample_rate).to_tensor("wav"),
)
def test_to_file_like_custom_file_object(self, tmp_path):
class CustomFileObject:
def __init__(self):
self._file = io.BytesIO()
def write(self, data):
return self._file.write(data)
def seek(self, offset, whence=0):
return self._file.seek(offset, whence)
def get_encoded_data(self):
return self._file.getvalue()
asset = NASA_AUDIO_MP3
source_samples = self.decode(asset).data
encoder = AudioEncoder(source_samples, sample_rate=asset.sample_rate)
file_like = CustomFileObject()
encoder.to_file_like(file_like, format="flac")
decoded_samples = self.decode(file_like.get_encoded_data())
torch.testing.assert_close(
decoded_samples.data,
source_samples,
rtol=0,
atol=1e-4,
)
def test_to_file_like_real_file(self, tmp_path):
"""Test to_file_like with a real file opened in binary write mode."""
asset = NASA_AUDIO_MP3
source_samples = self.decode(asset).data
encoder = AudioEncoder(source_samples, sample_rate=asset.sample_rate)
file_path = tmp_path / "test_file_like.wav"
with open(file_path, "wb") as file_like:
encoder.to_file_like(file_like, format="flac")
decoded_samples = self.decode(str(file_path))
torch.testing.assert_close(
decoded_samples.data, source_samples, rtol=0, atol=1e-4
)
def test_to_file_like_bad_methods(self):
asset = NASA_AUDIO_MP3
source_samples = self.decode(asset).data
encoder = AudioEncoder(source_samples, sample_rate=asset.sample_rate)
class NoWriteMethod:
def seek(self, offset, whence=0):
return 0
with pytest.raises(
RuntimeError, match="File like object must implement a write method"
):
encoder.to_file_like(NoWriteMethod(), format="wav")
class NoSeekMethod:
def write(self, data):
return len(data)
with pytest.raises(
RuntimeError, match="File like object must implement a seek method"
):
encoder.to_file_like(NoSeekMethod(), format="wav")
class TestVideoEncoder:
def decode(self, source=None) -> torch.Tensor:
return VideoDecoder(source).get_frames_in_range(start=0, stop=30).data
# TODO: add average_fps field to TestVideo asset
def decode_and_get_frame_rate(self, source=None):
decoder = VideoDecoder(source)
frames = decoder.get_frames_in_range(start=0, stop=30).data
frame_rate = decoder.metadata.average_fps
return frames, frame_rate
def _get_video_metadata(self, file_path, fields):
"""Helper function to get video metadata from a file using ffprobe."""
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
f"stream={','.join(fields)}",
"-of",
"default=noprint_wrappers=1",
str(file_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
text=True,
)
metadata = {}
for line in result.stdout.strip().split("\n"):
if "=" in line:
key, value = line.split("=", 1)
metadata[key] = value
assert all(field in metadata for field in fields)
return metadata
def _get_frames_info(self, file_path, fields):
"""Helper function to get frame info (pts, dts, etc.) using ffprobe."""
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
f"frame={','.join(fields)}",
"-of",
"json",
str(file_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
text=True,
)
frames = json.loads(result.stdout)["frames"]
assert all(field in frame for field in fields for frame in frames)
return frames
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_bad_input_parameterized(self, tmp_path, method):
if method == "to_file":
valid_params = dict(dest=str(tmp_path / "output.mp4"))
elif method == "to_tensor":
valid_params = dict(format="mp4")
elif method == "to_file_like":
valid_params = dict(file_like=io.BytesIO(), format="mp4")
else:
raise ValueError(f"Unknown method: {method}")
with pytest.raises(
ValueError, match="Expected uint8 frames, got frames.dtype = torch.float32"
):
encoder = VideoEncoder(
frames=torch.rand(5, 3, 64, 64),
frame_rate=30,
)
getattr(encoder, method)(**valid_params)
with pytest.raises(
ValueError, match=r"Expected 4D frames, got frames.shape = torch.Size"
):
encoder = VideoEncoder(
frames=torch.zeros(10),
frame_rate=30,
)
getattr(encoder, method)(**valid_params)
with pytest.raises(
RuntimeError, match=r"frame must have 3 channels \(R, G, B\), got 2"
):
encoder = VideoEncoder(
frames=torch.zeros((5, 2, 64, 64), dtype=torch.uint8),
frame_rate=30,
)
getattr(encoder, method)(**valid_params)
with pytest.raises(
RuntimeError,
match=r"Video codec invalid_codec_name not found.",
):
encoder = VideoEncoder(
frames=torch.zeros((5, 3, 64, 64), dtype=torch.uint8),
frame_rate=30,
)
encoder.to_file(str(tmp_path / "output.mp4"), codec="invalid_codec_name")
with pytest.raises(RuntimeError, match=r"crf=-10 is out of valid range"):
encoder = VideoEncoder(
frames=torch.zeros((5, 3, 64, 64), dtype=torch.uint8),
frame_rate=30,
)
getattr(encoder, method)(**valid_params, crf=-10)
with pytest.raises(
RuntimeError,
match=r"avcodec_open2 failed: Invalid argument",
):
encoder.to_tensor(format="mp4", preset="fake_preset")
@pytest.mark.parametrize("method", ["to_file", "to_tensor", "to_file_like"])
@pytest.mark.parametrize("crf", [23, 23.5, -0.9])
def test_crf_valid_values(self, method, crf, tmp_path):
if method == "to_file":
valid_params = {"dest": str(tmp_path / "test.mp4")}
elif method == "to_tensor":
valid_params = {"format": "mp4"}
elif method == "to_file_like":
valid_params = dict(file_like=io.BytesIO(), format="mp4")
else:
raise ValueError(f"Unknown method: {method}")
encoder = VideoEncoder(
frames=torch.zeros((5, 3, 64, 64), dtype=torch.uint8),
frame_rate=30,
)
getattr(encoder, method)(**valid_params, crf=crf)
def test_bad_input(self, tmp_path):
encoder = VideoEncoder(
frames=torch.zeros((5, 3, 64, 64), dtype=torch.uint8),
frame_rate=30,
)
with pytest.raises(
RuntimeError,
match=r"Couldn't allocate AVFormatContext. The destination file is ./file.bad_extension, check the desired extension\?",
):
encoder.to_file("./file.bad_extension")
with pytest.raises(
RuntimeError,
match=r"avio_open failed. The destination file is ./bad/path.mp3, make sure it's a valid path\?",
):
encoder.to_file("./bad/path.mp3")
with pytest.raises(
RuntimeError,
match=r"Couldn't allocate AVFormatContext. Check the desired format\? Got format=bad_format",
):
encoder.to_tensor(format="bad_format")
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
@pytest.mark.parametrize(
"device", ("cpu", pytest.param("cuda", marks=pytest.mark.needs_cuda))
)
def test_pixel_format_errors(self, method, device, tmp_path):
frames = torch.zeros((5, 3, 64, 64), dtype=torch.uint8).to(device)
encoder = VideoEncoder(frames, frame_rate=30)
if method == "to_file":
valid_params = dict(dest=str(tmp_path / "output.mp4"))
elif method == "to_tensor":
valid_params = dict(format="mp4")
elif method == "to_file_like":
valid_params = dict(file_like=io.BytesIO(), format="mp4")
if device == "cuda":
with pytest.raises(
RuntimeError,
match="Video encoding on GPU currently only supports the nv12 pixel format. Do not set pixel_format to use nv12 by default.",
):
getattr(encoder, method)(**valid_params, pixel_format="yuv444p")
return
with pytest.raises(
RuntimeError,
match=r"Unknown pixel format: invalid_pix_fmt[\s\S]*Supported pixel formats.*yuv420p",
):
getattr(encoder, method)(**valid_params, pixel_format="invalid_pix_fmt")
with pytest.raises(
RuntimeError,
match=r"Specified pixel format rgb24 is not supported[\s\S]*Supported pixel formats.*yuv420p",
):
getattr(encoder, method)(**valid_params, pixel_format="rgb24")
@pytest.mark.parametrize(
"extra_options,error",
[
({"qp": -10}, "qp=-10 is out of valid range"),
(
{"qp": ""},
"Option qp expects a numeric value but got",
),
(
{"direct-pred": "a"},
"Option direct-pred expects a numeric value but got 'a'",
),
({"tune": "not_a_real_tune"}, "avcodec_open2 failed: Invalid argument"),
(
{"tune": 10},
"avcodec_open2 failed: Invalid argument",
),
],
)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_extra_options_errors(self, method, tmp_path, extra_options, error):
frames = torch.zeros((5, 3, 64, 64), dtype=torch.uint8)
encoder = VideoEncoder(frames, frame_rate=30)
if method == "to_file":
valid_params = dict(dest=str(tmp_path / "output.mp4"))
elif method == "to_tensor":
valid_params = dict(format="mp4")
elif method == "to_file_like":
valid_params = dict(file_like=io.BytesIO(), format="mp4")
else:
raise ValueError(f"Unknown method: {method}")
with pytest.raises(
RuntimeError,
match=error,
):
getattr(encoder, method)(**valid_params, extra_options=extra_options)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
@pytest.mark.parametrize(
"device",
(
"cpu",
pytest.param(
"cuda",
marks=[
pytest.mark.needs_cuda,
pytest.mark.skipif(
in_fbcode(), reason="NVENC not available in fbcode"
),
pytest.mark.skipif(
ffmpeg_major_version == 4,
reason="CUDA + FFmpeg 4 test is flaky",
),
],
),
),
)
def test_contiguity(self, method, tmp_path, device):
# Ensure that 2 sets of video frames with the same pixel values are encoded
# in the same way, regardless of their memory layout. Here we encode 2 equal
# frame tensors, one is contiguous while the other is non-contiguous.
num_frames, channels, height, width = 5, 3, 256, 256
contiguous_frames = (
torch.randint(
0, 256, size=(num_frames, channels, height, width), dtype=torch.uint8
)
.contiguous()
.to(device)
)
assert contiguous_frames.is_contiguous()
# Permute NCHW to NHWC, then update the memory layout, then permute back
non_contiguous_frames = (
contiguous_frames.permute(0, 2, 3, 1).contiguous().permute(0, 3, 1, 2)
)
assert non_contiguous_frames.stride() != contiguous_frames.stride()
assert not non_contiguous_frames.is_contiguous()
assert non_contiguous_frames.is_contiguous(memory_format=torch.channels_last)
torch.testing.assert_close(
contiguous_frames, non_contiguous_frames, rtol=0, atol=0
)
def encode_to_tensor(frames):
common_params = dict(
crf=0,
pixel_format="yuv444p" if device == "cpu" else None,
)
if method == "to_file":
dest = str(tmp_path / "output.mp4")
VideoEncoder(frames, frame_rate=30).to_file(dest=dest, **common_params)
with open(dest, "rb") as f:
return torch.frombuffer(f.read(), dtype=torch.uint8)
elif method == "to_tensor":
return VideoEncoder(frames, frame_rate=30).to_tensor(
format="mp4", **common_params
)
elif method == "to_file_like":
file_like = io.BytesIO()
VideoEncoder(frames, frame_rate=30).to_file_like(
file_like, format="mp4", **common_params
)
return torch.frombuffer(file_like.getvalue(), dtype=torch.uint8)
else:
raise ValueError(f"Unknown method: {method}")
encoded_from_contiguous = encode_to_tensor(contiguous_frames)
encoded_from_non_contiguous = encode_to_tensor(non_contiguous_frames)
torch.testing.assert_close(
encoded_from_contiguous, encoded_from_non_contiguous, rtol=0, atol=0
)
@pytest.mark.parametrize(
"format",
[
"mov",
"mp4",
"mkv",
pytest.param(
"webm",
marks=[
pytest.mark.slow,
pytest.mark.skipif(
ffmpeg_major_version == 4
or (IS_WINDOWS and ffmpeg_major_version >= 6),
reason="Codec for webm is not available in this FFmpeg installation.",
),
],
),
],
)
@pytest.mark.parametrize("method", ("to_file", "to_tensor", "to_file_like"))
def test_round_trip(self, tmp_path, format, method):
# Test that decode(encode(decode(frames))) == decode(frames)
source_frames, frame_rate = self.decode_and_get_frame_rate(TEST_SRC_2_720P.path)
encoder = VideoEncoder(frames=source_frames, frame_rate=frame_rate)
if method == "to_file":
encoded_path = str(tmp_path / f"encoder_output.{format}")
encoder.to_file(dest=encoded_path, pixel_format="yuv444p", crf=0)
round_trip_frames = self.decode(encoded_path)
elif method == "to_tensor":
encoded_tensor = encoder.to_tensor(
format=format, pixel_format="yuv444p", crf=0
)
round_trip_frames = self.decode(encoded_tensor)
elif method == "to_file_like":
file_like = io.BytesIO()
encoder.to_file_like(
file_like=file_like, format=format, pixel_format="yuv444p", crf=0
)
round_trip_frames = self.decode(file_like.getvalue())
else:
raise ValueError(f"Unknown method: {method}")
assert source_frames.shape == round_trip_frames.shape
assert source_frames.dtype == round_trip_frames.dtype
atol = 3 if format == "webm" else 2
for s_frame, rt_frame in zip(source_frames, round_trip_frames):
assert psnr(s_frame, rt_frame) > 30
torch.testing.assert_close(s_frame, rt_frame, atol=atol, rtol=0)
@pytest.mark.parametrize(
"format",
[
"mov",
"mp4",
"avi",
"mkv",
"flv",
"gif",
pytest.param(
"webm",
marks=[
pytest.mark.slow,