Skip to content

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

Fix thread safety issue in MP3Compressor. (#129)

Peter Sobot9a7f1f24c689
diff --git a/pedalboard/plugins/MP3Compressor.h b/pedalboard/plugins/MP3Compressor.h
index 749f525..dd5f7aa 100644
--- a/pedalboard/plugins/MP3Compressor.h
+++ b/pedalboard/plugins/MP3Compressor.h
@@ -20,6 +20,7 @@
extern "C" {
#include <lame.h>
+#include <lame_overrides.h>
}
namespace Pedalboard {
@@ -257,10 +258,10 @@ public:
auto ioBlock = context.getOutputBlock();
if (mp3BufferBytesFilled > 0) {
- int samplesDecoded =
- hip_decode(decoder.getContext(), (unsigned char *)mp3Buffer.getData(),
- mp3BufferBytesFilled, outputBuffer.getWritePointerAtEnd(0),
- outputBuffer.getWritePointerAtEnd(1));
+ int samplesDecoded = hip_decode_threadsafe(
+ decoder.getContext(), (unsigned char *)mp3Buffer.getData(),
+ mp3BufferBytesFilled, outputBuffer.getWritePointerAtEnd(0),
+ outputBuffer.getWritePointerAtEnd(1));
outputBuffer.incrementSampleCountBy(samplesDecoded);
mp3BufferBytesFilled = 0;
@@ -297,7 +298,8 @@ public:
// Decode frames from the buffer as soon as we get them:
if (mp3BufferBytesFilled > 0) {
- int samplesDecoded = hip_decode(
+
+ int samplesDecoded = hip_decode_threadsafe(
decoder.getContext(), (unsigned char *)mp3Buffer.getData(),
mp3BufferBytesFilled, outputBuffer.getWritePointerAtEnd(0),
outputBuffer.getWritePointerAtEnd(1));
diff --git a/setup.py b/setup.py
index c86d4d6..cb9ec8d 100644
--- a/setup.py
+++ b/setup.py
@@ -90,6 +90,9 @@ ALL_CPPFLAGS.extend(
)
ALL_SOURCE_PATHS += list(Path("vendors/rubberband/single").glob("*.cpp"))
+ALL_SOURCE_PATHS += list(Path("vendors").glob("*.c"))
+ALL_INCLUDES += ["vendors/"]
+
# LAME/mpglib:
LAME_FLAGS = ["-DHAVE_MPGLIB"]
LAME_CONFIG_FILE = str(Path("vendors/lame_config.h").resolve())
diff --git a/tests/test_thread_safety.py b/tests/test_thread_safety.py
new file mode 100644
index 0000000..e27bae5
--- /dev/null
+++ b/tests/test_thread_safety.py
@@ -0,0 +1,57 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 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 pytest
+from concurrent.futures import ThreadPoolExecutor
+
+import numpy as np
+
+import pedalboard
+
+
+TESTABLE_PLUGINS = []
+for plugin_class in pedalboard.Plugin.__subclasses__():
+ try:
+ plugin_class()
+ TESTABLE_PLUGINS.append(plugin_class)
+ except Exception:
+ pass
+
+
[email protected]("plugin_class", TESTABLE_PLUGINS)
+def test_concurrent_processing_produces_identical_audio(plugin_class):
+ num_concurrent_plugins = 10
+ sr = 48000
+ plugins = [plugin_class() for _ in range(num_concurrent_plugins)]
+
+ noise = np.random.rand(1, sr * 10)
+ expected_output = plugins[0].process(noise, sr)
+
+ # Test first to ensure the plugin is deterministic (some might not be):
+ if not np.allclose(expected_output, plugins[0].process(noise, sr)):
+ return
+
+ futures = []
+ with ThreadPoolExecutor(max_workers=num_concurrent_plugins) as e:
+ for plugin in plugins:
+ futures.append(e.submit(plugin.process, noise, sample_rate=sr))
+
+ # This will throw an exception if we exceed the timeout:
+ processed = [future.result(timeout=2 * num_concurrent_plugins) for future in futures]
+
+ for result in processed:
+ np.testing.assert_allclose(expected_output, result)
diff --git a/vendors/lame_overrides.c b/vendors/lame_overrides.c
new file mode 100644
index 0000000..e4882b8
--- /dev/null
+++ b/vendors/lame_overrides.c
@@ -0,0 +1,185 @@
+/**
+ * LAME's MP3 decoding routines are not thread-safe, and the functions that
+ * would need to be called to make them thread-safe from user code are `static`
+ * (i.e.: private) to the C file that contains them.
+ */
+
+#include "lame_overrides.h"
+
+#include "lame/libmp3lame/machine.h"
+
+#include "lame/libmp3lame/encoder.h"
+
+#include "lame/libmp3lame/util.h"
+#include "lame/mpglib/interface.h"
+#include "lame/mpglib/mpglib.h"
+
+#define hip_global_struct mpstr_tag
+
+/* copy mono samples */
+#define COPY_MONO(DST_TYPE, SRC_TYPE) \
+ { \
+ DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw; \
+ SRC_TYPE const *p_samples = (SRC_TYPE const *)p; \
+ for (i = 0; i < processed_samples; i++) \
+ *pcm_l++ = (DST_TYPE)(*p_samples++); \
+ }
+
+/* copy stereo samples */
+#define COPY_STEREO(DST_TYPE, SRC_TYPE) \
+ { \
+ DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw, *pcm_r = (DST_TYPE *)pcm_r_raw; \
+ SRC_TYPE const *p_samples = (SRC_TYPE const *)p; \
+ for (i = 0; i < processed_samples; i++) { \
+ *pcm_l++ = (DST_TYPE)(*p_samples++); \
+ *pcm_r++ = (DST_TYPE)(*p_samples++); \
+ } \
+ }
+
+int decode1_headersB_clipchoice(
+ PMPSTR pmp, unsigned char *buffer, size_t len, char pcm_l_raw[],
+ char pcm_r_raw[], mp3data_struct *mp3data, int *enc_delay, int *enc_padding,
+ char *p, size_t psize, int decoded_sample_size,
+ int (*decodeMP3_ptr)(PMPSTR, unsigned char *, int, char *, int, int *)) {
+ static const int smpls[2][4] = {
+ /* Layer I II III */
+ {0, 384, 1152, 1152}, /* MPEG-1 */
+ {0, 384, 1152, 576} /* MPEG-2(.5) */
+ };
+
+ int processed_bytes;
+ int processed_samples; /* processed samples per channel */
+ int ret;
+ int i;
+ int const len_l = len < INT_MAX ? (int)len : INT_MAX;
+ int const psize_l = psize < INT_MAX ? (int)psize : INT_MAX;
+
+ mp3data->header_parsed = 0;
+ ret = (*decodeMP3_ptr)(pmp, buffer, len_l, p, psize_l, &processed_bytes);
+ /* three cases:
+ * 1. headers parsed, but data not complete
+ * pmp->header_parsed==1
+ * pmp->framesize=0
+ * pmp->fsizeold=size of last frame, or 0 if this is first frame
+ *
+ * 2. headers, data parsed, but ancillary data not complete
+ * pmp->header_parsed==1
+ * pmp->framesize=size of frame
+ * pmp->fsizeold=size of last frame, or 0 if this is first frame
+ *
+ * 3. frame fully decoded:
+ * pmp->header_parsed==0
+ * pmp->framesize=0
+ * pmp->fsizeold=size of frame (which is now the last frame)
+ *
+ */
+ if (pmp->header_parsed || pmp->fsizeold > 0 || pmp->framesize > 0) {
+ mp3data->header_parsed = 1;
+ mp3data->stereo = pmp->fr.stereo;
+ mp3data->samplerate = freqs[pmp->fr.sampling_frequency];
+ mp3data->mode = pmp->fr.mode;
+ mp3data->mode_ext = pmp->fr.mode_ext;
+ mp3data->framesize = smpls[pmp->fr.lsf][pmp->fr.lay];
+
+ /* free format, we need the entire frame before we can determine
+ * the bitrate. If we haven't gotten the entire frame, bitrate=0 */
+ if (pmp->fsizeold > 0) /* works for free format and fixed, no overrun,
+ temporal results are < 400.e6 */
+ mp3data->bitrate = 8 * (4 + pmp->fsizeold) * mp3data->samplerate /
+ (1.e3 * mp3data->framesize) +
+ 0.5;
+ else if (pmp->framesize > 0)
+ mp3data->bitrate = 8 * (4 + pmp->framesize) * mp3data->samplerate /
+ (1.e3 * mp3data->framesize) +
+ 0.5;
+ else
+ mp3data->bitrate =
+ tabsel_123[pmp->fr.lsf][pmp->fr.lay - 1][pmp->fr.bitrate_index];
+
+ if (pmp->num_frames > 0) {
+ /* Xing VBR header found and num_frames was set */
+ mp3data->totalframes = pmp->num_frames;
+ mp3data->nsamp = mp3data->framesize * pmp->num_frames;
+ *enc_delay = pmp->enc_delay;
+ *enc_padding = pmp->enc_padding;
+ }
+ }
+
+ switch (ret) {
+ case MP3_OK:
+ switch (pmp->fr.stereo) {
+ case 1:
+ processed_samples = processed_bytes / decoded_sample_size;
+ COPY_MONO(short, short)
+ break;
+ case 2:
+ processed_samples = (processed_bytes / decoded_sample_size) >> 1;
+ COPY_STEREO(short, short)
+ break;
+ default:
+ processed_samples = -1;
+ assert(0);
+ break;
+ }
+ break;
+
+ case MP3_NEED_MORE:
+ processed_samples = 0;
+ break;
+
+ case MP3_ERR:
+ processed_samples = -1;
+ break;
+
+ default:
+ processed_samples = -1;
+ assert(0);
+ break;
+ }
+
+ /*fprintf(stderr,"ok, more, err: %i %i %i\n", MP3_OK, MP3_NEED_MORE, MP3_ERR
+ * ); */
+ /*fprintf(stderr,"ret = %i out=%i\n", ret, processed_samples ); */
+ return processed_samples;
+}
+
+#define OUTSIZE_CLIPPED (4096 * sizeof(short))
+
+/*
+ * For hip_decode: return code
+ * -1 error
+ * 0 ok, but need more data before outputing any samples
+ * n number of samples output. a multiple of 576 or 1152 depending on MP3
+ * file.
+ */
+int hip_decode_threadsafe(hip_t hip, unsigned char *buffer, size_t len,
+ short pcm_l[], short pcm_r[]) {
+ mp3data_struct mp3data;
+ int ret;
+ int totsize = 0; /* number of decoded samples per channel */
+ int enc_delay, enc_padding;
+
+ if (!hip) {
+ return -1;
+ }
+
+ char out[OUTSIZE_CLIPPED];
+
+ for (;;) {
+ int ret = decode1_headersB_clipchoice(
+ hip, buffer, len, (char *)pcm_l + totsize, (char *)pcm_r + totsize,
+ &mp3data, &enc_delay, &enc_padding, out, OUTSIZE_CLIPPED, sizeof(short),
+ decodeMP3);
+
+ switch (ret) {
+ case -1:
+ return ret;
+ case 0:
+ return totsize;
+ default:
+ totsize += ret;
+ len = 0; /* future calls to decodeMP3 are just to flush buffers */
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/vendors/lame_overrides.h b/vendors/lame_overrides.h
new file mode 100644
index 0000000..68337c5
--- /dev/null
+++ b/vendors/lame_overrides.h
@@ -0,0 +1,17 @@
+/**
+ * LAME's MP3 decoding routines are not thread-safe, and the functions that
+ * would need to be called to make them thread-safe from user code are `static`
+ * (i.e.: private) to the C file that contains them.
+ */
+
+#include "lame/include/lame.h"
+
+/*
+ * For hip_decode: return code
+ * -1 error
+ * 0 ok, but need more data before outputing any samples
+ * n number of samples output. a multiple of 576 or 1152 depending on MP3
+ * file.
+ */
+int hip_decode_threadsafe(hip_t hip, unsigned char *buffer, size_t len,
+ short pcm_l[], short pcm_r[]);
\ No newline at end of file