π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Propagate the correct exception through __exit__.
Peter Sobotd15a8d3c52c2
diff --git a/pedalboard/io/AudioStream.h b/pedalboard/io/AudioStream.hindex 9243fd1..e62d274 100644--- a/pedalboard/io/AudioStream.h+++ b/pedalboard/io/AudioStream.h@@ -159,7 +159,11 @@ public:void exit(const py::object &type, const py::object &value,const py::object &traceback) {+ bool shouldThrow = PythonException::isPending();stop();++ if (shouldThrow || PythonException::isPending())+ throw py::error_already_set();}static std::vector<std::string> getDeviceNames(bool isInput) {diff --git a/pedalboard/io/PythonOutputStream.h b/pedalboard/io/PythonOutputStream.hindex 035f8ff..075e0a9 100644--- a/pedalboard/io/PythonOutputStream.h+++ b/pedalboard/io/PythonOutputStream.h@@ -48,6 +48,9 @@ public:virtual void flush() noexcept override {py::gil_scoped_acquire acquire;+ if (PythonException::isPending())+ return;+try {if (py::hasattr(fileLike, "flush")) {fileLike.attr("flush")();@@ -72,6 +75,9 @@ public:virtual bool write(const void *ptr, size_t numBytes) noexcept override {py::gil_scoped_acquire acquire;+ if (PythonException::isPending())+ return false;+try {int bytesWritten =fileLike.attr("write")(py::bytes((const char *)ptr, numBytes))@@ -94,6 +100,9 @@ public:size_t numTimesToRepeat) noexcept override {py::gil_scoped_acquire acquire;+ if (PythonException::isPending())+ return false;+try {const size_t maxEffectiveSize = std::min(numTimesToRepeat, (size_t)8192);std::vector<char> buffer(maxEffectiveSize, byte);diff --git a/pedalboard/io/ReadableAudioFile.h b/pedalboard/io/ReadableAudioFile.hindex 2ecd148..364cb61 100644--- a/pedalboard/io/ReadableAudioFile.h+++ b/pedalboard/io/ReadableAudioFile.h@@ -431,7 +431,11 @@ public:void exit(const py::object &type, const py::object &value,const py::object &traceback) {+ bool shouldThrow = PythonException::isPending();close();++ if (shouldThrow || PythonException::isPending())+ throw py::error_already_set();}private:diff --git a/pedalboard/io/ResampledReadableAudioFile.h b/pedalboard/io/ResampledReadableAudioFile.hindex 6c0075b..37c965e 100644--- a/pedalboard/io/ResampledReadableAudioFile.h+++ b/pedalboard/io/ResampledReadableAudioFile.h@@ -224,7 +224,11 @@ public:void exit(const py::object &type, const py::object &value,const py::object &traceback) {+ bool shouldThrow = PythonException::isPending();close();++ if (shouldThrow || PythonException::isPending())+ throw py::error_already_set();}private:diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.hindex 317ab5c..154ce6f 100644--- a/pedalboard/io/WriteableAudioFile.h+++ b/pedalboard/io/WriteableAudioFile.h@@ -724,7 +724,11 @@ public:void exit(const py::object &type, const py::object &value,const py::object &traceback) {+ bool shouldThrow = PythonException::isPending();close();++ if (shouldThrow || PythonException::isPending())+ throw py::error_already_set();}PythonOutputStream *getPythonOutputStream() const {diff --git a/tests/test_io.py b/tests/test_io.pyindex db5d4d6..cc615d1 100644--- a/tests/test_io.py+++ b/tests/test_io.py@@ -986,14 +986,19 @@ def test_real_mp3_parsing_with_lyrics3():@pytest.mark.parametrize("quality", list(range(9)))[email protected]("chunk_duration", [16, 1024, 2048, 1024 * 1024])[email protected]("granularity", [1, 16, 17, 1024, 1025, 44100])[email protected]("chunk_duration", [16, 1024, 2048])+ "granularity,max_num_frames",+ [(1, 2048), (16, 2048), (17, 2048), (1024, 44100), (1025, 44100), (44100, 44100)],+)@pytest.mark.parametrize("extension", [".wav", ".aiff", ".flac"])-def test_seek_accuracy(quality: int, chunk_duration: int, granularity: int, extension: str):+def test_seek_accuracy(+ quality: int, chunk_duration: int, granularity: int, max_num_frames: int, extension: str+):stream = io.BytesIO()stream.name = "foo" + extensionsr = 44100- input_audio = np.random.rand(sr * 2).astype(np.float32)+ input_audio = np.random.rand(sr).astype(np.float32)if extension != ".flac":quality = Nonewith pedalboard.io.AudioFile(stream, "w", sr, quality=quality) as f:@@ -1004,19 +1009,20 @@ def test_seek_accuracy(quality: int, chunk_duration: int, granularity: int, extenum_frames = f.framesnp.testing.assert_allclose(f.read(f.frames)[0, : len(input_audio)], input_audio, atol=0.1)- for offset in range(0, num_frames, granularity):+ for offset in range(0, min(max_num_frames, num_frames), granularity):stream.seek(0)with pedalboard.io.ReadableAudioFile(stream) as f:- f.seek(offset)- np.testing.assert_allclose(- f.read(chunk_duration)[0, : len(input_audio) - offset],- input_audio[offset : offset + chunk_duration],- atol=0.1,- err_msg=(- f"{extension} file contents no longer matched after seeking to offset:"- f" {offset:,}"- ),- )+ for _ in range(2):+ f.seek(offset)+ np.testing.assert_allclose(+ f.read(chunk_duration)[0, : len(input_audio) - offset],+ input_audio[offset : offset + chunk_duration],+ atol=0.1,+ err_msg=(+ f"{extension} file contents no longer matched after seeking to offset:"+ f" {offset:,}"+ ),+ )@pytest.mark.parametrize("seek_seconds", [0, 0.1, 0.5, 1, 10])@@ -1099,3 +1105,41 @@ def test_mp3_at_all_samplerates(quality: str, samplerate: float, num_channels: i# skip a couple MP3 frames:af.read(MP3_FRAME_LENGTH_SAMPLES * 2)assert np.amax(np.mean(af.read(samplerate * secs), axis=0)) < 0.01+++def test_useful_exception_when_writing_to_unseekable_file_like():+ """+ Sigh.++ Writing to a tensorflow.io.gfile.GFile object fails, due to a known TensorFlow+ bug (as of March 9th, 2023): https://github.com/tensorflow/tensorflow/issues/32122++ While Pedalboard can't (or won't) easily work around this bug,+ this test ensures that if we encounter a misbehaving file-like object,+ we throw a useful error message.+ """++ class ILieAboutSeekability(object):+ def __init__(self):+ self.bytes_written = 0++ @property+ def name(self) -> str:+ return "something.wav"++ def seekable(self) -> bool:+ return True++ def write(self, data: bytes) -> None:+ self.bytes_written += len(data)++ def seek(self, new_position: int) -> None:+ raise NotImplementedError("What's a seek?")++ def tell(self) -> int:+ return self.bytes_written++ with pytest.raises(NotImplementedError) as e:+ with pedalboard.io.AudioFile(ILieAboutSeekability(), "w", 44100, 2) as f:+ f.write(np.random.rand(2, 44100))+ assert "What's a seek?" in str(e)