-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathtest_io.py
More file actions
1678 lines (1366 loc) Β· 61.4 KB
/
test_io.py
File metadata and controls
1678 lines (1366 loc) Β· 61.4 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
#! /usr/bin/env python
#
# Copyright 2022 Spotify AB
#
# Licensed under the GNU Public License, Version 3.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.gnu.org/licenses/gpl-3.0.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import io
import os
import pathlib
import platform
import shutil
import time
import wave
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from typing import BinaryIO, Optional, cast
import mutagen
import numpy as np
import numpy.typing as npt
import pytest
import pedalboard
from .utils import generate_sine_at
EXPECTED_DURATION_SECONDS = 5
EXPECT_LENGTH_TO_BE_EXACT = {"wav", "aiff", "caf", "ogg", "m4a", "mp4"}
MP3_FRAME_LENGTH_SAMPLES = 1152
TEST_AUDIO_FILES = {
22050: glob.glob(os.path.join(os.path.dirname(__file__), "audio", "correct", "*22050*")),
44100: glob.glob(os.path.join(os.path.dirname(__file__), "audio", "correct", "*44100*")),
48000: glob.glob(os.path.join(os.path.dirname(__file__), "audio", "correct", "*48000*")),
}
FILENAMES_AND_SAMPLERATES = [
(filename, samplerate)
for samplerate, filenames in TEST_AUDIO_FILES.items()
for filename in filenames
# On some platforms, not all extensions will be available.
if any(filename.endswith(extension) for extension in pedalboard.io.get_supported_read_formats())
]
UNSUPPORTED_FILENAMES = [
filename
for filename in sum(TEST_AUDIO_FILES.values(), [])
if not any(
filename.endswith(extension) for extension in pedalboard.io.get_supported_read_formats()
)
]
@lru_cache(maxsize=None)
def cached_rand(*args, **kwargs) -> npt.NDArray[np.float32]:
return cast(npt.NDArray, np.random.rand(*args, **kwargs)).astype(np.float32)
def get_tolerance_for_format_and_bit_depth(extension: str, input_format, file_dtype: str) -> float:
if not extension.startswith("."):
extension = "." + extension
if extension in {".wav", ".aiff", ".flac"}:
file_bit_depth = int(file_dtype.replace("float", "").replace("int", ""))
if np.issubdtype(input_format, np.signedinteger):
input_bit_depth = np.dtype(input_format).itemsize * 8
return 4 / (2 ** min(file_bit_depth, input_bit_depth))
return 4 / (2**file_bit_depth)
# These formats offset the waveform substantially, and these tests don't do any realignment.
if extension in {".m4a", ".ac3", ".adts", ".mp4", ".mp2", ".mp3"}:
return 3.0
return 0.12
def test_read_constructor_dispatch():
filename, _samplerate = FILENAMES_AND_SAMPLERATES[0]
# Support reading a file with just its filename:
assert isinstance(pedalboard.io.AudioFile(filename), pedalboard.io.ReadableAudioFile)
# Support reading a file with just its filename and an explicit "r" (read) flag:
assert isinstance(pedalboard.io.AudioFile(filename, "r"), pedalboard.io.ReadableAudioFile)
# Support reading a file by using the appropriate subclass constructor just its filename:
assert isinstance(pedalboard.io.ReadableAudioFile(filename), pedalboard.io.ReadableAudioFile)
# Don't support reading a file by passing a mode to the
# subclass constructor (which would be redundant):
with pytest.raises(TypeError) as e:
pedalboard.io.ReadableAudioFile(filename, "r") # type: ignore
assert "incompatible function arguments" in str(e)
def test_write_constructor_dispatch(tmp_path: pathlib.Path):
filename = str(tmp_path / "temp.wav")
# Don't support writing to a file with just its filename and write args:
with pytest.raises(TypeError):
pedalboard.io.AudioFile(filename, 44100, 1) # type: ignore
# Support writing to a file with just its filename and an explicit "w" (write) flag:
assert isinstance(
pedalboard.io.AudioFile(filename, "w", 44100, 1), pedalboard.io.WriteableAudioFile
)
# Support writing to a file by using the appropriate subclass constructor just its filename:
assert isinstance(
pedalboard.io.WriteableAudioFile(filename, 44100, 1), pedalboard.io.WriteableAudioFile
)
# Don't support writing to a file by passing a mode
# to the subclass constructor (which would be redundant):
with pytest.raises(TypeError) as e:
pedalboard.io.WriteableAudioFile(filename, "w", 44100, 1) # type: ignore
assert "incompatible function arguments" in str(e)
# Support writing to a file by omitting num_channels to WriteableAudioFile:
assert isinstance(
pedalboard.io.WriteableAudioFile(filename, samplerate=44100),
pedalboard.io.WriteableAudioFile,
)
# but not if samplerate is missing:
with pytest.raises(TypeError) as e:
pedalboard.io.WriteableAudioFile(filename, num_channels=1) # type: ignore
assert "samplerate" in str(e)
# ... or to regular AudioFile with a "w" flag:
assert isinstance(
pedalboard.io.AudioFile(filename, "w", samplerate=44100),
pedalboard.io.WriteableAudioFile,
)
# but not if samplerate is missing:
with pytest.raises(TypeError) as e:
pedalboard.io.AudioFile(filename, "w", num_channels=1) # type: ignore
assert "samplerate" in str(e)
@pytest.mark.parametrize("extension", [".mp3", ".wav", ".ogg", ".flac"])
def test_basic_formats_available_on_all_platforms(extension: str):
assert extension in pedalboard.io.get_supported_read_formats()
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_basic_read(audio_filename: str, samplerate: float):
af = pedalboard.io.AudioFile(audio_filename)
assert af.samplerate == samplerate
assert af.num_channels == 1
if not audio_filename.endswith(".mp3"):
assert af.exact_duration_known
else:
assert af.exact_duration_known in (True, False)
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
else:
assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
samples = af.read(samplerate * EXPECTED_DURATION_SECONDS)
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
# File should no longer be useful:
assert af.read(1).nbytes == 0
# Seeking back to the start of the file should work:
assert af.seekable()
af.seek(0)
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
# Seeking to an arbitrary point should also work
af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert f"file_dtype={af.file_dtype}" in repr(af)
af.seek(0)
assert af.exact_duration_known in (True, False)
actual = af.read(af.frames)
assert af.exact_duration_known
expected = generate_sine_at(
af.samplerate, num_channels=af.num_channels, num_seconds=af.duration
)
# Crop the ends of the file, as lossy formats sometimes don't encode the whole file:
actual = actual[:, : len(expected)]
tolerance = get_tolerance_for_format_and_bit_depth(
audio_filename.split(".")[-1], np.int16, af.file_dtype
)
np.testing.assert_allclose(np.squeeze(expected), np.squeeze(actual), atol=tolerance)
af.close()
# Should be able to read properties of the file even after it's been closed:
assert af.num_channels == 1
assert af.samplerate == samplerate
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert "closed" in repr(af)
with pytest.raises(RuntimeError):
af.read(1)
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_read_raw(audio_filename: str, samplerate: float):
with pedalboard.io.AudioFile(audio_filename) as af:
num_samples = int(samplerate * EXPECTED_DURATION_SECONDS)
raw_samples = af.read_raw(num_samples)
assert raw_samples.shape == (1, num_samples)
assert af.file_dtype in str(raw_samples.dtype)
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_use_reader_as_context_manager(audio_filename: str, samplerate: float):
num_frames_when_open = None
with pedalboard.io.AudioFile(audio_filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == 1
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
else:
assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
num_frames_when_open = af.frames
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
# File should no longer be useful:
assert af.read(1).nbytes == 0
# Seeking back to the start of the file should work:
assert af.seekable()
af.seek(0)
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
# Seeking to an arbitrary point should also work
af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert "closed" not in repr(af)
# Should be able to read properties of the file even after it's been closed:
assert af.num_channels == 1
assert af.samplerate == samplerate
assert af.frames == num_frames_when_open
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert "closed" in repr(af)
# ... but reading from a closed file is still an error:
with pytest.raises(RuntimeError):
af.read(1)
def test_context_manager_allows_exceptions():
af = None
with pytest.raises(AssertionError):
with pedalboard.io.AudioFile(FILENAMES_AND_SAMPLERATES[0][0]) as af:
assert False
assert af is not None and af.closed
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_read_okay_without_extension(
tmp_path: pathlib.Path, audio_filename: str, samplerate: float
):
dest_path = str(tmp_path / "no_extension")
shutil.copyfile(audio_filename, dest_path)
with pedalboard.io.AudioFile(dest_path) as af:
assert af.samplerate == samplerate
assert af.num_channels == 1
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_read_from_seekable_stream(audio_filename: str, samplerate: float):
with open(audio_filename, "rb") as f:
stream = io.BytesIO(f.read())
af = pedalboard.io.AudioFile(stream)
num_frames_when_open = None
with af:
assert af.samplerate == samplerate
assert af.num_channels == 1
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
else:
assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
num_frames_when_open = af.frames
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
# File should no longer be useful:
assert af.read(1).nbytes == 0
# Seeking back to the start of the file should work:
assert af.seekable()
af.seek(0)
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
# Seeking to an arbitrary point should also work
af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert repr(stream) in repr(af)
assert "closed" not in repr(af)
# Should be able to read properties of the file even after it's been closed:
assert af.num_channels == 1
assert af.samplerate == samplerate
assert af.frames == num_frames_when_open
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert "closed" in repr(af)
# ... but reading from a closed file is still an error:
with pytest.raises(RuntimeError):
af.read(1)
def test_read_from_bytes_io_memoryview():
"""
Reading from a `memoryview` should be possible; and should be faster
as we can release the GIL instead of calling back into Python for
every .read() call.
"""
stream = io.BytesIO()
with pedalboard.io.AudioFile(stream, "w", 44100, 1, format="wav") as af:
af.write(cached_rand(44100))
stream.seek(0)
# Should be able to pass in a memoryview:
_memoryview = stream.getbuffer()
with pedalboard.io.AudioFile(_memoryview) as af:
assert af.num_channels == 1
assert af.frames == 44100
af.read(af.frames)
assert repr(_memoryview) in repr(af)
# Should be able to pass in the BytesIO object itself and that should still work:
with pedalboard.io.AudioFile(stream) as af:
assert repr(stream) in repr(af)
def test_read_from_bytes_io_with_offset():
stream = io.BytesIO()
with pedalboard.io.AudioFile(stream, "w", 44100, 1, format="wav") as af:
af.write(cached_rand(44100))
# Prepend this buffer with random garbage:
garbo = io.BytesIO(b"foobar" + stream.getvalue())
# ...but skip the first 6 bytes, after which the stream should be valid:
garbo.seek(6)
with pedalboard.io.AudioFile(garbo) as af:
assert af.num_channels == 1
assert af.frames == 44100
# Ensure that if we attempt to read past the end of the BytesIO buffer,
# we still only get the data we want:
assert af.read(af.frames + 10).shape[1] == 44100
@pytest.mark.skipif(bool(os.getenv("CI", False)), reason="This test is very flaky on CI runners.")
def test_read_from_bytes_io_memoryview_without_gil():
stream = io.BytesIO()
num_frames = 44100 * 1000
with pedalboard.io.AudioFile(stream, "w", 44100, 1, format="wav") as af:
af.write(cached_rand(num_frames))
num_cpus = os.cpu_count() or 1
ios = [io.BytesIO(stream.getvalue()) for _ in range(num_cpus)]
with ThreadPoolExecutor(num_cpus) as executor:
a = time.time()
futures = [executor.submit(pedalboard.io.AudioFile(_io).read, num_frames) for _io in ios]
for future in futures:
future.result()
b = time.time()
threaded_duration = b - a
ios = [io.BytesIO(stream.getvalue()) for _ in range(num_cpus)]
a = time.time()
for _io in ios:
pedalboard.io.AudioFile(_io).read(num_frames)
b = time.time()
serial_duration = b - a
# Threaded access should be faster than serial access.
# If the GIL is held when we read from the BytesIO stream, then the threaded
# version of this will be 2-3x slower than the serial version.
assert threaded_duration <= serial_duration
@pytest.mark.parametrize(
"mp3_filename",
[f for f in sum(TEST_AUDIO_FILES.values(), []) if f.endswith("mp3")],
)
def test_read_mp3_from_unnamed_stream(mp3_filename: str):
with open(mp3_filename, "rb") as f:
file_like = io.BytesIO(f.read())
with pedalboard.io.AudioFile(file_like) as af:
assert af is not None
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
def test_read_from_end_of_stream_produces_helpful_error_message(extension: str):
buf = io.BytesIO()
buf.name = f"something.{extension}"
with pedalboard.io.AudioFile(buf, "w", 44100, 1) as af:
af.write(cached_rand(44100))
buf.seek(len(buf.getvalue()))
try:
with pedalboard.io.AudioFile(buf) as af:
assert af.frames >= 44100
except Exception as e:
assert "end of the stream" in str(e)
assert "Try seeking" in str(e)
def test_read_from_empty_stream_produces_helpful_error_message():
with pytest.raises(ValueError) as exc_info:
with pedalboard.io.AudioFile(io.BytesIO()):
pass
assert "is empty" in str(exc_info.value)
def test_file_like_exceptions_propagate_on_read():
audio_filename = FILENAMES_AND_SAMPLERATES[0][0]
stream = open(audio_filename, "rb")
stream_read = stream.read
should_throw = [False]
def eventually_throw_exception(*args, **kwargs):
if should_throw[0]:
raise ValueError("Some kinda error!")
return stream_read(*args, **kwargs)
stream.read = eventually_throw_exception
with pedalboard.io.AudioFile(stream) as af:
assert af.read(1).nbytes > 0
should_throw[0] = True
with pytest.raises(ValueError) as e:
for _ in range(af.frames - 1):
af.read(1)
assert "Some kinda error!" in str(e)
def test_file_like_exceptions_propagate_on_write():
buf = io.BytesIO()
stream_write = buf.write
should_throw = [False]
def eventually_throw_exception(*args, **kwargs):
if should_throw[0]:
raise ValueError("Some kinda error!")
return stream_write(*args, **kwargs)
buf.write = eventually_throw_exception
with pedalboard.io.AudioFile(buf, "w", 44100, 1, format="wav") as af:
af.write(cached_rand(44100))
should_throw[0] = True
with pytest.raises(ValueError, match=r"Some kinda error!"):
af.write(cached_rand(44100))
should_throw[0] = False
def test_file_like_must_be_seekable():
audio_filename = FILENAMES_AND_SAMPLERATES[0][0]
with open(audio_filename, "rb") as f:
stream = io.BytesIO(f.read())
stream.seekable = lambda: False
# avoid triggering the fast-path for memoryview
stream.getbuffer = lambda: False # type: ignore
with pytest.raises(ValueError) as e:
with pedalboard.io.AudioFile(stream):
pass
assert "seekable" in str(e)
def test_no_crash_if_type_error_on_file_like():
audio_filename = FILENAMES_AND_SAMPLERATES[0][0]
with open(audio_filename, "rb") as f:
stream = io.BytesIO(f.read())
# Seekable should be a method, not a property:
stream.seekable = False # type: ignore
# avoid triggering the fast-path for memoryview
stream.getbuffer = lambda: False # type: ignore
with pytest.raises(TypeError) as e:
with pedalboard.io.AudioFile(stream):
pass
assert "bool" in str(e)
def test_file_like_must_be_seekable_for_write():
stream = io.BytesIO()
stream.seek = lambda x: (_ for _ in ()).throw(
ValueError(f"Failed to seek from {stream.tell():,} to {x:,} because I don't wanna")
) # type: ignore
with pytest.raises(ValueError) as e:
with pedalboard.io.AudioFile(stream, "w", 44100, 2, format="flac"):
pass
assert "I don't wanna" in str(e)
def test_write_fails_without_extension(tmp_path: pathlib.Path):
dest_path = str(tmp_path / "no_extension")
with pytest.raises(ValueError):
pedalboard.io.AudioFile(dest_path, "w", 44100, 1)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
def test_write_to_stream_supports_format(extension: str):
assert pedalboard.io.AudioFile(io.BytesIO(), "w", 44100, 2, format=extension) is not None
assert pedalboard.io.AudioFile(io.BytesIO(), "w", 44100, 2, format=extension[1:]) is not None
assert pedalboard.io.WriteableAudioFile(io.BytesIO(), 44100, 2, format=extension) is not None
assert (
pedalboard.io.WriteableAudioFile(io.BytesIO(), 44100, 2, format=extension[1:]) is not None
)
with pytest.raises(ValueError):
pedalboard.io.AudioFile(io.BytesIO(), "w", 44100, 2, format="txt")
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
def test_write_to_stream_prefers_format_over_stream_name(extension: str):
stream = io.BytesIO()
stream.name = "foo.txt"
assert pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension) is not None
assert pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension[1:]) is not None
assert pedalboard.io.WriteableAudioFile(stream, 44100, 2, format=extension) is not None
assert pedalboard.io.WriteableAudioFile(stream, 44100, 2, format=extension[1:]) is not None
with pytest.raises(ValueError):
pedalboard.io.AudioFile(stream, "w", 44100, 2)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
def test_read_from_non_bytes_stream(extension: str):
stream = io.StringIO()
stream.name = f"foo{extension}"
with pytest.raises(TypeError) as e:
pedalboard.io.AudioFile(stream, "r") # type: ignore
assert "expected to return bytes" in str(e)
assert "returned str" in str(e)
with pytest.raises(TypeError) as e:
pedalboard.io.ReadableAudioFile(stream) # type: ignore
assert "expected to return bytes" in str(e)
assert "returned str" in str(e)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
def test_write_to_non_bytes_stream(extension: str):
stream = io.StringIO()
expected_message = None
try:
stream.write(b"") # type: ignore
except TypeError as e:
expected_message = e.args[0]
assert expected_message is not None
with pytest.raises(TypeError) as e:
with pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension) as af: # type: ignore
af.write(cached_rand(1, 2))
assert expected_message in str(e)
with pytest.raises(TypeError) as e:
with pedalboard.io.WriteableAudioFile(stream, 44100, 2, format=extension) as af: # type: ignore
af.write(cached_rand(1, 2))
assert expected_message in str(e)
def test_fails_gracefully():
with pytest.raises(ValueError):
pedalboard.io.AudioFile(__file__)
with pytest.raises(ValueError):
with pedalboard.io.AudioFile(__file__):
pass
@pytest.mark.parametrize("audio_filename", UNSUPPORTED_FILENAMES)
def test_fails_on_unsupported_format(audio_filename: str):
with pytest.raises(ValueError):
af = pedalboard.io.AudioFile(audio_filename)
assert not af
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize(
"samplerate", [8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000]
)
@pytest.mark.parametrize("num_channels", [1, 2, 3])
@pytest.mark.parametrize("transposed", [False, True])
@pytest.mark.parametrize("input_format", [np.float32, np.float64, np.int8, np.int16, np.int32])
def test_basic_write(
tmp_path: pathlib.Path,
extension: str,
samplerate: float,
num_channels: int,
transposed: bool,
input_format,
):
if extension == ".mp3":
if samplerate not in {32000, 44100, 48000}:
return
if num_channels > 2:
return
filename = str(tmp_path / f"test{extension}")
original_audio = generate_sine_at(samplerate, num_channels=num_channels)
write_bit_depth = 16
# Not all formats support full 32-bit depth:
if extension in {".wav"} and np.issubdtype(input_format, np.signedinteger):
write_bit_depth = np.dtype(input_format).itemsize * 8
# Handle integer audio types by scaling the floating-point data to the full integer range:
if np.issubdtype(input_format, np.signedinteger):
_max = np.iinfo(input_format).max
audio = (original_audio * _max).astype(input_format)
else:
_max = 1.0
audio = original_audio.astype(input_format)
# Before writing, assert that the data we're about to write is what we expect:
tolerance = get_tolerance_for_format_and_bit_depth(".wav", input_format, "int16")
np.testing.assert_allclose(original_audio, audio.astype(np.float32) / _max, atol=tolerance)
num_samples = audio.shape[-1]
with pedalboard.io.WriteableAudioFile(
filename,
samplerate=samplerate,
num_channels=num_channels,
bit_depth=write_bit_depth,
) as af:
if transposed:
af.write(audio.T)
else:
af.write(audio)
assert os.path.exists(filename)
assert os.path.getsize(filename) > 0
with pedalboard.io.ReadableAudioFile(filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == num_channels
assert af.frames >= num_samples
tolerance = get_tolerance_for_format_and_bit_depth(extension, input_format, af.file_dtype)
as_written = af.read(num_samples)
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)
def test_write_exact_int32_to_16_bit_wav(tmp_path: pathlib.Path):
filename = str(tmp_path / "test.wav")
original = np.array([1, 2, 3, -1, -2, -3]).astype(np.int32)
signal = (original << 16).astype(np.int32)
with pedalboard.io.WriteableAudioFile(filename, samplerate=1) as af:
af.write(signal)
assert os.path.exists(filename)
# Read the exact wave values out with the `wave` package:
with wave.open(filename) as f:
assert f.getsampwidth() == 2
encoded = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)
np.testing.assert_allclose(encoded, original)
def test_read_16_bit_wav_matches_stdlib(tmp_path: pathlib.Path):
filename = str(tmp_path / "test-16bit.wav")
original = np.array([1, 2, 3, -1, -2, -3]).astype(np.int16)
signal = original.astype(np.int32) << 16
with pedalboard.io.WriteableAudioFile(filename, samplerate=1, bit_depth=16) as af:
af.write(signal)
# Read the exact wave values out with the `wave` package:
with wave.open(filename) as f:
assert f.getsampwidth() == 2
stdlib_result = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)
np.testing.assert_allclose(stdlib_result, original)
float_signal = original / np.iinfo(np.int16).max
with pedalboard.io.AudioFile(filename) as af:
np.testing.assert_allclose(float_signal, af.read(af.frames)[0])
def test_basic_write_int32_to_16_bit_wav(tmp_path: pathlib.Path):
samplerate = 44100
num_channels = 1
filename = str(tmp_path / "test.wav")
original = np.linspace(0, 1, 11)
# As per AES17: the integer value -(2^31) should never show up in the stream.
signal = (original * (2**31 - 1)).astype(np.int32)
with pedalboard.io.WriteableAudioFile(
filename,
samplerate=samplerate,
num_channels=num_channels,
bit_depth=16,
) as af:
af.write(signal)
# Read the exact wave values out with the `wave` package:
with wave.open(filename) as f:
assert f.getsampwidth() == 2
stdlib_result = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)
assert np.all(np.equal(stdlib_result, signal >> 16))
with pedalboard.io.ReadableAudioFile(filename) as af:
as_written = af.read(len(signal))[0]
np.testing.assert_allclose(original, as_written, atol=2 / (2**15))
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize(
"samplerate", [8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000]
)
@pytest.mark.parametrize("num_channels", [1, 2, 3])
@pytest.mark.parametrize("transposed", [False, True])
@pytest.mark.parametrize("input_format", [np.float32, np.float64, np.int8, np.int16, np.int32])
def test_write_to_seekable_stream(
extension: str, samplerate: float, num_channels: int, transposed: bool, input_format
):
if extension == ".mp3":
if samplerate not in {32000, 44100, 48000}:
return
if num_channels > 2:
return
original_audio = generate_sine_at(samplerate, num_channels=num_channels)
write_bit_depth = 16
# Not all formats support full 32-bit depth:
if extension in {".wav"} and np.issubdtype(input_format, np.signedinteger):
write_bit_depth = np.dtype(input_format).itemsize * 8
# Handle integer audio types by scaling the floating-point data to the full integer range:
if np.issubdtype(input_format, np.signedinteger):
_max = np.iinfo(input_format).max
audio = (original_audio * _max).astype(input_format)
else:
_max = 1.0
audio = original_audio.astype(input_format)
# Before writing, assert that the data we're about to write is what we expect:
tolerance = get_tolerance_for_format_and_bit_depth(".wav", input_format, "int16")
np.testing.assert_allclose(original_audio, audio.astype(np.float32) / _max, atol=tolerance)
num_samples = audio.shape[-1]
stream = io.BytesIO()
stream.name = f"my_file{extension}"
with pedalboard.io.WriteableAudioFile(
stream,
samplerate=samplerate,
num_channels=num_channels,
bit_depth=write_bit_depth,
) as af:
if transposed:
af.write(audio.T)
else:
af.write(audio)
assert stream.tell() > 0
stream.seek(0)
with pedalboard.io.AudioFile(stream) as af:
assert af.samplerate == samplerate
assert af.num_channels == num_channels
tolerance = get_tolerance_for_format_and_bit_depth(extension, input_format, af.file_dtype)
as_written = af.read(num_samples)
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize("samplerate", [32000, 44100, 48000])
@pytest.mark.parametrize("num_channels", [1, 2])
def test_write_twice_overwrites(
tmp_path: pathlib.Path, extension: str, samplerate: int, num_channels: int
):
filename = str(tmp_path / f"test{extension}")
original_audio = np.zeros((num_channels, samplerate))
with pedalboard.io.AudioFile(
filename, "w", samplerate=samplerate, num_channels=num_channels
) as af:
af.write(original_audio)
assert os.path.exists(filename)
assert os.path.getsize(filename) > 0
with pedalboard.io.AudioFile(filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == num_channels
assert af.frames > 0
first_read_result = af.read(af.frames)
# Write again:
with pedalboard.io.AudioFile(
filename, "w", samplerate=samplerate, num_channels=num_channels
) as af:
af.write(original_audio)
with pedalboard.io.AudioFile(filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == num_channels
assert af.frames > 0
second_read_result = af.read(af.frames)
np.testing.assert_allclose(second_read_result, first_read_result)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize("samplerate", [8000, 96000])
@pytest.mark.parametrize("num_channels", [1, 2, 3])
@pytest.mark.parametrize("transposed", [False, True])
@pytest.mark.parametrize("input_format", [np.float32, np.int32])
def test_write_matches_encode(
extension: str, samplerate: float, num_channels: int, transposed: bool, input_format
):
if extension == ".mp3":
if samplerate not in {32000, 44100, 48000}:
return
if num_channels > 2:
return
original_audio = generate_sine_at(samplerate, num_channels=num_channels)
write_bit_depth = 16
# Not all formats support full 32-bit depth:
if extension in {".wav"} and np.issubdtype(input_format, np.signedinteger):
write_bit_depth = np.dtype(input_format).itemsize * 8
# Handle integer audio types by scaling the floating-point data to the full integer range:
if np.issubdtype(input_format, np.signedinteger):
_max = np.iinfo(input_format).max
audio = (original_audio * _max).astype(input_format)
else:
_max = 1.0
audio = original_audio.astype(input_format)
# Before writing, assert that the data we're about to write is what we expect:
tolerance = get_tolerance_for_format_and_bit_depth(".wav", input_format, "int16")
np.testing.assert_allclose(original_audio, audio.astype(np.float32) / _max, atol=tolerance)
stream = io.BytesIO()
stream.name = f"my_file{extension}"
with pedalboard.io.WriteableAudioFile(
stream,
samplerate=samplerate,
num_channels=num_channels,
bit_depth=write_bit_depth,
) as af:
if transposed:
af.write(audio.T)
else:
af.write(audio)
assert stream.tell() > 0
stream.seek(0)
encoded_output = pedalboard.io.AudioFile.encode(
audio,
samplerate,
extension,
num_channels,
bit_depth=write_bit_depth,
)
if extension != ".ogg":
assert encoded_output == stream.getvalue()
else:
# Ogg files contain some randomness when encoded, but should decode identically:
with (
pedalboard.io.AudioFile(io.BytesIO(encoded_output)) as encoded_f,
pedalboard.io.AudioFile(stream) as streamed_f,
):
assert encoded_f.samplerate == streamed_f.samplerate
assert encoded_f.num_channels == streamed_f.num_channels
assert encoded_f.frames == streamed_f.frames
assert encoded_f.file_dtype == streamed_f.file_dtype
np.testing.assert_allclose(
encoded_f.read(encoded_f.frames),
streamed_f.read(streamed_f.frames),
# Ogg files don't have 32-bit precision, and the encoding is not 100% deterministic:
atol=(1e-3 if input_format == np.int32 else 0),
)
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize("samplerate", [1234.5, 23.0000000001])
def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
filename = str(tmp_path / f"test{extension}")
with pytest.raises(TypeError):
pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)
@pytest.mark.parametrize("extension", set(pedalboard.io.get_supported_write_formats()) - {".mp3"})
@pytest.mark.parametrize("samplerate", [123, 999, 48001])
def test_uncommon_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
filename = str(tmp_path / f"test{extension}")
with pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1):
pass
with pedalboard.io.ReadableAudioFile(filename) as af:
assert af.samplerate == samplerate
@pytest.mark.parametrize("extension", [".flac"])
@pytest.mark.parametrize("samplerate", [123456, 234567])
def test_unusable_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
filename = str(tmp_path / f"test{extension}")
with pytest.raises(ValueError) as e:
pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)
assert "44100" in str(e), "Expected exception to include details about supported sample rates."
@pytest.mark.parametrize("samplerate", [1234, 44100, 48000])
def test_sample_rate_is_int_by_default(samplerate: int):
buf = io.BytesIO()
buf.name = "foo.wav"
with pedalboard.io.AudioFile(buf, "w", samplerate=samplerate, num_channels=1) as f:
f.write(cached_rand(100))
buf.seek(0)
with pedalboard.io.AudioFile(buf) as f:
assert isinstance(f.samplerate, int)
assert f.samplerate == samplerate
@pytest.mark.parametrize("extension", [".flac"])
@pytest.mark.parametrize("samplerate", [22050, 44100, 48000])
def test_swapped_parameter_exception(tmp_path: pathlib.Path, extension: str, samplerate):
filename = str(tmp_path / f"test{extension}")
with pytest.raises(ValueError) as e:
pedalboard.io.WriteableAudioFile(filename, samplerate=1, num_channels=samplerate)