π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add tests and documentation for AudioStream.
Peter Sobot0af3c6599309
diff --git a/README.md b/README.mdindex 8b92414..e060630 100644--- a/README.md+++ b/README.md@@ -24,6 +24,7 @@- Support for reading and writing AIFF, FLAC, MP3, OGG, and WAV files on all platforms with no dependencies- Additional support for reading AAC, AC3, WMA, and other formats depending on platform- Support for on-the-fly resampling of audio files and streams with `O(1)` memory usage+ - Live audio processing and effects via [`AudioStream`](https://spotify.github.io/pedalboard/reference/pedalboard.io.html)- Built-in support for a number of basic audio transformations, including:- Guitar-style effects: `Chorus`, `Distortion`, `Phaser`, `Clipping`- Loudness and dynamic range effects: `Compressor`, `Gain`, `Limiter`@@ -213,6 +214,35 @@ board = Pedalboard([])```+### Running Pedalboard on Live Audio++On macOS or Windows, Pedalboard supports streaming live audio through+[an `AudioStream` object](https://spotify.github.io/pedalboard/reference/pedalboard.io.html#pedalboard.io.AudioStream),+allowing for real-time manipulation of audio by adding effects in Python.++```python+from pedalboard import Pedalboard, Chorus, Compressor, Delay, Gain, Reverb, Phaser+from pedalboard.io import AudioStream++# Open up an audio stream:+with AudioStream(+ input_device_name="Apogee Jam+", # Guitar interface+ output_device_name="MacBook Pro Speakers"+) as stream:+ # Audio is now streaming through this pedalboard and out of your speakers!+ stream.plugins = Pedalboard([+ Compressor(threshold_db=-50, ratio=25),+ Gain(gain_db=30),+ Chorus(),+ Phaser(),+ Convolution("./guitar_amp.wav", 1.0),+ Reverb(room_size=0.25),+ ])+ input("Press enter to stop streaming...")++# The live AudioStream is now closed, and audio has stopped.+```+For more examples, see:- [the "examples" folder of this repository](https://github.com/spotify/pedalboard/tree/master/examples)- [the "Pedalboard Demo" Colab notebook](https://colab.research.google.com/drive/1bHjhJj1aCoOlXKl_lOfG99Xs3qWVrhch)diff --git a/docs/_sources/faq.rst.txt b/docs/_sources/faq.rst.txtindex d013fe1..c1dd45f 100644--- a/docs/_sources/faq.rst.txt+++ b/docs/_sources/faq.rst.txt@@ -4,15 +4,9 @@ Frequently Asked QuestionsCan Pedalboard be used with live (real-time) audio?^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-Technically, yes, Pedalboard could be used with live audio input/output. See:---* `Pull request #98 <https://github.com/spotify/pedalboard/pull/98>`_\ , which contains an experimental live audio interface written in C++.-* `@stefanobazzi <https://github.com/stefanobazzi>`_\ 's `guitarboard <https://github.com/stefanobazzi/guitarboard>`_ project for an example that uses the ``python-sounddevice`` library.--However, there are a couple big caveats when talking about using Pedalboard in a live context. Python, as a language, is `garbage-collected <https://devguide.python.org/garbage_collector/>`_\ , meaning that your code randomly pauses on a regular interval to clean up unused objects. In most programs, this is not an issue at all. However, for live audio, garbage collection can result in random pops, clicks, or audio drop-outs that are very difficult to prevent. Python's `Global Interpreter Lock <https://wiki.python.org/moin/GlobalInterpreterLock>`_ also adds potentially-unbounded delays when switching threads, and most operating systems use a separate high-priority thread for audio processing; meaning that Python could block this thread and cause stuttering if *any* Python objects are accessed or mutated in the audio thread.--Note that if your application processes audio in a streaming fashion, but allows for large buffer sizes (multiple seconds of audio) or soft real-time requirements, Pedalboard can be used there without issue. Examples of this use case include streaming audio processing over the network, or processing data offline but chunk-by-chunk.+Yes! As of Pedalboard v0.6.9, the `AudioStream <https://spotify.github.io/pedalboard/reference/pedalboard.io.html#pedalboard.io.AudioStream>`+class allows live processing of audio through a Pedalboard object without needing to worry about Python's+`Global Interpreter Lock <https://wiki.python.org/moin/GlobalInterpreterLock>`_.Does Pedalboard support changing a plugin's parameters over time?^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^diff --git a/docs/source/faq.rst b/docs/source/faq.rstindex d013fe1..c1dd45f 100644--- a/docs/source/faq.rst+++ b/docs/source/faq.rst@@ -4,15 +4,9 @@ Frequently Asked QuestionsCan Pedalboard be used with live (real-time) audio?^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-Technically, yes, Pedalboard could be used with live audio input/output. See:---* `Pull request #98 <https://github.com/spotify/pedalboard/pull/98>`_\ , which contains an experimental live audio interface written in C++.-* `@stefanobazzi <https://github.com/stefanobazzi>`_\ 's `guitarboard <https://github.com/stefanobazzi/guitarboard>`_ project for an example that uses the ``python-sounddevice`` library.--However, there are a couple big caveats when talking about using Pedalboard in a live context. Python, as a language, is `garbage-collected <https://devguide.python.org/garbage_collector/>`_\ , meaning that your code randomly pauses on a regular interval to clean up unused objects. In most programs, this is not an issue at all. However, for live audio, garbage collection can result in random pops, clicks, or audio drop-outs that are very difficult to prevent. Python's `Global Interpreter Lock <https://wiki.python.org/moin/GlobalInterpreterLock>`_ also adds potentially-unbounded delays when switching threads, and most operating systems use a separate high-priority thread for audio processing; meaning that Python could block this thread and cause stuttering if *any* Python objects are accessed or mutated in the audio thread.--Note that if your application processes audio in a streaming fashion, but allows for large buffer sizes (multiple seconds of audio) or soft real-time requirements, Pedalboard can be used there without issue. Examples of this use case include streaming audio processing over the network, or processing data offline but chunk-by-chunk.+Yes! As of Pedalboard v0.6.9, the `AudioStream <https://spotify.github.io/pedalboard/reference/pedalboard.io.html#pedalboard.io.AudioStream>`+class allows live processing of audio through a Pedalboard object without needing to worry about Python's+`Global Interpreter Lock <https://wiki.python.org/moin/GlobalInterpreterLock>`_.Does Pedalboard support changing a plugin's parameters over time?^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^diff --git a/pedalboard/io/AudioStream.h b/pedalboard/io/AudioStream.hindex 7b8476e..a53eea4 100644--- a/pedalboard/io/AudioStream.h+++ b/pedalboard/io/AudioStream.h@@ -42,10 +42,13 @@ class AudioStream : public std::enable_shared_from_this<AudioStream>{public:AudioStream(std::string inputDeviceName, std::string outputDeviceName,- double sampleRate, int bufferSize)+ std::optional<std::shared_ptr<Chain>> pedalboard,+ std::optional<double> sampleRate, int bufferSize,+ bool allowFeedback)#ifdef JUCE_MODULE_AVAILABLE_juce_audio_devices- : pedalboard(- std::make_shared<Chain>(std::vector<std::shared_ptr<Plugin>>())),+ : pedalboard(pedalboard ? *pedalboard+ : std::make_shared<Chain>(+ std::vector<std::shared_ptr<Plugin>>())),livePedalboard(std::vector<std::shared_ptr<Plugin>>())#endif{@@ -53,9 +56,20 @@ public:juce::AudioDeviceManager::AudioDeviceSetup setup;setup.inputDeviceName = inputDeviceName;setup.outputDeviceName = outputDeviceName;- setup.sampleRate = sampleRate;+ // A value of 0 indicates we want to use whatever the device default is:+ setup.sampleRate = sampleRate ? *sampleRate : 0;setup.bufferSize = bufferSize;+ if (!allowFeedback &&+ juce::String(inputDeviceName).containsIgnoreCase("microphone") &&+ juce::String(outputDeviceName).containsIgnoreCase("speaker")) {+ throw std::runtime_error(+ "The audio input device passed to AudioStream looks like a "+ "microphone, and the output device looks like a speaker. This setup "+ "may cause feedback. To create an AudioStream anyways, pass "+ "`allow_feedback=True` to the AudioStream constructor.");+ }+juce::String defaultDeviceName;juce::String error = deviceManager.initialise(2, 2, nullptr, true,defaultDeviceName, &setup);@@ -101,6 +115,8 @@ public:// Check to see if the live pedalboard and the regular pedalboard// differ, and apply any changes as necessary:if (pedalboard->getAllPlugins() != livePedalboard.getAllPlugins()) {+ juce::SpinLock::ScopedLockType lock(livePedalboardMutex);+livePedalboard.getPlugins().clear();for (auto plugin : pedalboard->getPlugins()) {plugin->prepare(spec);@@ -164,9 +180,11 @@ public:outputChannelData, numOutputChannels, 0, numSamples);juce::dsp::ProcessContextReplacing<float> context(ioBlock);- // TODO: Should getPlugins() here have a lock around it?- for (auto plugin : livePedalboard.getPlugins()) {- int outputSamples = plugin->process(context);+ juce::SpinLock::ScopedTryLockType tryLock(livePedalboardMutex);+ if (tryLock.isLocked()) {+ for (auto plugin : livePedalboard.getPlugins()) {+ int outputSamples = plugin->process(context);+ }}}@@ -177,12 +195,15 @@ public:spec.numChannels = static_cast<juce::uint32>(device->getActiveOutputChannels().countNumberOfSetBits());+ juce::SpinLock::ScopedLockType lock(livePedalboardMutex);for (auto plugin : livePedalboard.getPlugins()) {plugin->prepare(spec);}}virtual void audioDeviceStopped() {+ juce::SpinLock::ScopedLockType lock(livePedalboardMutex);+for (auto plugin : livePedalboard.getPlugins()) {plugin->reset();}@@ -201,6 +222,11 @@ private:std::shared_ptr<Chain> pedalboard;+ // A simple spin-lock mutex that we can try to acquire from+ // the audio thread, allowing us to avoid modifying state that's+ // currently being used for rendering.+ juce::SpinLock livePedalboardMutex;+// A "live" pedalboard, called from the audio thread.// This is not exposed to Python, and is only updated from C++.Chain livePedalboard;@@ -215,86 +241,121 @@ private:inline void init_audio_stream(py::module &m) {auto audioStream =- py::class_<AudioStream, std::shared_ptr<AudioStream>>(- m, "AudioStream",- R("-A class that pipes audio from an input device to an output device, passing it through a Pedalboard to add effects.+ py::class_<AudioStream, std::shared_ptr<AudioStream>>(m, "AudioStream",+ R"(+A class that streams audio from an input audio device (i.e.: a microphone,+audio interface, etc) to an output device (speaker, headphones),+passing it through a Pedalboard to add effects.:class:`AudioStream` may be used as a context manager::- with AudioStream(ogg_buffer) as stream:-#In this block, audio is streaming through `stream`!-#Add plugins to the live audio stream:+ input_device_name = AudioStream.input_device_names[0]+ output_device_name = AudioStream.output_device_names[0]+ with AudioStream(input_device_name, output_device_name) as stream:+ # In this block, audio is streaming through `stream`!+ # Audio will be coming out of your speakers at this point.++ # Add plugins to the live audio stream:reverb = Reverb()- stream.pedalboard.append(reverb)+ stream.plugins.append(reverb)++ # Change plugin properties as the stream is running:reverb.wet_level = 1.0-#Delete plugins, etc:- del stream.pedalboard[0]+ # Delete plugins:+ del stream.plugins[0]:class:`AudioStream` may also be used synchronously::stream = AudioStream(ogg_buffer)- stream.pedalboard.append(Reverb(wet_level=1.0))- stream.stream()--*Introduced in v0.6.9.*-"))+ stream.plugins.append(Reverb(wet_level=1.0))+ stream.run() # Run the stream until Ctrl-C is received++.. note::+ This class uses C++ under the hood to ensure speed, thread safety,+ and avoid any locking concerns with Python's Global Interpreter Lock.+ Audio data processed by :class:`AudioStream` is not available to+ Python code; the only way to interact with the audio stream is through+ the :py:attr:`plugins` attribute.++.. warning::+ The :class:`AudioStream` class implements a context manager interface+ to ensure that audio streams are never left "dangling" (i.e.: running in+ the background without being stopped).++ While it is possible to call the :meth:`__enter__` method directly to run an+ audio stream in the background, this can have some nasty side effects. If the+ :class:`AudioStream` object is no longer reachable (not bound to a variable,+ not in scope, etc), the audio stream will continue to play back forever, and+ won't stop until the Python interpreter exits.++ To run an :class:`AudioStream` in the background, use Python's+ :py:mod:`threading` module to call the synchronous :meth:`run` method on a+ background thread, allowing for easier cleanup.++*Introduced in v0.6.9. Not supported on Linux.*+)").def(py::init([](std::string inputDeviceName,- std::string outputDeviceName, double sampleRate,- int bufferSize) {- return std::make_shared<AudioStream>(inputDeviceName, outputDeviceName,- sampleRate, bufferSize);+ std::string outputDeviceName,+ std::optional<std::shared_ptr<Chain>> pedalboard,+ std::optional<double> sampleRate, int bufferSize,+ bool allowFeedback) {+ return std::make_shared<AudioStream>(+ inputDeviceName, outputDeviceName, pedalboard, sampleRate,+ bufferSize, allowFeedback);}),py::arg("input_device_name"), py::arg("output_device_name"),- py::arg("sample_rate") = 44100, py::arg("buffer_size") = 512);+ py::arg("plugins") = py::none(),+ py::arg("sample_rate") = py::none(),+ py::arg("buffer_size") = 512, py::arg("allow_feedback") = false);#ifdef JUCE_MODULE_AVAILABLE_juce_audio_devicesaudioStream- .def("stream", &AudioStream::stream,- "Stream audio from input to output, through the `plugins` on this "- "AudioStream object, until a KeyboardInterrupt is received. "- "This call will block the current thread.")+ .def("run", &AudioStream::stream,+ "Start streaming audio from input to output, passing the audio "+ "stream through the :py:attr:`plugins` on this AudioStream object. "+ "This call will block the current thread until a KeyboardInterrupt "+ "(Ctrl-C) is received.").def_property_readonly("running", &AudioStream::getIsRunning,- "True iff this stream is currently streaming live "- "audio from input to output.")+ "True if this stream is currently streaming live "+ "audio from input to output, False otherwise.").def("__enter__", &AudioStream::enter).def("__exit__", &AudioStream::exit).def("__repr__",[](const AudioStream &stream) {- std::ostringstream ss;- ss << "<pedalboard.io.AudioStream";- auto audioDeviceSetup = stream.getAudioDeviceSetup();- ss << " input_device_name="- << audioDeviceSetup.inputDeviceName.toStdString();- ss << " output_device_name="- << audioDeviceSetup.outputDeviceName.toStdString();- ss << " sample_rate="- << juce::String(audioDeviceSetup.sampleRate, 2).toStdString();- ss << " buffer_size=" << audioDeviceSetup.bufferSize;- if (stream.getIsRunning()) {- ss << " running";- } else {- ss << " not running";- }- ss << " at " << &stream;- ss << ">";- return ss.str();+ std::ostringstream ss;+ ss << "<pedalboard.io.AudioStream";+ auto audioDeviceSetup = stream.getAudioDeviceSetup();+ ss << " input_device_name="+ << audioDeviceSetup.inputDeviceName.toStdString();+ ss << " output_device_name="+ << audioDeviceSetup.outputDeviceName.toStdString();+ ss << " sample_rate="+ << juce::String(audioDeviceSetup.sampleRate, 2).toStdString();+ ss << " buffer_size=" << audioDeviceSetup.bufferSize;+ if (stream.getIsRunning()) {+ ss << " running";+ } else {+ ss << " not running";+ }+ ss << " at " << &stream;+ ss << ">";+ return ss.str();})- .def_property(- "pedalboard", &AudioStream::getPedalboard,- &AudioStream::setPedalboard,- "The Pedalboard object currently processing the live effects chain.")+ .def_property("plugins", &AudioStream::getPedalboard,+ &AudioStream::setPedalboard,+ "The Pedalboard object that this AudioStream will use to "+ "process audio.").def_property_readonly_static("input_device_names",- [](py::object *obj) {- return AudioStream::getDeviceNames(true); },- "The currently-available input device names.")+ [](py::object *obj) { return AudioStream::getDeviceNames(true); },+ "The input devices (i.e.: microphones, audio interfaces, etc.) "+ "currently available on the current machine.").def_property_readonly_static("output_device_names",- [](py::object *obj) {- return AudioStream::getDeviceNames(false); },- "The currently-available output device names.");+ [](py::object *obj) { return AudioStream::getDeviceNames(false); },+ "The output devices (i.e.: speakers, headphones, etc.) currently "+ "available on the current machine.");#endif}} // namespace Pedalboard\ No newline at end of filediff --git a/pedalboard_native/io/__init__.pyi b/pedalboard_native/io/__init__.pyiindex d5db666..c969bbb 100644--- a/pedalboard_native/io/__init__.pyi+++ b/pedalboard_native/io/__init__.pyi@@ -7,6 +7,8 @@ import typingfrom typing_extensions import Literalfrom enum import Enumimport numpy+import pedalboard_native.utils # type: ignore # type: ignore+import pedalboard # type: ignore_Shape = typing.Tuple[int, ...]@@ -137,7 +139,57 @@ class AudioFile:class AudioStream:"""- A class that pipes audio from an input device to an output device, passing it through a Pedalboard to add effects.+ A class that streams audio from an input audio device (i.e.: a microphone,+ audio interface, etc) to an output device (speaker, headphones),+ passing it through a Pedalboard to add effects.++ :class:`AudioStream` may be used as a context manager::++ input_device_name = AudioStream.input_device_names[0]+ output_device_name = AudioStream.output_device_names[0]+ with AudioStream(input_device_name, output_device_name) as stream:+ # In this block, audio is streaming through `stream`!+ # Audio will be coming out of your speakers at this point.++ # Add plugins to the live audio stream:+ reverb = Reverb()+ stream.plugins.append(reverb)++ # Change plugin properties as the stream is running:+ reverb.wet_level = 1.0++ # Delete plugins:+ del stream.plugins[0]+++ :class:`AudioStream` may also be used synchronously::++ stream = AudioStream(ogg_buffer)+ stream.plugins.append(Reverb(wet_level=1.0))+ stream.run() # Run the stream until Ctrl-C is received++ .. note::+ This class uses C++ under the hood to ensure speed, thread safety,+ and avoid any locking concerns with Python's Global Interpreter Lock.+ Audio data processed by :class:`AudioStream` is not available to+ Python code; the only way to interact with the audio stream is through+ the :py:attr:`plugins` attribute.++ .. warning::+ The :class:`AudioStream` class implements a context manager interface+ to ensure that audio streams are never left "dangling" (i.e.: running in+ the background without being stopped).++ While it is possible to call the :meth:`__enter__` method directly to run an+ audio stream in the background, this can make it possible to lose all+ references to the :class:`AudioStream` object, resulting in an audio stream+ that can't be stopped until the Python interpreter exits.++ To run an :class:`AudioStream` in the background, use Python's+ :module:`threading` module to call the :meth:`run` method on a background+ thread, allowing for easier cleanup.++ *Introduced in v0.6.9. Not supported on Linux.*"""def __enter__(self) -> AudioStream: ...@@ -146,35 +198,37 @@ class AudioStream:self,input_device_name: str,output_device_name: str,+ plugins: typing.Optional[pedalboard_native.utils.Chain] = None,sample_rate: float = 44100,buffer_size: int = 512,+ allow_feedback: bool = False,) -> None: ...def __repr__(self) -> str: ...- def stream(self) -> None:+ def run(self) -> None:"""- Stream audio from input to output, through the `plugins` on this AudioStream object, until a KeyboardInterrupt is received.+ Start streaming audio from input to output, passing the audio stream through the `plugins` on this AudioStream object. This call will block the current thread until a KeyboardInterrupt (Ctrl-C) is received."""@property- def pedalboard(self) -> pedalboard_native.utils.Chain:+ def plugins(self) -> pedalboard_native.utils.Chain:"""- The Pedalboard object currently processing the live effects chain.+ The Pedalboard object that this AudioStream will use to process audio."""- @pedalboard.setter- def pedalboard(self, arg1: pedalboard_native.utils.Chain) -> None:+ @plugins.setter+ def plugins(self, arg1: pedalboard_native.utils.Chain) -> None:"""- The Pedalboard object currently processing the live effects chain.+ The Pedalboard object that this AudioStream will use to process audio."""@propertydef running(self) -> bool:"""- True iff this stream is currently streaming live audio from input to output.+ True if this stream is currently streaming live audio from input to output, false otherwise."""input_device_names = ["Peter Sobotβs iPhone Microphone", "MacBook Pro Microphone"]- output_device_names = ["MacBook Pro Speakers"]+ output_device_names = ["DELL U3223QE", "MacBook Pro Speakers"]passclass ReadableAudioFile(AudioFile):