Skip to content

πŸŽ› πŸ”Š A Python library for audio.

Avoid deadlocks and nondeterministic results when using the same AudioFile in multiple threads. (#298)

Peter Sobot55e62aa33076
diff --git a/pedalboard/io/PythonFileLike.h b/pedalboard/io/PythonFileLike.h
index 288c0d4..39c2258 100644
--- a/pedalboard/io/PythonFileLike.h
+++ b/pedalboard/io/PythonFileLike.h
@@ -45,8 +45,64 @@ inline void raise() {
}
}; // namespace PythonException
+/**
+ * A tiny helper class that downgrades a write lock
+ * to a read lock for the given scope. If we can't
+ * regain the write lock on the provided object,
+ * the GIL will be released in a busy loop until
+ * the write lock becomes available to us.
+ */
+class ScopedDowngradeToReadLockWithGIL {
+public:
+ ScopedDowngradeToReadLockWithGIL(juce::ReadWriteLock *lock) : lock(lock) {
+ if (lock) {
+ lock->enterRead();
+ lock->exitWrite();
+ }
+ }
+
+ ~ScopedDowngradeToReadLockWithGIL() {
+ if (lock) {
+ while (!lock->tryEnterWrite()) {
+ // If we have the GIL, release it briefly to avoid deadlocks:
+ if (PyGILState_Check() == true) {
+ py::gil_scoped_release release;
+ }
+ }
+
+ lock->exitRead();
+ }
+ }
+
+private:
+ juce::ReadWriteLock *lock;
+};
+
+/** Cribbed from Juce 7: */
+class ScopedTryWriteLock {
+public:
+ ScopedTryWriteLock(juce::ReadWriteLock &lockIn) noexcept
+ : lock(lockIn), lockWasSuccessful(lock.tryEnterWrite()) {}
+
+ ~ScopedTryWriteLock() noexcept {
+ if (lockWasSuccessful)
+ lock.exitWrite();
+ }
+
+ bool isLocked() const noexcept { return lockWasSuccessful; }
+
+ bool retryLock() noexcept { return lockWasSuccessful = lock.tryEnterWrite(); }
+
+private:
+ juce::ReadWriteLock &lock;
+ bool lockWasSuccessful;
+};
+
/**
* A base class for file-like Python object wrappers.
+ *
+ * Note that the objectLock passed in will be unlocked before
+ * the GIL is reacquired to avoid deadlocks.
*/
class PythonFileLike {
public:
@@ -54,6 +110,7 @@ public:
virtual ~PythonFileLike() {}
virtual std::string getRepresentation() {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
return "<__repr__ failed>";
@@ -64,6 +121,7 @@ public:
// Some Python file-like objects expose a ".name" property.
// If this object has that property, return its value;
// otherwise return an empty optional.
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (!PythonException::isPending() && py::hasattr(fileLike, "name")) {
@@ -74,6 +132,7 @@ public:
}
virtual bool isSeekable() noexcept {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (!PythonException::isPending()) {
@@ -90,6 +149,7 @@ public:
}
virtual juce::int64 getPosition() noexcept {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (!PythonException::isPending()) {
@@ -106,6 +166,7 @@ public:
}
virtual bool setPosition(juce::int64 pos) noexcept {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (!PythonException::isPending()) {
@@ -124,7 +185,10 @@ public:
py::object getFileLikeObject() { return fileLike; }
+ void setObjectLock(juce::ReadWriteLock *lock) { objectLock = lock; }
+
protected:
py::object fileLike;
+ juce::ReadWriteLock *objectLock = nullptr;
};
}; // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/io/PythonInputStream.h b/pedalboard/io/PythonInputStream.h
index adc064e..aa46751 100644
--- a/pedalboard/io/PythonInputStream.h
+++ b/pedalboard/io/PythonInputStream.h
@@ -61,24 +61,8 @@ public:
PythonInputStream(py::object fileLike) : PythonFileLike(fileLike) {}
virtual ~PythonInputStream() {}
- bool isSeekable() noexcept override {
- py::gil_scoped_acquire acquire;
-
- if (PythonException::isPending())
- return false;
-
- try {
- return fileLike.attr("seekable")().cast<bool>();
- } catch (py::error_already_set e) {
- e.restore();
- return false;
- } catch (const py::builtin_exception &e) {
- e.set_error();
- return false;
- }
- }
-
juce::int64 getTotalLength() noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
@@ -114,11 +98,12 @@ public:
// The buffer should never be null, and a negative size is probably a
// sign that something is broken!
jassert(buffer != nullptr && bytesToRead >= 0);
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
+ py::gil_scoped_acquire acquire;
if (PythonException::isPending())
return 0;
- py::gil_scoped_acquire acquire;
try {
auto readResult = fileLike.attr("read")(bytesToRead);
@@ -172,6 +157,10 @@ public:
}
bool isExhausted() noexcept override {
+ // Read this up front to avoid releasing the object lock recursively:
+ juce::int64 totalLength = getTotalLength();
+
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
@@ -182,7 +171,7 @@ public:
return true;
}
- return fileLike.attr("tell")().cast<juce::int64>() == getTotalLength();
+ return fileLike.attr("tell")().cast<juce::int64>() == totalLength;
} catch (py::error_already_set e) {
e.restore();
return true;
@@ -193,6 +182,7 @@ public:
}
juce::int64 getPosition() noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
@@ -210,6 +200,7 @@ public:
}
bool setPosition(juce::int64 pos) noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
diff --git a/pedalboard/io/PythonOutputStream.h b/pedalboard/io/PythonOutputStream.h
index d3e1c9a..c14d114 100644
--- a/pedalboard/io/PythonOutputStream.h
+++ b/pedalboard/io/PythonOutputStream.h
@@ -46,6 +46,7 @@ public:
}
virtual void flush() noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
@@ -73,6 +74,7 @@ public:
}
virtual bool write(const void *ptr, size_t numBytes) noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
@@ -114,6 +116,7 @@ public:
virtual bool writeRepeatedByte(juce::uint8 byte,
size_t numTimesToRepeat) noexcept override {
+ ScopedDowngradeToReadLockWithGIL lock(objectLock);
py::gil_scoped_acquire acquire;
if (PythonException::isPending())
diff --git a/pedalboard/io/ReadableAudioFile.h b/pedalboard/io/ReadableAudioFile.h
index a6ff247..5bc864d 100644
--- a/pedalboard/io/ReadableAudioFile.h
+++ b/pedalboard/io/ReadableAudioFile.h
@@ -62,6 +62,9 @@ class ReadableAudioFile
public:
ReadableAudioFile(std::string filename) : filename(filename) {
registerPedalboardAudioFormats(formatManager, false);
+ // This is kind of silly, as nobody else has a reference
+ // to this object yet; but it prevents some juce assertions in debug builds:
+ juce::ScopedWriteLock writeLock(objectLock);
juce::File file(filename);
@@ -86,6 +89,12 @@ public:
ReadableAudioFile(std::unique_ptr<PythonInputStream> inputStream) {
registerPedalboardAudioFormats(formatManager, false);
+ // This is kind of silly, as nobody else has a reference
+ // to this object yet; but it prevents some juce assertions in debug builds:
+ juce::ScopedWriteLock writeLock(objectLock);
+
+ inputStream->setObjectLock(&objectLock);
+
if (!inputStream->isSeekable()) {
PythonException::raise();
throw std::domain_error("Failed to open audio file-like object: input "
@@ -163,6 +172,7 @@ public:
}
std::variant<double, long> getSampleRate() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -177,6 +187,7 @@ public:
}
double getSampleRateAsDouble() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -184,24 +195,28 @@ public:
}
long long getLengthInSamples() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
return reader->lengthInSamples + (lengthCorrection ? *lengthCorrection : 0);
}
double getDuration() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
return getLengthInSamples() / reader->sampleRate;
}
long getNumChannels() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
return reader->numChannels;
}
std::string getFileFormat() const {
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -251,7 +266,9 @@ public:
"pass a number of frames to read (available from the 'frames' "
"attribute).");
- const juce::ScopedLock scopedLock(objectLock);
+ std::optional<juce::ScopedReadLock> scopedLock =
+ std::optional<juce::ScopedReadLock>(objectLock);
+
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -261,6 +278,7 @@ public:
std::min(numSamples, (reader->lengthInSamples +
(lengthCorrection ? *lengthCorrection : 0)) -
currentPosition);
+
py::array_t<float> buffer =
py::array_t<float>({(long long)numChannels, (long long)numSamples});
@@ -272,9 +290,14 @@ public:
py::gil_scoped_release release;
numSamplesToKeep =
readInternal(numChannels, numSamples, (float *)outputInfo.ptr);
- PythonException::raise();
+
+ // After this point, we no longer need to hold the read lock as we don't
+ // interact with the reader object anymore. Releasing this early (before
+ // re-acquiring the GIL) helps avoid deadlocks:
+ scopedLock.reset();
}
+ PythonException::raise();
if (numSamplesToKeep < numSamples) {
buffer.resize({(long long)numChannels, (long long)numSamplesToKeep});
}
@@ -299,6 +322,16 @@ public:
long long readInternal(const long long numChannels,
const long long numSamplesToFill,
float *outputPointer) {
+ // Note: We take a "write" lock here as calling readInternal will
+ // advance internal state:
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. Note "
+ "that using multiple concurrent readers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+
// If the file being read does not have enough content, it _should_ pad
// the rest of the array with zeroes. Unfortunately, this does not seem to
// be true in practice, so we pre-zero the array to be returned here:
@@ -398,7 +431,7 @@ public:
"pass a number of frames to read (available from the 'frames' "
"attribute).");
- const juce::ScopedLock scopedLock(objectLock);
+ const juce::ScopedReadLock readLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -422,6 +455,7 @@ public:
template <typename SampleType>
py::array_t<SampleType> readInteger(long long numSamples) {
+ const juce::ScopedReadLock readLock(objectLock);
if (reader->usesFloatingPointData) {
throw std::runtime_error(
"Can't call readInteger with a floating point file!");
@@ -455,10 +489,21 @@ public:
channelPointers[c] = ((int *)outputInfo.ptr) + (numSamples * c);
}
- auto readResult = reader->readSamples(channelPointers, numChannels, 0,
- currentPosition, numSamples);
- PythonException::raise();
+ bool readResult = false;
+ {
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. Note "
+ "that using multiple concurrent readers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+ readResult = reader->readSamples(channelPointers, numChannels, 0,
+ currentPosition, numSamples);
+ }
+
if (!readResult) {
+ PythonException::raise();
throwReadError(currentPosition, numSamples);
}
} else {
@@ -479,13 +524,23 @@ public:
channelPointers[c] = intBuffers[c].data();
}
- auto readResult =
- reader->readSamples(channelPointers, numChannels, 0,
- currentPosition + startSample, samplesToRead);
+ bool readResult = false;
+ {
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. "
+ "Note that using multiple concurrent readers on the same "
+ "AudioFile object will produce nondeterministic results.");
+ }
- PythonException::raise();
+ readResult = reader->readSamples(channelPointers, numChannels, 0,
+ currentPosition + startSample,
+ samplesToRead);
+ }
if (!readResult) {
+ PythonException::raise();
throw std::runtime_error("Failed to read from file.");
}
@@ -502,12 +557,26 @@ public:
}
}
+ PythonException::raise();
+
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. "
+ "Note that using multiple concurrent readers on the same "
+ "AudioFile object will produce nondeterministic results.");
+ }
currentPosition += numSamples;
return buffer;
}
void seek(long long targetPosition) {
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
+ seekInternal(targetPosition);
+ }
+
+ void seekInternal(long long targetPosition) {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
if (targetPosition >
@@ -519,36 +588,55 @@ public:
" frames).");
if (targetPosition < 0)
throw std::domain_error("Cannot seek before start of file.");
+
+ // Promote to a write lock as we're now modifying the object:
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. Note that "
+ "using multiple concurrent readers on the same AudioFile object will "
+ "produce nondeterministic results.");
+ }
currentPosition = targetPosition;
}
long long tell() const {
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
return currentPosition;
}
void close() {
- const juce::ScopedLock scopedLock(objectLock);
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile; it cannot "
+ "be closed until the other thread completes its operation.");
+ }
+ // Note: This may deallocate a Python object, so must be called with the
+ // GIL held:
reader.reset();
}
bool isClosed() const {
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedLock(objectLock);
return !reader;
}
bool isSeekable() const {
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedLock(objectLock);
// At the moment, ReadableAudioFile instances are always seekable, as
// they're backed by files.
- return !isClosed();
+ return reader != nullptr;
}
bool exactDurationKnown() const {
- const juce::ScopedLock scopedLock(objectLock);
+ const juce::ScopedReadLock scopedLock(objectLock);
if (juce::AudioFormatReaderWithPosition *approximateLengthReader =
dynamic_cast<juce::AudioFormatReaderWithPosition *>(reader.get())) {
@@ -643,7 +731,7 @@ private:
juce::AudioFormatManager formatManager;
std::string filename;
std::unique_ptr<juce::AudioFormatReader> reader;
- juce::CriticalSection objectLock;
+ juce::ReadWriteLock objectLock;
long long currentPosition = 0;
diff --git a/pedalboard/io/ResampledReadableAudioFile.h b/pedalboard/io/ResampledReadableAudioFile.h
index 3c83d94..f1c85f7 100644
--- a/pedalboard/io/ResampledReadableAudioFile.h
+++ b/pedalboard/io/ResampledReadableAudioFile.h
@@ -61,6 +61,9 @@ public:
audioFile->getNumChannels(), quality) {}
std::variant<double, long> getSampleRate() const {
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
+
double integerPart;
double fractionalPart =
std::modf(resampler.getTargetSampleRate(), &integerPart);
@@ -73,13 +76,20 @@ public:
}
double getSampleRateAsDouble() const {
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
return resampler.getTargetSampleRate();
}
long getLengthInSamples() const {
- double length = (((double)audioFile->getLengthInSamples() *
- resampler.getTargetSampleRate()) /
- audioFile->getSampleRateAsDouble());
+ double underlyingLengthInSamples = (double)audioFile->getLengthInSamples();
+ double underlyingSampleRate = audioFile->getSampleRateAsDouble();
+
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
+ double length =
+ ((underlyingLengthInSamples * resampler.getTargetSampleRate()) /
+ underlyingSampleRate);
if (resampler.getOutputLatency() > 0) {
length -= (std::round(resampler.getOutputLatency()) -
resampler.getOutputLatency());
@@ -87,17 +97,36 @@ public:
return (long)length;
}
- double getDuration() const { return audioFile->getDuration(); }
+ double getDuration() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->getDuration();
+ }
- long getNumChannels() const { return audioFile->getNumChannels(); }
+ long getNumChannels() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->getNumChannels();
+ }
- bool exactDurationKnown() const { return audioFile->exactDurationKnown(); }
+ bool exactDurationKnown() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->exactDurationKnown();
+ }
- std::string getFileFormat() const { return audioFile->getFileFormat(); }
+ std::string getFileFormat() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->getFileFormat();
+ }
- std::string getFileDatatype() const { return audioFile->getFileDatatype(); }
+ std::string getFileDatatype() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->getFileDatatype();
+ }
- ResamplingQuality getQuality() const { return resampler.getQuality(); }
+ ResamplingQuality getQuality() const {
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
+ return resampler.getQuality();
+ }
py::array_t<float> read(std::variant<double, long long> numSamplesVariant) {
long long numSamples = parseNumSamples(numSamplesVariant);
@@ -108,13 +137,13 @@ public:
"memory. Please pass a number of frames to read (available from "
"the 'frames' attribute).");
- py::gil_scoped_release release;
juce::AudioBuffer<float> resampledBuffer;
{
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
resampledBuffer = readInternal(numSamples);
}
- py::gil_scoped_acquire acquire;
+
+ PythonException::raise();
return copyJuceBufferIntoPyArray(resampledBuffer,
ChannelLayout::NotInterleaved, 0);
}
@@ -127,6 +156,16 @@ public:
* @return juce::AudioBuffer<float> The resulting audio.
*/
juce::AudioBuffer<float> readInternal(long long numSamples) {
+ // Note: We take a "write" lock here as calling readInternal will
+ // advance internal state:
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. Note "
+ "that using multiple concurrent readers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+
long long samplesInResampledBuffer = 0;
juce::AudioBuffer<float> resampledBuffer(audioFile->getNumChannels(),
numSamples);
@@ -266,63 +305,97 @@ public:
void seek(long long targetPosition) {
py::gil_scoped_release release;
- const juce::ScopedLock scopedLock(objectLock);
- long long positionToSeekToIncludingBuffers = targetPosition;
+ {
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile. Note "
+ "that using multiple concurrent readers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+ long long positionToSeekToIncludingBuffers = targetPosition;
- long long targetPositionInSourceSampleRate =
- std::max(0LL, (long long)(((double)positionToSeekToIncludingBuffers *
- resampler.getSourceSampleRate()) /
- resampler.getTargetSampleRate()));
+ long long targetPositionInSourceSampleRate =
+ std::max(0LL, (long long)(((double)positionToSeekToIncludingBuffers *
+ resampler.getSourceSampleRate()) /
+ resampler.getTargetSampleRate()));
- targetPositionInSourceSampleRate -=
- inputBufferSizeFor(resampler.getQuality());
+ targetPositionInSourceSampleRate -=
+ inputBufferSizeFor(resampler.getQuality());
- long long maximumOverflow = (long long)std::ceil(
- resampler.getSourceSampleRate() / resampler.getTargetSampleRate());
- targetPositionInSourceSampleRate -= std::max(0LL, maximumOverflow);
+ long long maximumOverflow = (long long)std::ceil(
+ resampler.getSourceSampleRate() / resampler.getTargetSampleRate());
+ targetPositionInSourceSampleRate -= std::max(0LL, maximumOverflow);
- double floatingPositionInTargetSampleRate =
- std::max(0.0, ((double)targetPositionInSourceSampleRate *
- resampler.getTargetSampleRate()) /
- resampler.getSourceSampleRate());
+ double floatingPositionInTargetSampleRate =
+ std::max(0.0, ((double)targetPositionInSourceSampleRate *
+ resampler.getTargetSampleRate()) /
+ resampler.getSourceSampleRate());
- positionInTargetSampleRate =
- (long long)(floatingPositionInTargetSampleRate);
+ positionInTargetSampleRate =
+ (long long)(floatingPositionInTargetSampleRate);
- resampler.reset();
+ resampler.reset();
- long long inputSamplesUsed =
- resampler.advanceResamplerState(positionInTargetSampleRate);
- targetPositionInSourceSampleRate = inputSamplesUsed;
+ long long inputSamplesUsed =
+ resampler.advanceResamplerState(positionInTargetSampleRate);
+ targetPositionInSourceSampleRate = inputSamplesUsed;
- audioFile->seek(std::max(0LL, targetPositionInSourceSampleRate));
+ audioFile->seekInternal(std::max(0LL, targetPositionInSourceSampleRate));
- outputBuffer.setSize(0, 0);
+ outputBuffer.setSize(0, 0);
- const long long chunkSize = 1024 * 1024;
- for (long long i = positionInTargetSampleRate; i < targetPosition;
- i += chunkSize) {
- long long numSamples = std::min(chunkSize, targetPosition - i);
- this->readInternal(numSamples);
+ const long long chunkSize = 1024 * 1024;
+ for (long long i = positionInTargetSampleRate; i < targetPosition;
+ i += chunkSize) {
+ long long numSamples = std::min(chunkSize, targetPosition - i);
+ this->readInternal(numSamples);
+ }
}
+
+ PythonException::raise();
}
- long long tell() const { return positionInTargetSampleRate; }
+ long long tell() const {
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
+ return positionInTargetSampleRate;
+ }
void close() {
- const juce::ScopedLock scopedLock(objectLock);
+ py::gil_scoped_release release;
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently reading from this AudioFile; it cannot "
+ "be closed until the other thread completes its operation.");
+ }
_isClosed = true;
}
- bool isClosed() const { return audioFile->isClosed() || _isClosed; }
+ bool isClosed() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ if (audioFile->isClosed())
+ return true;
- bool isSeekable() const { return audioFile->isSeekable(); }
+ // ...but we do need a read lock here:
+ py::gil_scoped_release release;
+ const juce::ScopedReadLock scopedReadLock(objectLock);
+ return _isClosed;
+ }
+
+ bool isSeekable() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
+ return audioFile->isSeekable();
+ }
std::optional<std::string> getFilename() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
return audioFile->getFilename();
}
PythonInputStream *getPythonInputStream() const {
+ // No need for a ScopedReadLock here, as audioFile is const:
return audioFile->getPythonInputStream();
}
@@ -340,11 +413,11 @@ public:
}
private:
- std::shared_ptr<ReadableAudioFile> audioFile;
+ const std::shared_ptr<ReadableAudioFile> audioFile;
StreamResampler<float> resampler;
juce::AudioBuffer<float> outputBuffer;
long long positionInTargetSampleRate = 0;
- juce::CriticalSection objectLock;
+ juce::ReadWriteLock objectLock;
bool _isClosed = false;
};
diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.h
index 2c6de94..291c0a7 100644
--- a/pedalboard/io/WriteableAudioFile.h
+++ b/pedalboard/io/WriteableAudioFile.h
@@ -233,6 +233,10 @@ public:
std::optional<std::variant<std::string, float>> qualityInput = {}) {
pybind11::gil_scoped_release release;
+ // This is kind of silly, as nobody else has a reference
+ // to this object yet; but it prevents some juce assertions in debug builds:
+ juce::ScopedWriteLock writeLock(objectLock);
+
if (!isInteger(writeSampleRate)) {
throw py::type_error(
"Opening an audio file for writing requires an integer sample rate.");
@@ -298,6 +302,7 @@ public:
}
unsafeOutputStream = pythonOutputStream.get();
+ pythonOutputStream->setObjectLock(&objectLock);
outputStream = std::move(pythonOutputStream);
} else {
juce::File file(filename);
@@ -412,10 +417,27 @@ public:
// - so we need to release it before possibly throwing an exception, or
// the stream will leak.
outputStream.release();
- PythonException::raise();
+ try {
+ PythonException::raise();
+ } catch (const std::exception &e) {
+ // AudioFormatWriter objects may call .write() in their destructors,
+ // and we need to hold the ScopedWriteLock if they do, so we explicitly
+ // free the writer here instead of when WriteableAudioFile gets
+ // deallocated. (Note that because the object hasn't finished
+ // construction, its destructor will never be called directly.)
+ writer.reset();
+ throw;
+ }
}
}
+ ~WriteableAudioFile() {
+ // We need to release the writer here, as it may call .write() in its
+ // destructor, and we need to hold the ScopedWriteLock if it does:
+ juce::ScopedWriteLock writeLock(objectLock);
+ writer.reset();
+ }
+
/**
* A generic type-dispatcher for all writes.
* pybind11 supports dispatch here, but both pybind11-stubgen
@@ -448,7 +470,7 @@ public:
template <typename SampleType>
void write(py::array_t<SampleType, py::array::c_style> inputArray) {
- const juce::ScopedLock scopedLock(objectLock);
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
@@ -537,8 +559,9 @@ public:
bool writeSuccessful =
write(channelPointers, numChannels, samplesToWrite);
- PythonException::raise();
+
if (!writeSuccessful) {
+ PythonException::raise();
throw std::runtime_error("Unable to write data to audio file.");
}
}
@@ -554,8 +577,9 @@ public:
}
bool writeSuccessful = write(channelPointers, numChannels, numSamples);
- PythonException::raise();
+
if (!writeSuccessful) {
+ PythonException::raise();
throw std::runtime_error("Unable to write data to audio file.");
}
break;
@@ -565,7 +589,17 @@ public:
"Internal error: got unexpected channel layout.");
}
- framesWritten += numSamples;
+ {
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile. Note "
+ "that using multiple concurrent writers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+
+ framesWritten += numSamples;
+ }
}
template <typename TargetType, typename InputType,
@@ -639,6 +673,13 @@ public:
if (writer->isFloatingPoint()) {
return writeConvertingTo<float>(channels, numChannels, numSamples);
} else {
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile. Note "
+ "that using multiple concurrent writers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
return writer->write(channels, numSamples);
}
} else {
@@ -649,9 +690,23 @@ public:
// Just pass the floating point data into the writer as if it were
// integer data. If the writer requires floating-point input data, this
// works (and is documented!)
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile. Note "
+ "that using multiple concurrent writers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
return writer->write((const int **)channels, numSamples);
} else {
// Convert floating-point to fixed point, but let JUCE do that for us:
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile. Note "
+ "that using multiple concurrent writers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
return writer->writeFromFloatArrays(channels, numChannels, numSamples);
}
} else {
@@ -661,30 +716,52 @@ public:
}
void flush() {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
- const juce::ScopedLock scopedLock(objectLock);
- pybind11::gil_scoped_release release;
- if (!writer->flush()) {
+ bool flushSucceeded = false;
+ {
+ pybind11::gil_scoped_release release;
+
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile. Note "
+ "that using multiple concurrent writers on the same AudioFile "
+ "object will produce nondeterministic results.");
+ }
+ flushSucceeded = writer->flush();
+ }
+
+ if (!flushSucceeded) {
+ PythonException::raise();
throw std::runtime_error(
"Unable to flush audio file; is the underlying file seekable?");
}
}
void close() {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("Cannot close closed file.");
- const juce::ScopedLock scopedLock(objectLock);
+
+ ScopedTryWriteLock scopedTryWriteLock(objectLock);
+ if (!scopedTryWriteLock.isLocked()) {
+ throw std::runtime_error(
+ "Another thread is currently writing to this AudioFile; it cannot "
+ "be closed until the other thread completes its operation.");
+ }
writer.reset();
}
bool isClosed() const {
- const juce::ScopedLock scopedLock(objectLock);
+ const juce::ScopedReadLock scopedReadLock(objectLock);
return !writer;
}
std::variant<double, long> getSampleRate() const {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
@@ -699,6 +776,7 @@ public:
}
double getSampleRateAsDouble() const {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
@@ -712,12 +790,14 @@ public:
std::optional<std::string> getQuality() const { return quality; }
long getNumChannels() const {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
return writer->getNumChannels();
}
std::string getFileDatatype() const {
+ const juce::ScopedReadLock scopedReadLock(objectLock);
if (!writer)
throw std::runtime_error("I/O operation on a closed file.");
@@ -780,7 +860,7 @@ private:
std::optional<std::string> quality;
std::unique_ptr<juce::AudioFormatWriter> writer;
PythonOutputStream *unsafeOutputStream = nullptr;
- juce::CriticalSection objectLock;
+ juce::ReadWriteLock objectLock;
int framesWritten = 0;
};
diff --git a/tests/test_io.py b/tests/test_io.py
index 1f17b79..c9cbdf7 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -428,7 +428,7 @@ def test_read_from_empty_stream_produces_helpful_error_message():
assert "is empty" in str(exc_info.value)
-def test_file_like_exceptions_propagate():
+def test_file_like_exceptions_propagate_on_read():
audio_filename = FILENAMES_AND_SAMPLERATES[0][0]
stream = open(audio_filename, "rb")
stream_read = stream.read
@@ -451,6 +451,27 @@ def test_file_like_exceptions_propagate():
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(np.random.rand(44100))
+ should_throw[0] = True
+ with pytest.raises(ValueError, match=r"Some kinda error!"):
+ af.write(np.random.rand(44100))
+ should_throw[0] = False
+
+
def test_file_like_must_be_seekable():
audio_filename = FILENAMES_AND_SAMPLERATES[0][0]
diff --git a/tests/test_io_threading.py b/tests/test_io_threading.py
new file mode 100644
index 0000000..ad6d9bf
--- /dev/null
+++ b/tests/test_io_threading.py
@@ -0,0 +1,242 @@
+#! /usr/bin/env python
+#
+# Copyright 2024 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 random
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import nullcontext
+from functools import lru_cache
+from io import BytesIO
+
+import numpy as np
+import pytest
+
+from pedalboard import Resample
+from pedalboard.io import AudioFile
+
+# The number of iterations to run the test for with and
+# without a lock around each call to AudioFile's methods:
+MAX_ITERATIONS = {"lock": 10, "no lock": 100_000}
+
+
+class RandomError(Exception):
+ pass
+
+
+@lru_cache(maxsize=None)
+def big_buffer() -> np.ndarray:
+ return np.random.rand(44_100 * 60 * 10)
+
+
+def patch_bytes_io(io: BytesIO, should_error: threading.Event):
+ old_read = io.read
+
+ def read_and_sometimes_throw(*args, **kwargs):
+ if should_error.is_set():
+ raise RandomError()
+ return old_read(*args, **kwargs)
+
+ io.read = read_and_sometimes_throw
+
+ old_write = io.write
+
+ def write_and_sometimes_throw(*args, **kwargs):
+ if should_error.is_set():
+ raise RandomError()
+ return old_write(*args, **kwargs)
+
+ io.write = write_and_sometimes_throw
+ return io
+
+
+def one_minute_buffer(allow_memoryview: bool, should_error: threading.Event) -> BytesIO:
+ buf = BytesIO()
+ with AudioFile(buf, "w", 44100, 1, format="wav") as f:
+ f.write(np.random.rand(44100 * 60))
+ buf.seek(0)
+ if not allow_memoryview:
+ # Avoid triggering the fast-path for memoryview, which releases the GIL:
+ buf.getbuffer = lambda: False
+ return patch_bytes_io(buf, should_error)
+
+
[email protected]("num_workers", [2, 4])
[email protected]("allow_memoryview", [True, False])
[email protected]("locking_scheme", ["lock", "no lock"])
[email protected]("sample_rate", [44100, 22050])
[email protected]("raise_exceptions", [False, True])
+def test_simultaneous_reads_from_the_same_file(
+ num_workers: int,
+ allow_memoryview: bool,
+ locking_scheme: str,
+ sample_rate: float,
+ raise_exceptions: bool,
+):
+ """
+ Ensure that two concurrent readers of the same file don't cause
+ the Python process to deadlock on the GIL or the AudioFile object's
+ internal lock(s).
+
+ Note: This is still nonsensical (you would never want this as the
+ results are garbage) but it should at least not deadlock the
+ process.
+
+ raise_exceptions will randomly cause exceptions to be thrown by the
+ underlying Python file-like object, which should be propagated to
+ the caller regardless of the locking scheme used.
+ """
+ should_error = threading.Event()
+ buf = one_minute_buffer(allow_memoryview, should_error)
+
+ exception_occurred = threading.Event()
+ num_iterations = MAX_ITERATIONS[locking_scheme]
+
+ def do_work(af, lock):
+ operations = [
+ lambda: af.closed,
+ lambda: af.samplerate,
+ lambda: af.num_channels,
+ lambda: af.frames,
+ lambda: af.seek(0),
+ lambda: af.tell(),
+ lambda: af.seekable(),
+ lambda: af.seek(22050),
+ lambda: af.read(22050),
+ ]
+ # ResampledReadableAudioFile does not have this method:
+ if hasattr(af, "read_raw"):
+ operations.append(lambda: af.read_raw(22050))
+ try:
+ for _ in range(num_iterations):
+ if exception_occurred.is_set():
+ break
+ with lock or nullcontext():
+ try:
+ random.choice(operations)()
+ except RandomError:
+ pass
+ except Exception as e:
+ exception_occurred.set()
+ raise e
+
+ lock = threading.Lock() if locking_scheme == "lock" else None
+ with ThreadPoolExecutor(num_workers) as e, AudioFile(buf).resampled_to(
+ sample_rate, Resample.Quality.ZeroOrderHold
+ ) as af:
+ if raise_exceptions:
+ should_error.set()
+ futures = [e.submit(do_work, af, lock) for _ in range(num_workers)]
+
+ if lock:
+ for future in futures:
+ future.result()
+ else:
+ # Without a lock, we should expect a RuntimeError:
+ with pytest.raises(RuntimeError, match=r"thread"):
+ for future in futures:
+ future.result()
+
+ # Ensure that all threads are done:
+ for future in futures:
+ future.exception()
+ should_error.clear()
+
+
[email protected]("num_workers", [2, 4])
[email protected]("locking_scheme", ["lock", "no lock"])
[email protected]("raise_exceptions", [False, True])
+def test_simultaneous_writes_to_the_same_file(
+ num_workers: int,
+ locking_scheme: str,
+ raise_exceptions: bool,
+):
+ """
+ Ensure that two concurrent writers to the same file don't cause
+ the Python process to deadlock on the GIL or the AudioFile object's
+ internal lock(s).
+
+ Note: This is still nonsensical (you would never want this as the
+ results are garbage) but it should at least not deadlock the
+ process.
+
+ raise_exceptions will randomly cause exceptions to be thrown by the
+ underlying Python file-like object, which should be propagated to
+ the caller regardless of the locking scheme used.
+ """
+
+ big_buffer() # Pre-cache the buffer to avoid it being created in the threads
+
+ should_error = threading.Event()
+ exception_occurred = threading.Event()
+ num_iterations = MAX_ITERATIONS[locking_scheme]
+
+ def do_work(af, lock):
+ operations = [
+ lambda: af.tell(),
+ lambda: af.flush(),
+ lambda: af.closed,
+ lambda: af.samplerate,
+ lambda: af.num_channels,
+ lambda: af.frames,
+ lambda: af.write(big_buffer()),
+ ]
+ try:
+ for _ in range(num_iterations):
+ if exception_occurred.is_set():
+ break
+ with lock or nullcontext():
+ try:
+ random.choice(operations)()
+ except RandomError:
+ pass
+ except RuntimeError as e:
+ if "Unable to write" in repr(e):
+ # TODO: We _should_ get a RandomError here, but
+ # the Python exception can be cleared by another
+ # thread before we have a chance to raise it.
+ # Properly fixing this would require a lot of
+ # refactoring (to hold the GIL indefinitely
+ # once an exception is thrown), so for now we just
+ # put up with the generic error message in this
+ # extremely rare case.
+ pass
+ else:
+ raise
+ except Exception as e:
+ exception_occurred.set()
+ raise e
+
+ lock = threading.Lock() if locking_scheme == "lock" else None
+ buf = patch_bytes_io(BytesIO(), should_error)
+ with ThreadPoolExecutor(num_workers) as e, AudioFile(buf, "w", 44100, 1, format="wav") as af:
+ if raise_exceptions:
+ should_error.set()
+ futures = [e.submit(do_work, af, lock) for _ in range(num_workers)]
+
+ if lock:
+ for future in futures:
+ future.result()
+ else:
+ # Without a lock, we should expect a RuntimeError eventually
+ # once two or more threads try to write at the same time:
+ with pytest.raises(RuntimeError, match=r"thread"):
+ for future in futures:
+ future.result()
+
+ for future in futures:
+ future.exception()
+ should_error.clear()