π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add read_raw.
Peter Sobot6563073148af
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.hindex 0a35bc4..c7abf00 100644--- a/pedalboard/io/AudioFile.h+++ b/pedalboard/io/AudioFile.h@@ -219,6 +219,116 @@ public:return buffer;}+ py::handle readRaw(long long numSamples) {+ if (numSamples == 0)+ throw std::domain_error(+ "ReadableAudioFile will not read an entire file at once, due to the "+ "possibility that a file may be larger than available memory. Please "+ "pass a number of frames to read (available from the 'frames' "+ "attribute).");++ const juce::ScopedLock scopedLock(objectLock);+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");++ if (reader->usesFloatingPointData) {+ return read(numSamples).release();+ } else {+ switch (reader->bitsPerSample) {+ case 32:+ return readInteger<int>(numSamples).release();+ case 16:+ return readInteger<short>(numSamples).release();+ case 8:+ return readInteger<char>(numSamples).release();+ default:+ throw std::runtime_error("Not sure how to read " ++ std::to_string(reader->bitsPerSample) ++ "-bit audio data!");+ }+ }+ }++ template <typename SampleType>+ py::array_t<SampleType> readInteger(long long numSamples) {+ if (reader->usesFloatingPointData) {+ throw std::runtime_error(+ "Can't call readInteger with a floating point file!");+ }++ // Allocate a buffer to return of up to numSamples:+ int numChannels = reader->numChannels;+ numSamples =+ std::min(numSamples, reader->lengthInSamples - currentPosition);+ py::array_t<SampleType> buffer =+ py::array_t<SampleType>({(int)numChannels, (int)numSamples});++ py::buffer_info outputInfo = buffer.request();++ {+ py::gil_scoped_release release;++ // TODO: if reading 24-bit or 32-bit audio, pass through directly:+ if (reader->bitsPerSample > 16) {+ if (sizeof(SampleType) < 4) {+ throw std::runtime_error("Output array not wide enough to store " ++ std::to_string(reader->bitsPerSample) ++ "-bit integer data.");+ }++ std::memset((void *)outputInfo.ptr, 0,+ numChannels * numSamples * sizeof(SampleType));++ int **channelPointers = (int **)alloca(numChannels * sizeof(int *));+ for (int c = 0; c < numChannels; c++) {+ channelPointers[c] = ((int *)outputInfo.ptr) + (numSamples * c);+ }++ if (!reader->readSamples(channelPointers, numChannels, 0,+ currentPosition, numSamples)) {+ throw std::runtime_error("Failed to read from file.");+ }+ } else {+ // Read the file in smaller chunks, converting from int32 to the+ // appropriate output format as we go:+ std::vector<std::vector<int>> intBuffers;+ intBuffers.resize(numChannels);++ int **channelPointers = (int **)alloca(numChannels * sizeof(int *));+ for (long long startSample = 0; startSample < numSamples;+ startSample += DEFAULT_AUDIO_BUFFER_SIZE_FRAMES) {+ int samplesToRead =+ std::min(numSamples - startSample,+ (long long)DEFAULT_AUDIO_BUFFER_SIZE_FRAMES);++ for (int c = 0; c < numChannels; c++) {+ intBuffers[c].resize(samplesToRead);+ channelPointers[c] = intBuffers[c].data();+ }++ if (!reader->readSamples(channelPointers, numChannels, 0,+ currentPosition + startSample,+ samplesToRead)) {+ throw std::runtime_error("Failed to read from file.");+ }++ // Convert the data in intBuffers to the output format:+ char shift = 32 - reader->bitsPerSample;+ for (int c = 0; c < numChannels; c++) {+ SampleType *outputChannelPointer =+ (((SampleType *)outputInfo.ptr) + (c * numSamples));+ for (int i = 0; i < samplesToRead; i++) {+ outputChannelPointer[startSample + i] = intBuffers[c][i] >> shift;+ }+ }+ }+ }+ }++ currentPosition += numSamples;+ return buffer;+ }+void seek(long long targetPosition) {const juce::ScopedLock scopedLock(objectLock);if (!reader)@@ -273,7 +383,7 @@ private:juce::CriticalSection objectLock;int currentPosition = 0;-}; // namespace Pedalboard+};bool isInteger(double value) {double intpart;@@ -736,6 +846,12 @@ inline void init_audiofile(py::module &m) {"audio file at the current position. Audio samples are returned in ""the shape (channels, samples); i.e.: a stereo audio file will have ""shape (2, <length>). Returned data is always in float32 format.")+ .def("read_raw", &ReadableAudioFile::readRaw, py::arg("num_frames") = 0,+ "Read the given number of frames (samples in each channel) from the "+ "audio file at the current position. Audio samples are returned in "+ "the shape (channels, samples); i.e.: a stereo audio file will have "+ "shape (2, <length>). Returned data is in the raw format stored by "+ "the underlying file (one of int8, int16, int32, or float32).").def("seekable", &ReadableAudioFile::isSeekable,"Returns True if the file is currently open and calls to seek() ""will work.")diff --git a/tests/test_io.py b/tests/test_io.pyindex b43b02b..ac4f65f 100644--- a/tests/test_io.py+++ b/tests/test_io.py@@ -193,6 +193,15 @@ def test_basic_read(audio_filename: str, samplerate: float):af.read(1)[email protected]("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):with pedalboard.io.AudioFile(audio_filename) as af:@@ -281,7 +290,7 @@ def test_fails_on_unsupported_format(audio_filename: str):@pytest.mark.parametrize("samplerate", [8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000])[email protected]("num_channels", [1, 2, 8])[email protected]("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(@@ -295,20 +304,25 @@ def test_basic_write(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 = min(np.abs(np.iinfo(input_format).min), np.abs(np.iinfo(input_format).max))+ _max = np.iinfo(input_format).maxaudio = (original_audio * _max).astype(input_format)else:+ _max = 1.0audio = original_audio.astype(input_format)- num_samples = audio.shape[-1]-- write_bit_depth = 16+ # 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)- # 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+ num_samples = audio.shape[-1]with pedalboard.io.WriteableAudioFile(filename,@@ -354,21 +368,19 @@ def test_write_exact_int32_to_16_bit_wav(tmp_path: pathlib.Path):def test_read_16_bit_wav_matches_stdlib(tmp_path: pathlib.Path):filename = str(tmp_path / f"test-16bit.wav")- original = np.array([1, 2, 3, -1, -2, -3]).astype(np.int32)- signal = (original << 16).astype(np.int32)+ 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) as af:+ with pedalboard.io.WriteableAudioFile(filename, samplerate=1, bit_depth=16) 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() == 2stdlib_result = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)np.testing.assert_allclose(stdlib_result, original)- float_signal = signal / np.iinfo(np.int32).max+ float_signal = original / np.iinfo(np.int16).maxwith pedalboard.io.AudioFile(filename) as af:np.testing.assert_allclose(float_signal, af.read(af.frames)[0])