адаптация s13bby/osc под vst и gui. (вайбкод)
вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio. обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
+2043
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,584 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Manages the state of some audio and midi i/o devices.
|
||||
|
||||
This class keeps tracks of a currently-selected audio device, through
|
||||
with which it continuously streams data from an audio callback, as well as
|
||||
one or more midi inputs.
|
||||
|
||||
The idea is that your application will create one global instance of this object,
|
||||
and let it take care of creating and deleting specific types of audio devices
|
||||
internally. So when the device is changed, your callbacks will just keep running
|
||||
without having to worry about this.
|
||||
|
||||
The manager can save and reload all of its device settings as XML, which
|
||||
makes it very easy for you to save and reload the audio setup of your
|
||||
application.
|
||||
|
||||
And to make it easy to let the user change its settings, there's a component
|
||||
to do just that - the AudioDeviceSelectorComponent class, which contains a set of
|
||||
device selection/sample-rate/latency controls.
|
||||
|
||||
To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
|
||||
call addAudioCallback() to register your audio callback with it, and use that to process
|
||||
your audio data.
|
||||
|
||||
The manager also acts as a handy hub for incoming midi messages, allowing a
|
||||
listener to register for messages from either a specific midi device, or from whatever
|
||||
the current default midi input device is. The listener then doesn't have to worry about
|
||||
re-registering with different midi devices if they are changed or deleted.
|
||||
|
||||
And yet another neat trick is that amount of CPU time being used is measured and
|
||||
available with the getCpuUsage() method.
|
||||
|
||||
The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
|
||||
listeners whenever one of its settings is changed.
|
||||
|
||||
@see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioDeviceManager : public ChangeBroadcaster
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a default AudioDeviceManager.
|
||||
|
||||
Initially no audio device will be selected. You should call the initialise() method
|
||||
and register an audio callback with setAudioCallback() before it'll be able to
|
||||
actually make any noise.
|
||||
*/
|
||||
AudioDeviceManager();
|
||||
|
||||
/** Destructor. */
|
||||
~AudioDeviceManager() override;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This structure holds a set of properties describing the current audio setup.
|
||||
|
||||
An AudioDeviceManager uses this class to save/load its current settings, and to
|
||||
specify your preferred options when opening a device.
|
||||
|
||||
@see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
|
||||
*/
|
||||
struct JUCE_API AudioDeviceSetup
|
||||
{
|
||||
/** The name of the audio device used for output.
|
||||
The name has to be one of the ones listed by the AudioDeviceManager's currently
|
||||
selected device type.
|
||||
This may be the same as the input device.
|
||||
*/
|
||||
String outputDeviceName;
|
||||
|
||||
/** The name of the audio device used for input.
|
||||
This may be the same as the output device.
|
||||
*/
|
||||
String inputDeviceName;
|
||||
|
||||
/** The current sample rate.
|
||||
This rate is used for both the input and output devices.
|
||||
A value of 0 indicates that you don't care what rate is used, and the
|
||||
device will choose a sensible rate for you.
|
||||
*/
|
||||
double sampleRate = 0;
|
||||
|
||||
/** The buffer size, in samples.
|
||||
This buffer size is used for both the input and output devices.
|
||||
A value of 0 indicates the default buffer size.
|
||||
*/
|
||||
int bufferSize = 0;
|
||||
|
||||
/** The set of active input channels.
|
||||
The bits that are set in this array indicate the channels of the
|
||||
input device that are active.
|
||||
If useDefaultInputChannels is true, this value is ignored.
|
||||
*/
|
||||
BigInteger inputChannels;
|
||||
|
||||
/** If this is true, it indicates that the inputChannels array
|
||||
should be ignored, and instead, the device's default channels
|
||||
should be used.
|
||||
*/
|
||||
bool useDefaultInputChannels = true;
|
||||
|
||||
/** The set of active output channels.
|
||||
The bits that are set in this array indicate the channels of the
|
||||
input device that are active.
|
||||
If useDefaultOutputChannels is true, this value is ignored.
|
||||
*/
|
||||
BigInteger outputChannels;
|
||||
|
||||
/** If this is true, it indicates that the outputChannels array
|
||||
should be ignored, and instead, the device's default channels
|
||||
should be used.
|
||||
*/
|
||||
bool useDefaultOutputChannels = true;
|
||||
|
||||
bool operator== (const AudioDeviceSetup&) const;
|
||||
bool operator!= (const AudioDeviceSetup&) const;
|
||||
};
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/** Opens a set of audio devices ready for use.
|
||||
|
||||
This will attempt to open either a default audio device, or one that was
|
||||
previously saved as XML.
|
||||
|
||||
@param maxNumInputChannelsNeeded the maximum number of input channels your app would like to
|
||||
use (the actual number of channels opened may be less than
|
||||
the number requested)
|
||||
@param maxNumOutputChannelsNeeded the maximum number of output channels your app would like to
|
||||
use (the actual number of channels opened may be less than
|
||||
the number requested)
|
||||
@param savedState either a previously-saved state that was produced
|
||||
by createStateXml(), or nullptr if you want the manager
|
||||
to choose the best device to open.
|
||||
@param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
|
||||
fails to open, then a default device will be used
|
||||
instead. If false, then on failure, no device is
|
||||
opened.
|
||||
@param preferredDefaultDeviceName if this is not empty, and there's a device with this
|
||||
name, then that will be used as the default device
|
||||
(assuming that there wasn't one specified in the XML).
|
||||
The string can actually be a simple wildcard, containing "*"
|
||||
and "?" characters
|
||||
@param preferredSetupOptions if this is non-null, the structure will be used as the
|
||||
set of preferred settings when opening the device. If you
|
||||
use this parameter, the preferredDefaultDeviceName
|
||||
field will be ignored. If you set the outputDeviceName
|
||||
or inputDeviceName data members of the AudioDeviceSetup
|
||||
to empty strings, then a default device will be used.
|
||||
|
||||
|
||||
@returns an error message if anything went wrong, or an empty string if it worked ok.
|
||||
*/
|
||||
String initialise (int maxNumInputChannelsNeeded,
|
||||
int maxNumOutputChannelsNeeded,
|
||||
const XmlElement* savedState,
|
||||
bool selectDefaultDeviceOnFailure,
|
||||
const String& preferredDefaultDeviceName = String(),
|
||||
const AudioDeviceSetup* preferredSetupOptions = nullptr);
|
||||
|
||||
/** Resets everything to a default device setup, clearing any stored settings. */
|
||||
String initialiseWithDefaultDevices (int numInputChannelsNeeded,
|
||||
int numOutputChannelsNeeded);
|
||||
|
||||
/** Returns some XML representing the current state of the manager.
|
||||
|
||||
This stores the current device, its samplerate, block size, etc, and
|
||||
can be restored later with initialise().
|
||||
|
||||
Note that this can return a null pointer if no settings have been explicitly changed
|
||||
(i.e. if the device manager has just been left in its default state).
|
||||
*/
|
||||
std::unique_ptr<XmlElement> createStateXml() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the current device properties that are in use.
|
||||
@see setAudioDeviceSetup
|
||||
*/
|
||||
AudioDeviceSetup getAudioDeviceSetup() const;
|
||||
|
||||
/** Returns the current device properties that are in use.
|
||||
This is an old method, kept around for compatibility, but you should prefer the new
|
||||
version which returns the result rather than taking an out-parameter.
|
||||
@see getAudioDeviceSetup()
|
||||
*/
|
||||
void getAudioDeviceSetup (AudioDeviceSetup& result) const;
|
||||
|
||||
/** Changes the current device or its settings.
|
||||
|
||||
If you want to change a device property, like the current sample rate or
|
||||
block size, you can call getAudioDeviceSetup() to retrieve the current
|
||||
settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
|
||||
and pass it back into this method to apply the new settings.
|
||||
|
||||
@param newSetup the settings that you'd like to use.
|
||||
If you don't need an input or output device, set the
|
||||
inputDeviceName or outputDeviceName data members respectively
|
||||
to empty strings. Note that this behaviour differs from
|
||||
the behaviour of initialise().
|
||||
@param treatAsChosenDevice if this is true and if the device opens correctly, these new
|
||||
settings will be taken as having been explicitly chosen by the
|
||||
user, and the next time createStateXml() is called, these settings
|
||||
will be returned. If it's false, then the device is treated as a
|
||||
temporary or default device, and a call to createStateXml() will
|
||||
return either the last settings that were made with treatAsChosenDevice
|
||||
as true, or the last XML settings that were passed into initialise().
|
||||
@returns an error message if anything went wrong, or an empty string if it worked ok.
|
||||
|
||||
@see getAudioDeviceSetup
|
||||
*/
|
||||
String setAudioDeviceSetup (const AudioDeviceSetup& newSetup, bool treatAsChosenDevice);
|
||||
|
||||
|
||||
/** Returns the currently-active audio device. */
|
||||
AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice.get(); }
|
||||
|
||||
/** Returns the type of audio device currently in use.
|
||||
@see setCurrentAudioDeviceType
|
||||
*/
|
||||
String getCurrentAudioDeviceType() const { return currentDeviceType; }
|
||||
|
||||
/** Returns the currently active audio device type object.
|
||||
Don't keep a copy of this pointer - it's owned by the device manager and could
|
||||
change at any time.
|
||||
*/
|
||||
AudioIODeviceType* getCurrentDeviceTypeObject() const;
|
||||
|
||||
/** Changes the class of audio device being used.
|
||||
|
||||
This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
|
||||
this because there's only one type: CoreAudio.
|
||||
|
||||
For a list of types, see getAvailableDeviceTypes().
|
||||
*/
|
||||
void setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice);
|
||||
|
||||
/** Returns the current audio device workgroup, if supported. */
|
||||
AudioWorkgroup getDeviceAudioWorkgroup() const;
|
||||
|
||||
/** Closes the currently-open device.
|
||||
You can call restartLastAudioDevice() later to reopen it in the same state
|
||||
that it was just in.
|
||||
*/
|
||||
void closeAudioDevice();
|
||||
|
||||
/** Tries to reload the last audio device that was running.
|
||||
|
||||
Note that this only reloads the last device that was running before
|
||||
closeAudioDevice() was called - it doesn't reload any kind of saved-state,
|
||||
and can only be called after a device has been opened with setAudioDeviceSetup().
|
||||
|
||||
If a device is already open, this call will do nothing.
|
||||
*/
|
||||
void restartLastAudioDevice();
|
||||
|
||||
//==============================================================================
|
||||
/** Registers an audio callback to be used.
|
||||
|
||||
The manager will redirect callbacks from whatever audio device is currently
|
||||
in use to all registered callback objects. If more than one callback is
|
||||
active, they will all be given the same input data, and their outputs will
|
||||
be summed.
|
||||
|
||||
If necessary, this method will invoke audioDeviceAboutToStart() on the callback
|
||||
object before returning.
|
||||
|
||||
To remove a callback, use removeAudioCallback().
|
||||
*/
|
||||
void addAudioCallback (AudioIODeviceCallback* newCallback);
|
||||
|
||||
/** Deregisters a previously added callback.
|
||||
|
||||
If necessary, this method will invoke audioDeviceStopped() on the callback
|
||||
object before returning.
|
||||
|
||||
@see addAudioCallback
|
||||
*/
|
||||
void removeAudioCallback (AudioIODeviceCallback* callback);
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the average proportion of available CPU being spent inside the audio callbacks.
|
||||
@returns A value between 0 and 1.0 to indicate the approximate proportion of CPU
|
||||
time spent in the callbacks.
|
||||
*/
|
||||
double getCpuUsage() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Enables or disables a midi input device.
|
||||
|
||||
The list of devices can be obtained with the MidiInput::getAvailableDevices() method.
|
||||
|
||||
Any incoming messages from enabled input devices will be forwarded on to all the
|
||||
listeners that have been registered with the addMidiInputDeviceCallback() method. They
|
||||
can either register for messages from a particular device, or from just the "default"
|
||||
midi input.
|
||||
|
||||
Routing the midi input via an AudioDeviceManager means that when a listener
|
||||
registers for the default midi input, this default device can be changed by the
|
||||
manager without the listeners having to know about it or re-register.
|
||||
|
||||
It also means that a listener can stay registered for a midi input that is disabled
|
||||
or not present, so that when the input is re-enabled, the listener will start
|
||||
receiving messages again.
|
||||
|
||||
@see addMidiInputDeviceCallback, isMidiInputDeviceEnabled
|
||||
*/
|
||||
void setMidiInputDeviceEnabled (const String& deviceIdentifier, bool enabled);
|
||||
|
||||
/** Returns true if a given midi input device is being used.
|
||||
|
||||
@see setMidiInputDeviceEnabled
|
||||
*/
|
||||
bool isMidiInputDeviceEnabled (const String& deviceIdentifier) const;
|
||||
|
||||
/** Registers a listener for callbacks when midi events arrive from a midi input.
|
||||
|
||||
The device identifier can be empty to indicate that it wants to receive all incoming
|
||||
events from all the enabled MIDI inputs. Or it can be the identifier of one of the
|
||||
MIDI input devices if it just wants the events from that device. (see
|
||||
MidiInput::getAvailableDevices() for the list of devices).
|
||||
|
||||
Only devices which are enabled (see the setMidiInputDeviceEnabled() method) will have their
|
||||
events forwarded on to listeners.
|
||||
*/
|
||||
void addMidiInputDeviceCallback (const String& deviceIdentifier,
|
||||
MidiInputCallback* callback);
|
||||
|
||||
/** Removes a listener that was previously registered with addMidiInputDeviceCallback(). */
|
||||
void removeMidiInputDeviceCallback (const String& deviceIdentifier,
|
||||
MidiInputCallback* callback);
|
||||
|
||||
//==============================================================================
|
||||
/** Sets a midi output device to use as the default.
|
||||
|
||||
The list of devices can be obtained with the MidiOutput::getAvailableDevices() method.
|
||||
|
||||
The specified device will be opened automatically and can be retrieved with the
|
||||
getDefaultMidiOutput() method.
|
||||
|
||||
Pass in an empty string to deselect all devices. For the default device, you
|
||||
can use MidiOutput::getDefaultDevice().
|
||||
|
||||
@see getDefaultMidiOutput, getDefaultMidiOutputIdentifier
|
||||
*/
|
||||
void setDefaultMidiOutputDevice (const String& deviceIdentifier);
|
||||
|
||||
/** Returns the name of the default midi output.
|
||||
|
||||
@see setDefaultMidiOutputDevice, getDefaultMidiOutput
|
||||
*/
|
||||
const String& getDefaultMidiOutputIdentifier() const noexcept { return defaultMidiOutputDeviceInfo.identifier; }
|
||||
|
||||
/** Returns the current default midi output device. If no device has been selected, or the
|
||||
device can't be opened, this will return nullptr.
|
||||
|
||||
@see getDefaultMidiOutputIdentifier
|
||||
*/
|
||||
MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput.get(); }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a list of the types of device supported. */
|
||||
const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
|
||||
|
||||
/** Creates a list of available types.
|
||||
|
||||
This will add a set of new AudioIODeviceType objects to the specified list, to
|
||||
represent each available types of device.
|
||||
|
||||
You can override this if your app needs to do something specific, like avoid
|
||||
using DirectSound devices, etc.
|
||||
*/
|
||||
virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
|
||||
|
||||
/** Adds a new device type to the list of types. */
|
||||
void addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType);
|
||||
|
||||
/** Removes a previously added device type from the manager. */
|
||||
void removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove);
|
||||
|
||||
//==============================================================================
|
||||
/** Plays a beep through the current audio device.
|
||||
|
||||
This is here to allow the audio setup UI panels to easily include a "test"
|
||||
button so that the user can check where the audio is coming from.
|
||||
*/
|
||||
void playTestSound();
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A simple reference-counted struct that holds a level-meter value that can be read
|
||||
using getCurrentLevel().
|
||||
|
||||
This is used to ensure that the level processing code is only executed when something
|
||||
holds a reference to one of these objects and will be bypassed otherwise.
|
||||
|
||||
@see getInputLevelGetter, getOutputLevelGetter
|
||||
*/
|
||||
struct LevelMeter : public ReferenceCountedObject
|
||||
{
|
||||
LevelMeter() noexcept;
|
||||
double getCurrentLevel() const noexcept;
|
||||
|
||||
using Ptr = ReferenceCountedObjectPtr<LevelMeter>;
|
||||
|
||||
private:
|
||||
friend class AudioDeviceManager;
|
||||
|
||||
Atomic<float> level { 0 };
|
||||
void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
|
||||
};
|
||||
|
||||
/** Returns a reference-counted object that can be used to get the current input level.
|
||||
|
||||
You need to store this object locally to ensure that the reference count is incremented
|
||||
and decremented properly. The current input level value can be read using getCurrentLevel().
|
||||
*/
|
||||
LevelMeter::Ptr getInputLevelGetter() noexcept { return inputLevelGetter; }
|
||||
|
||||
/** Returns a reference-counted object that can be used to get the current output level.
|
||||
|
||||
You need to store this object locally to ensure that the reference count is incremented
|
||||
and decremented properly. The current output level value can be read using getCurrentLevel().
|
||||
*/
|
||||
LevelMeter::Ptr getOutputLevelGetter() noexcept { return outputLevelGetter; }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the a lock that can be used to synchronise access to the audio callback.
|
||||
Obviously while this is locked, you're blocking the audio thread from running, so
|
||||
it must only be used for very brief periods when absolutely necessary.
|
||||
*/
|
||||
CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
|
||||
|
||||
/** Returns the a lock that can be used to synchronise access to the midi callback.
|
||||
Obviously while this is locked, you're blocking the midi system from running, so
|
||||
it must only be used for very brief periods when absolutely necessary.
|
||||
*/
|
||||
CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of under- or over runs reported.
|
||||
|
||||
This method will use the underlying device's native getXRunCount if it supports
|
||||
it. Otherwise it will estimate the number of under-/overruns by measuring the
|
||||
time it spent in the audio callback.
|
||||
*/
|
||||
int getXRunCount() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
[[deprecated ("Use setMidiInputDeviceEnabled instead.")]]
|
||||
void setMidiInputEnabled (const String&, bool);
|
||||
[[deprecated ("Use isMidiInputDeviceEnabled instead.")]]
|
||||
bool isMidiInputEnabled (const String&) const;
|
||||
[[deprecated ("Use addMidiInputDeviceCallback instead.")]]
|
||||
void addMidiInputCallback (const String&, MidiInputCallback*);
|
||||
[[deprecated ("Use removeMidiInputDeviceCallback instead.")]]
|
||||
void removeMidiInputCallback (const String&, MidiInputCallback*);
|
||||
[[deprecated ("Use setDefaultMidiOutputDevice instead.")]]
|
||||
void setDefaultMidiOutput (const String&);
|
||||
[[deprecated ("Use getDefaultMidiOutputIdentifier instead.")]]
|
||||
const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputDeviceInfo.name; }
|
||||
/** @endcond */
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
OwnedArray<AudioIODeviceType> availableDeviceTypes;
|
||||
OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
|
||||
|
||||
AudioDeviceSetup currentSetup;
|
||||
std::unique_ptr<AudioIODevice> currentAudioDevice;
|
||||
Array<AudioIODeviceCallback*> callbacks;
|
||||
int numInputChansNeeded = 0, numOutputChansNeeded = 2;
|
||||
String preferredDeviceName, currentDeviceType;
|
||||
std::unique_ptr<XmlElement> lastExplicitSettings;
|
||||
mutable bool listNeedsScanning = true;
|
||||
AudioBuffer<float> tempBuffer;
|
||||
MidiDeviceListConnection midiDeviceListConnection = MidiDeviceListConnection::make ([this]
|
||||
{
|
||||
midiDeviceListChanged();
|
||||
});
|
||||
|
||||
struct MidiCallbackInfo
|
||||
{
|
||||
String deviceIdentifier;
|
||||
MidiInputCallback* callback;
|
||||
};
|
||||
|
||||
Array<MidiDeviceInfo> midiDeviceInfosFromXml;
|
||||
std::vector<std::unique_ptr<MidiInput>> enabledMidiInputs;
|
||||
Array<MidiCallbackInfo> midiCallbacks;
|
||||
|
||||
MidiDeviceInfo defaultMidiOutputDeviceInfo;
|
||||
std::unique_ptr<MidiOutput> defaultMidiOutput;
|
||||
CriticalSection audioCallbackLock, midiCallbackLock;
|
||||
|
||||
std::unique_ptr<AudioBuffer<float>> testSound;
|
||||
int testSoundPosition = 0;
|
||||
|
||||
AudioProcessLoadMeasurer loadMeasurer;
|
||||
|
||||
LevelMeter::Ptr inputLevelGetter { new LevelMeter() },
|
||||
outputLevelGetter { new LevelMeter() };
|
||||
|
||||
//==============================================================================
|
||||
class CallbackHandler;
|
||||
std::unique_ptr<CallbackHandler> callbackHandler;
|
||||
|
||||
void audioDeviceIOCallbackInt (const float* const* inputChannelData,
|
||||
int totalNumInputChannels,
|
||||
float* const* outputChannelData,
|
||||
int totalNumOutputChannels,
|
||||
int numSamples,
|
||||
const AudioIODeviceCallbackContext& context);
|
||||
void audioDeviceAboutToStartInt (AudioIODevice*);
|
||||
void audioDeviceStoppedInt();
|
||||
void audioDeviceErrorInt (const String&);
|
||||
void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
|
||||
void audioDeviceListChanged();
|
||||
void midiDeviceListChanged();
|
||||
|
||||
void stopDevice();
|
||||
|
||||
void updateXml();
|
||||
|
||||
void updateCurrentSetup();
|
||||
void createDeviceTypesIfNeeded();
|
||||
void scanDevicesIfNeeded();
|
||||
void deleteCurrentDevice();
|
||||
double chooseBestSampleRate (double preferred) const;
|
||||
int chooseBestBufferSize (int preferred) const;
|
||||
void insertDefaultDeviceNames (AudioDeviceSetup&) const;
|
||||
String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
|
||||
String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
|
||||
const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
|
||||
void openLastRequestedMidiDevices (const Array<MidiDeviceInfo>&, const MidiDeviceInfo&);
|
||||
|
||||
AudioIODeviceType* findType (const String& inputName, const String& outputName);
|
||||
AudioIODeviceType* findType (const String& typeName);
|
||||
void pickCurrentDeviceTypeWithDevices();
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
void AudioIODeviceCallback::audioDeviceIOCallbackWithContext ([[maybe_unused]] const float* const* inputChannelData,
|
||||
[[maybe_unused]] int numInputChannels,
|
||||
[[maybe_unused]] float* const* outputChannelData,
|
||||
[[maybe_unused]] int numOutputChannels,
|
||||
[[maybe_unused]] int numSamples,
|
||||
[[maybe_unused]] const AudioIODeviceCallbackContext& context) {}
|
||||
|
||||
//==============================================================================
|
||||
AudioIODevice::AudioIODevice (const String& deviceName, const String& deviceTypeName)
|
||||
: name (deviceName), typeName (deviceTypeName)
|
||||
{
|
||||
}
|
||||
|
||||
AudioIODevice::~AudioIODevice() {}
|
||||
|
||||
void AudioIODeviceCallback::audioDeviceError (const String&) {}
|
||||
bool AudioIODevice::setAudioPreprocessingEnabled (bool) { return false; }
|
||||
bool AudioIODevice::hasControlPanel() const { return false; }
|
||||
int AudioIODevice::getXRunCount() const noexcept { return -1; }
|
||||
|
||||
bool AudioIODevice::showControlPanel()
|
||||
{
|
||||
jassertfalse; // this should only be called for devices which return true from
|
||||
// their hasControlPanel() method.
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,368 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AudioIODevice;
|
||||
|
||||
/**
|
||||
Additional information that may be passed to the AudioIODeviceCallback.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct AudioIODeviceCallbackContext
|
||||
{
|
||||
/** If the host provides this information, this field will be set to point to
|
||||
an integer holding the current value; otherwise, this will be nullptr.
|
||||
*/
|
||||
const uint64_t* hostTimeNs = nullptr;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
One of these is passed to an AudioIODevice object to stream the audio data
|
||||
in and out.
|
||||
|
||||
The AudioIODevice will repeatedly call this class's audioDeviceIOCallbackWithContext()
|
||||
method on its own high-priority audio thread, when it needs to send or receive
|
||||
the next block of data.
|
||||
|
||||
@see AudioIODevice, AudioDeviceManager
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioIODeviceCallback
|
||||
{
|
||||
public:
|
||||
/** Destructor. */
|
||||
virtual ~AudioIODeviceCallback() = default;
|
||||
|
||||
/** Processes a block of incoming and outgoing audio data.
|
||||
|
||||
The subclass's implementation should use the incoming audio for whatever
|
||||
purposes it needs to, and must fill all the output channels with the next
|
||||
block of output data before returning.
|
||||
|
||||
The channel data is arranged with the same array indices as the channel name
|
||||
array returned by AudioIODevice::getOutputChannelNames(), but those channels
|
||||
that aren't specified in AudioIODevice::open() will have a null pointer for their
|
||||
associated channel, so remember to check for this.
|
||||
|
||||
@param inputChannelData a set of arrays containing the audio data for each
|
||||
incoming channel - this data is valid until the function
|
||||
returns. There will be one channel of data for each input
|
||||
channel that was enabled when the audio device was opened
|
||||
(see AudioIODevice::open())
|
||||
@param numInputChannels the number of pointers to channel data in the
|
||||
inputChannelData array.
|
||||
@param outputChannelData a set of arrays which need to be filled with the data
|
||||
that should be sent to each outgoing channel of the device.
|
||||
There will be one channel of data for each output channel
|
||||
that was enabled when the audio device was opened (see
|
||||
AudioIODevice::open())
|
||||
The initial contents of the array is undefined, so the
|
||||
callback function must fill all the channels with zeros if
|
||||
its output is silence. Failing to do this could cause quite
|
||||
an unpleasant noise!
|
||||
@param numOutputChannels the number of pointers to channel data in the
|
||||
outputChannelData array.
|
||||
@param numSamples the number of samples in each channel of the input and
|
||||
output arrays. The number of samples will depend on the
|
||||
audio device's buffer size and will usually remain constant,
|
||||
although this isn't guaranteed. For example, on Android,
|
||||
on devices which support it, Android will chop up your audio
|
||||
processing into several smaller callbacks to ensure higher audio
|
||||
performance. So make sure your code can cope with reasonable
|
||||
changes in the buffer size from one callback to the next.
|
||||
@param context Additional information that may be passed to the
|
||||
AudioIODeviceCallback.
|
||||
*/
|
||||
virtual void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
|
||||
int numInputChannels,
|
||||
float* const* outputChannelData,
|
||||
int numOutputChannels,
|
||||
int numSamples,
|
||||
const AudioIODeviceCallbackContext& context);
|
||||
|
||||
/** Called to indicate that the device is about to start calling back.
|
||||
|
||||
This will be called just before the audio callbacks begin, either when this
|
||||
callback has just been added to an audio device, or after the device has been
|
||||
restarted because of a sample-rate or block-size change.
|
||||
|
||||
You can use this opportunity to find out the sample rate and block size
|
||||
that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
|
||||
and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
|
||||
|
||||
@param device the audio IO device that will be used to drive the callback.
|
||||
Note that if you're going to store this pointer, it is only
|
||||
valid until the next time that audioDeviceStopped is called.
|
||||
*/
|
||||
virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
|
||||
|
||||
/** Called to indicate that the device has stopped. */
|
||||
virtual void audioDeviceStopped() = 0;
|
||||
|
||||
/** This can be overridden to be told if the device generates an error while operating.
|
||||
Be aware that this could be called by any thread! And not all devices perform
|
||||
this callback.
|
||||
*/
|
||||
virtual void audioDeviceError (const String& errorMessage);
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Base class for an audio device with synchronised input and output channels.
|
||||
|
||||
Subclasses of this are used to implement different protocols such as DirectSound,
|
||||
ASIO, CoreAudio, etc.
|
||||
|
||||
To create one of these, you'll need to use the AudioIODeviceType class - see the
|
||||
documentation for that class for more info.
|
||||
|
||||
For an easier way of managing audio devices and their settings, have a look at the
|
||||
AudioDeviceManager class.
|
||||
|
||||
@see AudioIODeviceType, AudioDeviceManager
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioIODevice
|
||||
{
|
||||
public:
|
||||
/** Destructor. */
|
||||
virtual ~AudioIODevice();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the device's name, (as set in the constructor). */
|
||||
const String& getName() const noexcept { return name; }
|
||||
|
||||
/** Returns the type of the device.
|
||||
|
||||
E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
|
||||
*/
|
||||
const String& getTypeName() const noexcept { return typeName; }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the names of all the available output channels on this device.
|
||||
To find out which of these are currently in use, call getActiveOutputChannels().
|
||||
*/
|
||||
virtual StringArray getOutputChannelNames() = 0;
|
||||
|
||||
/** Returns the names of all the available input channels on this device.
|
||||
To find out which of these are currently in use, call getActiveInputChannels().
|
||||
*/
|
||||
virtual StringArray getInputChannelNames() = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** For devices that support a default layout, returns the channels that are enabled in the
|
||||
default layout.
|
||||
|
||||
Returns nullopt if the device doesn't supply a default layout.
|
||||
*/
|
||||
virtual std::optional<BigInteger> getDefaultOutputChannels() const { return {}; }
|
||||
|
||||
/** For devices that support a default layout, returns the channels that are enabled in the
|
||||
default layout.
|
||||
|
||||
Returns nullopt if the device doesn't supply a default layout.
|
||||
*/
|
||||
virtual std::optional<BigInteger> getDefaultInputChannels() const { return {}; }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the set of sample-rates this device supports.
|
||||
@see getCurrentSampleRate
|
||||
*/
|
||||
virtual Array<double> getAvailableSampleRates() = 0;
|
||||
|
||||
/** Returns the set of buffer sizes that are available.
|
||||
@see getCurrentBufferSizeSamples, getDefaultBufferSize
|
||||
*/
|
||||
virtual Array<int> getAvailableBufferSizes() = 0;
|
||||
|
||||
/** Returns the default buffer-size to use.
|
||||
@returns a number of samples
|
||||
@see getAvailableBufferSizes
|
||||
*/
|
||||
virtual int getDefaultBufferSize() = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Tries to open the device ready to play.
|
||||
|
||||
@param inputChannels a BigInteger in which a set bit indicates that the corresponding
|
||||
input channel should be enabled
|
||||
@param outputChannels a BigInteger in which a set bit indicates that the corresponding
|
||||
output channel should be enabled
|
||||
@param sampleRate the sample rate to try to use - to find out which rates are
|
||||
available, see getAvailableSampleRates()
|
||||
@param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
|
||||
sizes, see getAvailableBufferSizes()
|
||||
@returns an error description if there's a problem, or an empty string if it succeeds in
|
||||
opening the device
|
||||
@see close
|
||||
*/
|
||||
virtual String open (const BigInteger& inputChannels,
|
||||
const BigInteger& outputChannels,
|
||||
double sampleRate,
|
||||
int bufferSizeSamples) = 0;
|
||||
|
||||
/** Closes and releases the device if it's open. */
|
||||
virtual void close() = 0;
|
||||
|
||||
/** Returns true if the device is still open.
|
||||
|
||||
A device might spontaneously close itself if something goes wrong, so this checks if
|
||||
it's still open.
|
||||
*/
|
||||
virtual bool isOpen() = 0;
|
||||
|
||||
/** Starts the device actually playing.
|
||||
|
||||
This must be called after the device has been opened.
|
||||
|
||||
@param callback the callback to use for streaming the data.
|
||||
@see AudioIODeviceCallback, open
|
||||
*/
|
||||
virtual void start (AudioIODeviceCallback* callback) = 0;
|
||||
|
||||
/** Stops the device playing.
|
||||
|
||||
Once a device has been started, this will stop it. Any pending calls to the
|
||||
callback class will be flushed before this method returns.
|
||||
*/
|
||||
virtual void stop() = 0;
|
||||
|
||||
/** Returns true if the device is still calling back.
|
||||
|
||||
The device might mysteriously stop, so this checks whether it's
|
||||
still playing.
|
||||
*/
|
||||
virtual bool isPlaying() = 0;
|
||||
|
||||
/** Returns the last error that happened if anything went wrong. */
|
||||
virtual String getLastError() = 0;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the buffer size that the device is currently using.
|
||||
|
||||
If the device isn't actually open, this value doesn't really mean much.
|
||||
*/
|
||||
virtual int getCurrentBufferSizeSamples() = 0;
|
||||
|
||||
/** Returns the sample rate that the device is currently using.
|
||||
|
||||
If the device isn't actually open, this value doesn't really mean much.
|
||||
*/
|
||||
virtual double getCurrentSampleRate() = 0;
|
||||
|
||||
/** Returns the device's current physical bit-depth.
|
||||
|
||||
If the device isn't actually open, this value doesn't really mean much.
|
||||
*/
|
||||
virtual int getCurrentBitDepth() = 0;
|
||||
|
||||
/** Returns a mask showing which of the available output channels are currently
|
||||
enabled.
|
||||
@see getOutputChannelNames
|
||||
*/
|
||||
virtual BigInteger getActiveOutputChannels() const = 0;
|
||||
|
||||
/** Returns a mask showing which of the available input channels are currently
|
||||
enabled.
|
||||
@see getInputChannelNames
|
||||
*/
|
||||
virtual BigInteger getActiveInputChannels() const = 0;
|
||||
|
||||
/** Returns the device's output latency.
|
||||
|
||||
This is the delay in samples between a callback getting a block of data, and
|
||||
that data actually getting played.
|
||||
*/
|
||||
virtual int getOutputLatencyInSamples() = 0;
|
||||
|
||||
/** Returns the device's input latency.
|
||||
|
||||
This is the delay in samples between some audio actually arriving at the soundcard,
|
||||
and the callback getting passed this block of data.
|
||||
*/
|
||||
virtual int getInputLatencyInSamples() = 0;
|
||||
|
||||
/** Returns the workgroup for this device. */
|
||||
virtual AudioWorkgroup getWorkgroup() const { return {}; }
|
||||
|
||||
//==============================================================================
|
||||
/** True if this device can show a pop-up control panel for editing its settings.
|
||||
|
||||
This is generally just true of ASIO devices. If true, you can call showControlPanel()
|
||||
to display it.
|
||||
*/
|
||||
virtual bool hasControlPanel() const;
|
||||
|
||||
/** Shows a device-specific control panel if there is one.
|
||||
|
||||
This should only be called for devices which return true from hasControlPanel().
|
||||
*/
|
||||
virtual bool showControlPanel();
|
||||
|
||||
/** On devices which support it, this allows automatic gain control or other
|
||||
mic processing to be disabled.
|
||||
If the device doesn't support this operation, it'll return false.
|
||||
*/
|
||||
virtual bool setAudioPreprocessingEnabled (bool shouldBeEnabled);
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of under- or over runs reported by the OS since
|
||||
playback/recording has started.
|
||||
|
||||
This number may be different than determining the Xrun count manually (by
|
||||
measuring the time spent in the audio callback) as the OS may be doing
|
||||
some buffering internally - especially on mobile devices.
|
||||
|
||||
Returns -1 if playback/recording has not started yet or if getting the underrun
|
||||
count is not supported for this device (Android SDK 23 and lower).
|
||||
*/
|
||||
virtual int getXRunCount() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
protected:
|
||||
/** Creates a device, setting its name and type member variables. */
|
||||
AudioIODevice (const String& deviceName,
|
||||
const String& typeName);
|
||||
|
||||
/** @internal */
|
||||
String name, typeName;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
AudioIODeviceType::AudioIODeviceType (const String& name)
|
||||
: typeName (name)
|
||||
{
|
||||
}
|
||||
|
||||
AudioIODeviceType::~AudioIODeviceType()
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void AudioIODeviceType::addListener (Listener* l) { listeners.add (l); }
|
||||
void AudioIODeviceType::removeListener (Listener* l) { listeners.remove (l); }
|
||||
|
||||
void AudioIODeviceType::callDeviceChangeListeners()
|
||||
{
|
||||
listeners.call ([] (Listener& l) { l.audioDeviceListChanged(); });
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_MAC
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio() { return new CoreAudioClasses::CoreAudioIODeviceType(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_IOS
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio() { return new iOSAudioIODeviceType(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_WINDOWS && JUCE_WASAPI
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode deviceMode)
|
||||
{
|
||||
return new WasapiClasses::WASAPIAudioIODeviceType (deviceMode);
|
||||
}
|
||||
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (bool exclusiveMode)
|
||||
{
|
||||
return createAudioIODeviceType_WASAPI (exclusiveMode ? WASAPIDeviceMode::exclusive
|
||||
: WASAPIDeviceMode::shared);
|
||||
}
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode) { return nullptr; }
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (bool) { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_WINDOWS && JUCE_DIRECTSOUND
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound() { return new DSoundAudioIODeviceType(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_WINDOWS && JUCE_ASIO
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO() { return new ASIOAudioIODeviceType(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if (JUCE_LINUX || JUCE_BSD) && JUCE_ALSA
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA() { return createAudioIODeviceType_ALSA_PCMDevices(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if (JUCE_LINUX || JUCE_BSD || JUCE_MAC || JUCE_WINDOWS) && JUCE_JACK
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK() { return new JackAudioIODeviceType(); }
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_ANDROID
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()
|
||||
{
|
||||
#if JUCE_USE_ANDROID_OBOE
|
||||
if (isOboeAvailable())
|
||||
return nullptr;
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_ANDROID_OPENSLES
|
||||
if (isOpenSLAvailable())
|
||||
return nullptr;
|
||||
#endif
|
||||
|
||||
return new AndroidAudioIODeviceType();
|
||||
}
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_ANDROID && JUCE_USE_ANDROID_OPENSLES
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES()
|
||||
{
|
||||
return isOpenSLAvailable() ? new OpenSLAudioDeviceType() : nullptr;
|
||||
}
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES() { return nullptr; }
|
||||
#endif
|
||||
|
||||
#if JUCE_ANDROID && JUCE_USE_ANDROID_OBOE
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Oboe()
|
||||
{
|
||||
return isOboeAvailable() ? new OboeAudioIODeviceType() : nullptr;
|
||||
}
|
||||
#else
|
||||
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Oboe() { return nullptr; }
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
|
||||
|
||||
To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
|
||||
method. Each of the objects returned can then be used to list the available
|
||||
devices of that type. E.g.
|
||||
@code
|
||||
OwnedArray<AudioIODeviceType> types;
|
||||
myAudioDeviceManager.createAudioDeviceTypes (types);
|
||||
|
||||
for (int i = 0; i < types.size(); ++i)
|
||||
{
|
||||
String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
|
||||
|
||||
types[i]->scanForDevices(); // This must be called before getting the list of devices
|
||||
|
||||
StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
|
||||
|
||||
for (int j = 0; j < deviceNames.size(); ++j)
|
||||
{
|
||||
AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
|
||||
|
||||
...
|
||||
}
|
||||
}
|
||||
@endcode
|
||||
|
||||
For an easier way of managing audio devices and their settings, have a look at the
|
||||
AudioDeviceManager class.
|
||||
|
||||
@see AudioIODevice, AudioDeviceManager
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioIODeviceType
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Returns the name of this type of driver that this object manages.
|
||||
|
||||
This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
|
||||
*/
|
||||
const String& getTypeName() const noexcept { return typeName; }
|
||||
|
||||
//==============================================================================
|
||||
/** Refreshes the object's cached list of known devices.
|
||||
|
||||
This must be called at least once before calling getDeviceNames() or any of
|
||||
the other device creation methods.
|
||||
*/
|
||||
virtual void scanForDevices() = 0;
|
||||
|
||||
/** Returns the list of available devices of this type.
|
||||
|
||||
The scanForDevices() method must have been called to create this list.
|
||||
|
||||
@param wantInputNames for devices which have separate inputs and outputs
|
||||
this determines which list of names is returned
|
||||
*/
|
||||
virtual StringArray getDeviceNames (bool wantInputNames = false) const = 0;
|
||||
|
||||
/** Returns the name of the default device.
|
||||
|
||||
This will be one of the names from the getDeviceNames() list.
|
||||
|
||||
@param forInput if true, this means that a default input device should be
|
||||
returned; if false, it should return the default output
|
||||
*/
|
||||
virtual int getDefaultDeviceIndex (bool forInput) const = 0;
|
||||
|
||||
/** Returns the index of a given device in the list of device names.
|
||||
If asInput is true, it shows the index in the inputs list, otherwise it
|
||||
looks for it in the outputs list.
|
||||
*/
|
||||
virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
|
||||
|
||||
/** Returns true if two different devices can be used for the input and output.
|
||||
*/
|
||||
virtual bool hasSeparateInputsAndOutputs() const = 0;
|
||||
|
||||
/** Creates one of the devices of this type.
|
||||
|
||||
The deviceName must be one of the strings returned by getDeviceNames(), and
|
||||
scanForDevices() must have been called before this method is used.
|
||||
*/
|
||||
virtual AudioIODevice* createDevice (const String& outputDeviceName,
|
||||
const String& inputDeviceName) = 0;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A class for receiving events when audio devices are inserted or removed.
|
||||
|
||||
You can register an AudioIODeviceType::Listener with an AudioIODeviceType object
|
||||
using the AudioIODeviceType::addListener() method, and it will be called when
|
||||
devices of that type are added or removed.
|
||||
|
||||
@see AudioIODeviceType::addListener, AudioIODeviceType::removeListener
|
||||
*/
|
||||
class Listener
|
||||
{
|
||||
public:
|
||||
virtual ~Listener() = default;
|
||||
|
||||
/** Called when the list of available audio devices changes. */
|
||||
virtual void audioDeviceListChanged() = 0;
|
||||
};
|
||||
|
||||
/** Adds a listener that will be called when this type of device is added or
|
||||
removed from the system.
|
||||
*/
|
||||
void addListener (Listener* listener);
|
||||
|
||||
/** Removes a listener that was previously added with addListener(). */
|
||||
void removeListener (Listener* listener);
|
||||
|
||||
//==============================================================================
|
||||
/** Destructor. */
|
||||
virtual ~AudioIODeviceType();
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a CoreAudio device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
|
||||
/** Creates an iOS device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
|
||||
/** Creates a WASAPI device type in the specified mode if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_WASAPI (WASAPIDeviceMode deviceMode);
|
||||
/** Creates a DirectSound device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_DirectSound();
|
||||
/** Creates an ASIO device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_ASIO();
|
||||
/** Creates an ALSA device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_ALSA();
|
||||
/** Creates a JACK device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_JACK();
|
||||
/** Creates an Android device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_Android();
|
||||
/** Creates an Android OpenSLES device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_OpenSLES();
|
||||
/** Creates an Oboe device type if it's available on this platform, or returns null. */
|
||||
static AudioIODeviceType* createAudioIODeviceType_Oboe();
|
||||
|
||||
/** @cond */
|
||||
[[deprecated ("You should call the method which takes a WASAPIDeviceMode instead.")]]
|
||||
static AudioIODeviceType* createAudioIODeviceType_WASAPI (bool exclusiveMode);
|
||||
/** @endcond */
|
||||
|
||||
protected:
|
||||
explicit AudioIODeviceType (const String& typeName);
|
||||
|
||||
/** Synchronously calls all the registered device list change listeners. */
|
||||
void callDeviceChangeListeners();
|
||||
|
||||
private:
|
||||
String typeName;
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::SampleRateHelpers
|
||||
{
|
||||
|
||||
static inline const std::vector<double>& getCommonSampleRates()
|
||||
{
|
||||
static auto sampleRates = std::invoke ([]
|
||||
{
|
||||
std::vector<double> result;
|
||||
constexpr double baseRates[] = { 8000.0, 11025.0, 12000.0 };
|
||||
constexpr double maxRate = 768000.0;
|
||||
|
||||
for (auto rate : baseRates)
|
||||
for (; rate <= maxRate; rate *= 2)
|
||||
result.insert (std::upper_bound (result.begin(), result.end(), rate),
|
||||
rate);
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
return sampleRates;
|
||||
}
|
||||
|
||||
} // namespace juce::SampleRateHelpers
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Contains functions to control the system's master volume.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API SystemAudioVolume
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Returns the operating system's current volume level in the range 0 to 1.0 */
|
||||
static float JUCE_CALLTYPE getGain();
|
||||
|
||||
/** Attempts to set the operating system's current volume level.
|
||||
@param newGain the level, between 0 and 1.0
|
||||
@returns true if the operation succeeds
|
||||
*/
|
||||
static bool JUCE_CALLTYPE setGain (float newGain);
|
||||
|
||||
/** Returns true if the system's audio output is currently muted. */
|
||||
static bool JUCE_CALLTYPE isMuted();
|
||||
|
||||
/** Attempts to mute the operating system's audio output.
|
||||
@param shouldBeMuted true if you want it to be muted
|
||||
@returns true if the operation succeeds
|
||||
*/
|
||||
static bool JUCE_CALLTYPE setMuted (bool shouldBeMuted);
|
||||
|
||||
private:
|
||||
SystemAudioVolume(); // Don't instantiate this class, just call its static fns.
|
||||
JUCE_DECLARE_NON_COPYABLE (SystemAudioVolume)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,292 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#ifdef JUCE_AUDIO_DEVICES_H_INCLUDED
|
||||
/* When you add this cpp file to your project, you mustn't include it in a file where you've
|
||||
already included any other headers - just put it inside a file on its own, possibly with your config
|
||||
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
|
||||
header files that the compiler may be using.
|
||||
*/
|
||||
#error "Incorrect use of JUCE cpp file"
|
||||
#endif
|
||||
|
||||
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
|
||||
#define JUCE_CORE_INCLUDE_COM_SMART_PTR 1
|
||||
#define JUCE_CORE_INCLUDE_JNI_HELPERS 1
|
||||
#define JUCE_CORE_INCLUDE_NATIVE_HEADERS 1
|
||||
#define JUCE_EVENTS_INCLUDE_WIN32_MESSAGE_WINDOW 1
|
||||
|
||||
#ifndef JUCE_USE_WINRT_MIDI
|
||||
#define JUCE_USE_WINRT_MIDI 0
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_WINRT_MIDI
|
||||
#define JUCE_EVENTS_INCLUDE_WINRT_WRAPPER 1
|
||||
#endif
|
||||
|
||||
#include "juce_audio_devices.h"
|
||||
|
||||
#include "midi_io/juce_WaitFreeListeners.h"
|
||||
#include "midi_io/juce_WaitFreeListeners.cpp"
|
||||
#include "midi_io/juce_MidiDeviceListConnectionBroadcaster.cpp"
|
||||
|
||||
#include "midi_io/ump/juce_UMPBlock.cpp"
|
||||
#include "midi_io/ump/juce_UMPIOHelpers.cpp"
|
||||
#include "midi_io/ump/juce_UMPInput.cpp"
|
||||
#include "midi_io/ump/juce_UMPOutput.cpp"
|
||||
#include "midi_io/ump/juce_UMPLegacyVirtualInput.cpp"
|
||||
#include "midi_io/ump/juce_UMPLegacyVirtualOutput.cpp"
|
||||
#include "midi_io/ump/juce_UMPVirtualEndpoint.cpp"
|
||||
#include "midi_io/ump/juce_UMPSession.cpp"
|
||||
#include "midi_io/ump/juce_UMPEndpoint.cpp"
|
||||
#include "midi_io/ump/juce_UMPStaticDeviceInfo.cpp"
|
||||
#include "midi_io/ump/juce_UMPEndpoints.cpp"
|
||||
#include "midi_io/ump/juce_UMPEndpointId.cpp"
|
||||
|
||||
#include "audio_io/juce_SampleRateHelpers.cpp"
|
||||
#include "midi_io/juce_MidiDevices.cpp"
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_MAC || JUCE_IOS
|
||||
#include <juce_audio_basics/native/juce_CoreAudioTimeConversions_mac.h>
|
||||
#include <juce_audio_basics/native/juce_AudioWorkgroup_mac.h>
|
||||
#endif
|
||||
|
||||
#if JUCE_MAC
|
||||
#define Point CarbonDummyPointName
|
||||
#define Component CarbonDummyCompName
|
||||
#import <CoreAudio/AudioHardware.h>
|
||||
#import <CoreMIDI/CoreMIDI.h>
|
||||
#import <AudioToolbox/AudioServices.h>
|
||||
#undef Point
|
||||
#undef Component
|
||||
|
||||
#include "native/juce_CoreAudio_mac.cpp"
|
||||
|
||||
#elif JUCE_IOS
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#import <CoreMIDI/CoreMIDI.h>
|
||||
|
||||
#if JUCE_MODULE_AVAILABLE_juce_graphics
|
||||
#include <juce_graphics/native/juce_CoreGraphicsHelpers_mac.h>
|
||||
#endif
|
||||
|
||||
#include "native/juce_Audio_ios.cpp"
|
||||
|
||||
//==============================================================================
|
||||
#elif JUCE_WINDOWS
|
||||
#include <cfgmgr32.h>
|
||||
|
||||
#if ! JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES
|
||||
#pragma comment (lib, "cfgmgr32.lib")
|
||||
#endif
|
||||
|
||||
#if JUCE_WASAPI
|
||||
#include <mmreg.h>
|
||||
#include "native/juce_WASAPI_windows.cpp"
|
||||
#endif
|
||||
|
||||
#if JUCE_DIRECTSOUND
|
||||
#include "native/juce_DirectSound_windows.cpp"
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_WINRT_MIDI && (JUCE_MSVC || JUCE_CLANG)
|
||||
/* If you cannot find any of the header files below then you are probably
|
||||
attempting to use the Windows 10 Bluetooth Low Energy API. For this to work you
|
||||
need to install version 10.0.14393.0 of the Windows Standalone SDK and you may
|
||||
need to add the path to the WinRT headers to your build system. This path should
|
||||
have the form "C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\winrt".
|
||||
|
||||
Also please note that Microsoft's Bluetooth MIDI stack has multiple issues, so
|
||||
this API is EXPERIMENTAL - use at your own risk!
|
||||
*/
|
||||
#include <windows.devices.h>
|
||||
#include <windows.devices.midi.h>
|
||||
#include <windows.devices.enumeration.h>
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4265)
|
||||
#include <wrl/event.h>
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4467)
|
||||
#include <robuffer.h>
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
#endif
|
||||
|
||||
#if JUCE_ASIO
|
||||
#if JUCE_ASIO_USE_EXTERNAL_SDK
|
||||
#include <iasiodrv.h>
|
||||
#else
|
||||
#include <juce_audio_devices/native/asio/iasiodrv.h>
|
||||
#endif
|
||||
#include "native/juce_ASIO_windows.cpp"
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
#elif JUCE_LINUX || JUCE_BSD
|
||||
#if JUCE_ALSA
|
||||
/* Got an include error here? If so, you've either not got ALSA installed, or you've
|
||||
not got your paths set up correctly to find its header files.
|
||||
|
||||
The package you need to install to get ASLA support is "libasound2-dev".
|
||||
|
||||
If you don't have the ALSA library and don't want to build JUCE with audio support,
|
||||
just set the JUCE_ALSA flag to 0.
|
||||
*/
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wzero-length-array")
|
||||
#include <alsa/asoundlib.h>
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
#include "native/juce_ALSA_weak_linux.h"
|
||||
#include "native/juce_ALSA_linux.cpp"
|
||||
#endif
|
||||
#undef SIZEOF
|
||||
|
||||
//==============================================================================
|
||||
#elif JUCE_ANDROID
|
||||
|
||||
// Currently we're just using this for enum values
|
||||
#include <amidi/AMidi.h>
|
||||
|
||||
namespace juce
|
||||
{
|
||||
using RealtimeThreadFactory = pthread_t (*) (void* (*) (void*), void*);
|
||||
RealtimeThreadFactory getAndroidRealtimeThreadFactory();
|
||||
} // namespace juce
|
||||
|
||||
#include "native/juce_Audio_android.cpp"
|
||||
|
||||
#if JUCE_USE_ANDROID_OPENSLES || JUCE_USE_ANDROID_OBOE
|
||||
#include "native/juce_HighPerformanceAudioHelpers_android.h"
|
||||
|
||||
#if JUCE_USE_ANDROID_OPENSLES
|
||||
#include <SLES/OpenSLES.h>
|
||||
#include <SLES/OpenSLES_Android.h>
|
||||
#include <SLES/OpenSLES_AndroidConfiguration.h>
|
||||
#include "native/juce_OpenSL_android.cpp"
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_ANDROID_OBOE
|
||||
#if JUCE_USE_ANDROID_OPENSLES
|
||||
#error "Oboe cannot be enabled at the same time as openSL! Please disable JUCE_USE_ANDROID_OPENSLES"
|
||||
#endif
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wunused-parameter",
|
||||
"-Wzero-as-null-pointer-constant",
|
||||
"-Winconsistent-missing-destructor-override",
|
||||
"-Wshadow-field-in-constructor",
|
||||
"-Wshadow-field",
|
||||
"-Wsign-conversion",
|
||||
"-Wswitch-enum",
|
||||
"-Wshorten-64-to-32")
|
||||
#include <oboe/Oboe.h>
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
#include "native/juce_Oboe_android.cpp"
|
||||
#endif
|
||||
#else
|
||||
// No audio library, so no way to create realtime threads.
|
||||
namespace juce
|
||||
{
|
||||
RealtimeThreadFactory getAndroidRealtimeThreadFactory() { return nullptr; }
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#if (JUCE_LINUX || JUCE_BSD || JUCE_MAC || JUCE_WINDOWS) && JUCE_JACK
|
||||
/* Got an include error here? If so, you've either not got jack-audio-connection-kit
|
||||
installed, or you've not got your paths set up correctly to find its header files.
|
||||
|
||||
Linux: The package you need to install to get JACK support is libjack-dev.
|
||||
|
||||
macOS: The package you need to install to get JACK support is jack, which you can
|
||||
install using Homebrew.
|
||||
|
||||
Windows: The package you need to install to get JACK support is available from the
|
||||
JACK Audio website. Download and run the installer for Windows.
|
||||
|
||||
If you don't have the jack-audio-connection-kit library and don't want to build
|
||||
JUCE with low latency audio support, just set the JUCE_JACK flag to 0.
|
||||
*/
|
||||
#include <jack/jack.h>
|
||||
#include "native/juce_JackAudio.cpp"
|
||||
#endif
|
||||
|
||||
#if ! JUCE_SYSTEMAUDIOVOL_IMPLEMENTED
|
||||
namespace juce
|
||||
{
|
||||
// None of these methods are available. (On Windows you might need to enable WASAPI for this)
|
||||
float JUCE_CALLTYPE SystemAudioVolume::getGain() { jassertfalse; return 0.0f; }
|
||||
bool JUCE_CALLTYPE SystemAudioVolume::setGain (float) { jassertfalse; return false; }
|
||||
bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { jassertfalse; return false; }
|
||||
bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool) { jassertfalse; return false; }
|
||||
}
|
||||
#endif
|
||||
|
||||
#include "audio_io/juce_AudioDeviceManager.cpp"
|
||||
#include "audio_io/juce_AudioIODevice.cpp"
|
||||
#include "audio_io/juce_AudioIODeviceType.cpp"
|
||||
#include "midi_io/juce_MidiMessageCollector.cpp"
|
||||
#include "sources/juce_AudioSourcePlayer.cpp"
|
||||
#include "sources/juce_AudioTransportSource.cpp"
|
||||
|
||||
#if JUCE_LINUX || JUCE_BSD
|
||||
#include "native/juce_Midi_linux.cpp"
|
||||
#elif JUCE_ANDROID
|
||||
#include "native/juce_Midi_android.cpp"
|
||||
#elif JUCE_MAC || JUCE_IOS
|
||||
#include "native/juce_CoreMidi_mac.mm"
|
||||
#elif JUCE_WINDOWS
|
||||
#if JUCE_USE_WINDOWS_MIDI_SERVICES
|
||||
static_assert (JUCE_CXX20_IS_AVAILABLE, "Make sure C++20 is enabled to use Windows MIDI Services");
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4265)
|
||||
#include <winrt/Windows.Foundation.h>
|
||||
#include <winrt/Windows.Foundation.Collections.h>
|
||||
#include <winrt/Windows.Devices.Enumeration.h>
|
||||
|
||||
#include <WindowsMidiServicesAppSdkComExtensions.h>
|
||||
#include <winrt/Windows.Devices.Midi2.h>
|
||||
#include <winrt/Windows.Devices.Midi2.Enumeration.h>
|
||||
#include <winrt/Windows.Devices.Midi2.Transports.Virtual.h>
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
#endif
|
||||
|
||||
#include "native/juce_Midi_windows.cpp"
|
||||
#endif
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
#include "midi_io/juce_ScheduledEventThread_test.cpp"
|
||||
#endif
|
||||
@@ -0,0 +1,256 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
The block below describes the properties of this module, and is read by
|
||||
the Projucer to automatically generate project code that uses it.
|
||||
For details about the syntax and how to create or use a module, see the
|
||||
JUCE Module Format.md file.
|
||||
|
||||
|
||||
BEGIN_JUCE_MODULE_DECLARATION
|
||||
|
||||
ID: juce_audio_devices
|
||||
vendor: juce
|
||||
version: 9.0.5
|
||||
name: JUCE audio and MIDI I/O device classes
|
||||
description: Classes to play and record from audio and MIDI I/O devices
|
||||
website: http://www.juce.com/juce
|
||||
license: AGPLv3/Commercial
|
||||
minimumCppStandard: 17
|
||||
|
||||
dependencies: juce_audio_basics, juce_events
|
||||
OSXFrameworks: CoreAudio CoreMIDI AudioToolbox
|
||||
iOSFrameworks: CoreAudio CoreMIDI AudioToolbox AVFoundation
|
||||
linuxPackages: alsa
|
||||
|
||||
END_JUCE_MODULE_DECLARATION
|
||||
|
||||
*******************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
#define JUCE_AUDIO_DEVICES_H_INCLUDED
|
||||
|
||||
#include <juce_events/juce_events.h>
|
||||
#include <juce_audio_basics/juce_audio_basics.h>
|
||||
|
||||
#if JUCE_MODULE_AVAILABLE_juce_graphics
|
||||
#include <juce_graphics/juce_graphics.h>
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
/** Config: JUCE_USE_WINRT_MIDI
|
||||
Enables the use of the Windows Runtime API for MIDI, allowing connections
|
||||
to Bluetooth Low Energy devices on Windows 10 version 1809 (October 2018
|
||||
Update) and later. If you enable this flag then older versions of Windows
|
||||
will automatically fall back to using the regular Win32 MIDI API.
|
||||
|
||||
You will need version 10.0.14393.0 of the Windows Standalone SDK to compile
|
||||
and you may need to add the path to the WinRT headers. The path to the
|
||||
headers will be something similar to
|
||||
"C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\winrt".
|
||||
*/
|
||||
#ifndef JUCE_USE_WINRT_MIDI
|
||||
#define JUCE_USE_WINRT_MIDI 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_USE_WINDOWS_MIDI_SERVICES
|
||||
Enables the use of Windows MIDI Services, in turn enabling MIDI 2.0 support on
|
||||
some Windows versions. At time of writing, this only works on the Canary insiders
|
||||
build of Windows 11, but eventually this will work on the final release of
|
||||
Windows 10 too.
|
||||
|
||||
In order to enable this functionality, your target and minimum Windows SDK
|
||||
versions must be set to at least 10.0.20348.0.
|
||||
|
||||
This functionality depends on the CppWinRT tool and the Windows MIDI Services
|
||||
NuGet package at build-time. If you're using the Projucer, this will be set up
|
||||
for you automatically when this flag is enabled. If you're using CMake, you'll
|
||||
need to pass "NEEDS_WINDOWS_MIDI_SERVICES TRUE" to your juce_add_<target> call.
|
||||
|
||||
Currently, the Windows MIDI Services NuGet package is not hosted in the official
|
||||
repository. In order to allow NuGet and/or Visual Studio to find the package,
|
||||
you'll need to set up a local repository pointing at a local folder holding the
|
||||
package. You can do this from the Visual Studio package management UI.
|
||||
|
||||
Because this API is implemented using code generated by the CppWinRT tool, it
|
||||
can only be built by compilers that understand the generated code. MSVC is
|
||||
most likely to work; some versions of Clang may work but this is not guaranteed.
|
||||
|
||||
Even once the Windows MIDI Services are stable and enabled in Windows,
|
||||
the service won't be usable until the service's SDK package is installed.
|
||||
Therefore, you will need to ensure that the installer for your software also
|
||||
installs this SDK package, or informs the user how to install the dependency.
|
||||
If the SDK is not available, JUCE will fall back to using the older WinRT
|
||||
API (if enabled) or the Win32 API otherwise. These APIs do not support MIDI 2.0.
|
||||
*/
|
||||
#ifndef JUCE_USE_WINDOWS_MIDI_SERVICES
|
||||
#define JUCE_USE_WINDOWS_MIDI_SERVICES 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_ASIO
|
||||
Enables ASIO audio devices (MS Windows only).
|
||||
IMPORTANT: Turning this on will cause your program to depend on source files
|
||||
from the ASIO SDK from Steinberg, so your resulting program must adhere to
|
||||
the license terms of those files.
|
||||
|
||||
By default, this option will use the bundled ASIO headers distributed
|
||||
alongside JUCE. See the documentation for JUCE_ASIO_USE_EXTERNAL_SDK to
|
||||
learn how to use a different version of those headers.
|
||||
*/
|
||||
#ifndef JUCE_ASIO
|
||||
#define JUCE_ASIO 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_ASIO_USE_EXTERNAL_SDK
|
||||
The default behaviour of the JUCE_ASIO flag is to include a bundled header
|
||||
from the ASIO SDK. If you need to supply your own version of this header,
|
||||
instead of using the bundled one, you can enable this flag. If you do,
|
||||
then you must also ensure that the file "iasiodrv.h" from the SDK can be
|
||||
located via your project's header include paths.
|
||||
|
||||
The option only has an effect when JUCE_ASIO is also enabled.
|
||||
*/
|
||||
#ifndef JUCE_ASIO_USE_EXTERNAL_SDK
|
||||
#define JUCE_ASIO_USE_EXTERNAL_SDK 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_WASAPI
|
||||
Enables WASAPI audio devices (Windows Vista and above).
|
||||
*/
|
||||
#ifndef JUCE_WASAPI
|
||||
#define JUCE_WASAPI 1
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_DIRECTSOUND
|
||||
Enables DirectSound audio (MS Windows only).
|
||||
*/
|
||||
#ifndef JUCE_DIRECTSOUND
|
||||
#define JUCE_DIRECTSOUND 1
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_ALSA
|
||||
Enables ALSA audio devices (Linux only).
|
||||
*/
|
||||
#ifndef JUCE_ALSA
|
||||
#define JUCE_ALSA 1
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_JACK
|
||||
Enables JACK audio devices.
|
||||
*/
|
||||
#ifndef JUCE_JACK
|
||||
#define JUCE_JACK 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_USE_ANDROID_OBOE
|
||||
Enables Oboe devices (Android only).
|
||||
*/
|
||||
#ifndef JUCE_USE_ANDROID_OBOE
|
||||
#define JUCE_USE_ANDROID_OBOE 1
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_USE_OBOE_STABILIZED_CALLBACK
|
||||
If JUCE_USE_ANDROID_OBOE is enabled, enabling this will wrap output audio
|
||||
streams in the oboe::StabilizedCallback class. This class attempts to keep
|
||||
the CPU spinning to avoid it being scaled down on certain devices.
|
||||
(Android only).
|
||||
*/
|
||||
#ifndef JUCE_USE_ANDROID_OBOE_STABILIZED_CALLBACK
|
||||
#define JUCE_USE_ANDROID_OBOE_STABILIZED_CALLBACK 0
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_USE_ANDROID_OPENSLES
|
||||
Enables OpenSLES devices (Android only).
|
||||
*/
|
||||
#ifndef JUCE_USE_ANDROID_OPENSLES
|
||||
#if ! JUCE_USE_ANDROID_OBOE
|
||||
#define JUCE_USE_ANDROID_OPENSLES 1
|
||||
#else
|
||||
#define JUCE_USE_ANDROID_OPENSLES 0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/** Config: JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS
|
||||
Turning this on gives your app exclusive access to the system's audio
|
||||
on platforms which support it (currently iOS only).
|
||||
*/
|
||||
#ifndef JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS
|
||||
#define JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS 0
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
#include "midi_io/juce_ScheduledEventThread.h"
|
||||
#include "midi_io/ump/juce_UMPEndpointId.h"
|
||||
#include "midi_io/ump/juce_UMPStaticDeviceInfo.h"
|
||||
#include "midi_io/ump/juce_UMPBlock.h"
|
||||
#include "midi_io/ump/juce_UMPEndpoint.h"
|
||||
#include "midi_io/ump/juce_UMPDisconnectionListener.h"
|
||||
#include "midi_io/ump/juce_UMPInput.h"
|
||||
#include "midi_io/ump/juce_UMPOutput.h"
|
||||
#include "midi_io/ump/juce_UMPLegacyVirtualInput.h"
|
||||
#include "midi_io/ump/juce_UMPLegacyVirtualOutput.h"
|
||||
#include "midi_io/ump/juce_UMPVirtualEndpoint.h"
|
||||
#include "midi_io/ump/juce_UMPSession.h"
|
||||
#include "midi_io/ump/juce_UMPEndpoints.h"
|
||||
#include "midi_io/juce_MidiDevices.h"
|
||||
#include "midi_io/juce_MidiMessageCollector.h"
|
||||
|
||||
namespace juce
|
||||
{
|
||||
/** Available modes for the WASAPI audio device.
|
||||
|
||||
Pass one of these to the AudioIODeviceType::createAudioIODeviceType_WASAPI()
|
||||
method to create a WASAPI AudioIODeviceType object in this mode.
|
||||
*/
|
||||
enum class WASAPIDeviceMode
|
||||
{
|
||||
shared,
|
||||
exclusive,
|
||||
sharedLowLatency
|
||||
};
|
||||
}
|
||||
|
||||
#include "audio_io/juce_AudioIODevice.h"
|
||||
#include "audio_io/juce_AudioIODeviceType.h"
|
||||
#include "audio_io/juce_SystemAudioVolume.h"
|
||||
#include "sources/juce_AudioSourcePlayer.h"
|
||||
#include "sources/juce_AudioTransportSource.h"
|
||||
#include "audio_io/juce_AudioDeviceManager.h"
|
||||
|
||||
#if JUCE_IOS
|
||||
#include "native/juce_Audio_ios.h"
|
||||
#endif
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#include "juce_audio_devices.cpp"
|
||||
Vendored
+364
@@ -0,0 +1,364 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/* Identifies a single group of an endpoint. */
|
||||
struct EndpointGroup
|
||||
{
|
||||
ump::EndpointId endpointId;
|
||||
uint8_t group; // 0 to 15 inclusive
|
||||
|
||||
bool operator== (const EndpointGroup& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tuple (x.endpointId, x.group); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool operator!= (const EndpointGroup& other) const { return ! operator== (other); }
|
||||
};
|
||||
|
||||
class MidiDeviceListConnectionBroadcaster : private AsyncUpdater,
|
||||
private ump::EndpointsListener
|
||||
{
|
||||
struct GroupId
|
||||
{
|
||||
String identifier;
|
||||
ump::IOKind kind;
|
||||
|
||||
auto tie() const { return std::tuple (identifier, kind); }
|
||||
bool operator== (const GroupId& other) const { return tie() == other.tie(); }
|
||||
bool operator!= (const GroupId& other) const { return tie() != other.tie(); }
|
||||
bool operator< (const GroupId& other) const { return tie() < other.tie(); }
|
||||
};
|
||||
|
||||
class Endpoints
|
||||
{
|
||||
auto tie() const { return std::tie (idBuffer, map, inputs, outputs); }
|
||||
|
||||
public:
|
||||
void refresh()
|
||||
{
|
||||
updateIdBuffer();
|
||||
map = computeMap();
|
||||
inputs = computeInfo (ump::IOKind::src);
|
||||
outputs = computeInfo (ump::IOKind::dst);
|
||||
}
|
||||
|
||||
std::optional<EndpointGroup> getEndpointGroupForId (ump::IOKind direction, const String& id) const
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
const auto iter = map.find ({ id, direction });
|
||||
|
||||
if (iter == map.end())
|
||||
return {};
|
||||
|
||||
return iter->second;
|
||||
}
|
||||
|
||||
void getAllMidiDeviceInfo (ump::IOKind direction, Array<MidiDeviceInfo>& buffer) const
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
buffer.addArray (direction == ump::IOKind::src ? inputs : outputs);
|
||||
}
|
||||
|
||||
bool operator== (const Endpoints& other) const
|
||||
{
|
||||
return tie() == other.tie();
|
||||
}
|
||||
|
||||
bool operator!= (const Endpoints& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
private:
|
||||
void updateIdBuffer()
|
||||
{
|
||||
idBuffer.clear();
|
||||
|
||||
auto* ep = ump::Endpoints::getInstance();
|
||||
|
||||
if (ep == nullptr)
|
||||
return;
|
||||
|
||||
ep->getEndpoints (idBuffer);
|
||||
}
|
||||
|
||||
std::map<GroupId, EndpointGroup> computeMap() const
|
||||
{
|
||||
auto* ep = ump::Endpoints::getInstance();
|
||||
|
||||
if (ep == nullptr)
|
||||
return {};
|
||||
|
||||
std::map<GroupId, EndpointGroup> result;
|
||||
|
||||
for (const auto& id : idBuffer)
|
||||
{
|
||||
const auto info = ep->getStaticDeviceInfo (id);
|
||||
|
||||
if (! info.has_value())
|
||||
continue;
|
||||
|
||||
for (const auto kind : ump::ioKinds)
|
||||
{
|
||||
const auto groups = info->getLegacyIdentifiers (kind);
|
||||
|
||||
for (const auto [index, groupId] : enumerate (groups, uint8_t{}))
|
||||
{
|
||||
if (groupId.isNotEmpty())
|
||||
result.emplace (GroupId { groupId, kind }, EndpointGroup { id, index });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Array<MidiDeviceInfo> computeInfo (ump::IOKind dir) const
|
||||
{
|
||||
auto* ep = ump::Endpoints::getInstance();
|
||||
|
||||
if (ep == nullptr)
|
||||
return {};
|
||||
|
||||
Array<MidiDeviceInfo> result;
|
||||
|
||||
for (const auto& id : idBuffer)
|
||||
{
|
||||
const auto endpoint = ep->getEndpoint (id);
|
||||
|
||||
if (! endpoint.has_value())
|
||||
continue;
|
||||
|
||||
const auto info = ep->getStaticDeviceInfo (id);
|
||||
|
||||
if (! info.has_value())
|
||||
continue;
|
||||
|
||||
const auto groups = info->getLegacyIdentifiers (dir);
|
||||
|
||||
for (const auto [groupIndex, groupId] : enumerate (groups, uint8_t{}))
|
||||
{
|
||||
if (groupId.isEmpty())
|
||||
continue;
|
||||
|
||||
const auto blockName = findNameForGroup (groupIndex, dir, endpoint->getBlocks());
|
||||
|
||||
if (! blockName.has_value())
|
||||
continue;
|
||||
|
||||
const auto name = buildName (endpoint->getName(), *blockName);
|
||||
|
||||
result.add (MidiDeviceInfo { name, groupId });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<ump::EndpointId> idBuffer = std::invoke ([]() -> std::vector<ump::EndpointId>
|
||||
{
|
||||
auto* ep = ump::Endpoints::getInstance();
|
||||
|
||||
if (ep == nullptr)
|
||||
return {};
|
||||
|
||||
std::vector<ump::EndpointId> result;
|
||||
ep->getEndpoints (result);
|
||||
return result;
|
||||
});
|
||||
|
||||
std::map<GroupId, EndpointGroup> map = computeMap();
|
||||
Array<MidiDeviceInfo> inputs = computeInfo (ump::IOKind::src), outputs = computeInfo (ump::IOKind::dst);
|
||||
};
|
||||
|
||||
public:
|
||||
~MidiDeviceListConnectionBroadcaster() override
|
||||
{
|
||||
if (auto* instance = ump::Endpoints::getInstanceWithoutCreating())
|
||||
instance->removeListener (*this);
|
||||
|
||||
cancelPendingUpdate();
|
||||
}
|
||||
|
||||
MidiDeviceListConnection::Key add (std::function<void()> callback)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
return callbacks.emplace (key++, std::move (callback)).first->first;
|
||||
}
|
||||
|
||||
void getAllMidiDeviceInfo (ump::IOKind direction, Array<MidiDeviceInfo>& buffer)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (! endpoints.has_value())
|
||||
endpoints = Endpoints{};
|
||||
|
||||
endpoints->getAllMidiDeviceInfo (direction, buffer);
|
||||
}
|
||||
|
||||
std::optional<MidiDeviceInfo> getInfoForId (ump::IOKind direction, const String& id)
|
||||
{
|
||||
if (const auto eg = getEndpointGroupForId (direction, id))
|
||||
return findInfoForDeviceIdentifier ({ id, direction }, *eg);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<EndpointGroup> getEndpointGroupForId (ump::IOKind direction, const String& id)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (! endpoints.has_value())
|
||||
endpoints = Endpoints{};
|
||||
|
||||
return endpoints->getEndpointGroupForId (direction, id);
|
||||
}
|
||||
|
||||
void remove (const MidiDeviceListConnection::Key k)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
callbacks.erase (k);
|
||||
}
|
||||
|
||||
static auto& get()
|
||||
{
|
||||
static MidiDeviceListConnectionBroadcaster result;
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
MidiDeviceListConnectionBroadcaster()
|
||||
{
|
||||
ump::Endpoints::getInstance()->addListener (*this);
|
||||
}
|
||||
|
||||
static std::optional<String> findNameForGroup (uint8_t group, ump::IOKind kind, Span<const ump::Block> blocks)
|
||||
{
|
||||
const auto matchingGroup = std::find_if (blocks.begin(), blocks.end(), [&] (const ump::Block& b)
|
||||
{
|
||||
return directionsMatch (b, kind) && group == b.getFirstGroup() && b.getNumGroups() == 1;
|
||||
});
|
||||
|
||||
if (matchingGroup != blocks.end())
|
||||
return matchingGroup->getName();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void endpointsChanged() override
|
||||
{
|
||||
auto* mm = MessageManager::getInstanceWithoutCreating();
|
||||
|
||||
if (mm == nullptr)
|
||||
return;
|
||||
|
||||
if (! mm->isThisTheMessageThread())
|
||||
{
|
||||
triggerAsyncUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
cancelPendingUpdate();
|
||||
|
||||
if (auto prev = std::exchange (endpoints, Endpoints{}); prev != endpoints)
|
||||
for (auto it = callbacks.begin(); it != callbacks.end();)
|
||||
NullCheckedInvocation::invoke ((it++)->second);
|
||||
}
|
||||
|
||||
void handleAsyncUpdate() override
|
||||
{
|
||||
endpointsChanged();
|
||||
}
|
||||
|
||||
static bool directionsMatch (ump::BlockDirection d, ump::IOKind k)
|
||||
{
|
||||
switch (d)
|
||||
{
|
||||
case ump::BlockDirection::unknown: return true;
|
||||
case ump::BlockDirection::bidirectional: return true;
|
||||
case ump::BlockDirection::sender: return k == ump::IOKind::src;
|
||||
case ump::BlockDirection::receiver: return k == ump::IOKind::dst;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool directionsMatch (const ump::Block& b, ump::IOKind k)
|
||||
{
|
||||
return directionsMatch (b.getDirection(), k);
|
||||
}
|
||||
|
||||
static std::optional<MidiDeviceInfo> findInfoForDeviceIdentifier (const GroupId& key, const EndpointGroup& value)
|
||||
{
|
||||
auto* endpoints = ump::Endpoints::getInstance();
|
||||
|
||||
if (endpoints == nullptr)
|
||||
return {};
|
||||
|
||||
const auto endpoint = endpoints->getEndpoint (value.endpointId);
|
||||
|
||||
if (! endpoint.has_value())
|
||||
return {};
|
||||
|
||||
const auto blockName = findNameForGroup (value.group, key.kind, endpoint->getBlocks());
|
||||
|
||||
if (! blockName.has_value())
|
||||
return {};
|
||||
|
||||
const auto name = buildName (endpoint->getName(), *blockName);
|
||||
|
||||
return MidiDeviceInfo { name, key.identifier };
|
||||
}
|
||||
|
||||
static String buildName (String endpoint, String block)
|
||||
{
|
||||
const auto separator = endpoint.isEmpty() || block.isEmpty() ? "" : " ";
|
||||
|
||||
MemoryOutputStream stream;
|
||||
stream << endpoint << separator << block;
|
||||
return stream.toString();
|
||||
}
|
||||
|
||||
std::optional<Endpoints> endpoints;
|
||||
std::map<MidiDeviceListConnection::Key, std::function<void()>> callbacks;
|
||||
MidiDeviceListConnection::Key key = 0;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,448 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
MidiDeviceListConnection MidiDeviceListConnection::make (std::function<void()> callback)
|
||||
{
|
||||
auto& broadcaster = MidiDeviceListConnectionBroadcaster::get();
|
||||
|
||||
const auto key = broadcaster.add (std::move (callback));
|
||||
|
||||
MidiDeviceListConnection result;
|
||||
result.token = ErasedScopeGuard { [&broadcaster, key] { broadcaster.remove (key); } };
|
||||
return result;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static std::shared_ptr<ump::Session> getLegacySession()
|
||||
{
|
||||
static std::weak_ptr<ump::Session> weak;
|
||||
|
||||
if (auto strong = weak.lock())
|
||||
return strong;
|
||||
|
||||
if (auto session = ump::Endpoints::getInstance()->makeSession (ump::Endpoints::Impl::getGlobalMidiClientName()))
|
||||
{
|
||||
auto strong = std::make_shared<ump::Session> (std::move (session));
|
||||
weak = strong;
|
||||
return strong;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
class MidiInput::Impl : private ump::Consumer,
|
||||
private ump::DisconnectionListener
|
||||
{
|
||||
public:
|
||||
void start()
|
||||
{
|
||||
const SpinLock::ScopedLockType lock { spinLock };
|
||||
active = true;
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
const SpinLock::ScopedLockType lock { spinLock };
|
||||
active = false;
|
||||
}
|
||||
|
||||
MidiDeviceInfo getDeviceInfo() const noexcept
|
||||
{
|
||||
return customName.has_value() ? storedInfo.withName (*customName) : storedInfo;
|
||||
}
|
||||
|
||||
void setName (String x)
|
||||
{
|
||||
customName = std::move (x);
|
||||
}
|
||||
|
||||
void addCallback (MidiInputCallback& cb)
|
||||
{
|
||||
callbacks.add (cb);
|
||||
}
|
||||
|
||||
void removeCallback (MidiInputCallback& cb)
|
||||
{
|
||||
callbacks.remove (cb);
|
||||
}
|
||||
|
||||
/* session may be null, in which case it's up to the caller to ensure that the session lives
|
||||
long enough for the connection to be useful.
|
||||
*/
|
||||
static std::unique_ptr<MidiInput> make (std::shared_ptr<ump::Session> session,
|
||||
ump::Input connection,
|
||||
uint8_t group,
|
||||
const MidiDeviceInfo& info,
|
||||
MidiInputCallback* cb,
|
||||
ump::LegacyVirtualInput virtualEndpoint)
|
||||
{
|
||||
auto result = rawToUniquePtr (new MidiInput);
|
||||
result->pimpl = rawToUniquePtr (new Impl (session,
|
||||
std::move (connection),
|
||||
group,
|
||||
result.get(),
|
||||
info,
|
||||
std::move (virtualEndpoint)));
|
||||
|
||||
if (cb != nullptr)
|
||||
result->addCallback (*cb);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
uint8_t getGroup() const
|
||||
{
|
||||
return group;
|
||||
}
|
||||
|
||||
ump::EndpointId getEndpointId() const
|
||||
{
|
||||
return connection.getEndpointId();
|
||||
}
|
||||
|
||||
void addDisconnectionListener (DisconnectionListener& l)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
disconnectionListeners.add (&l);
|
||||
}
|
||||
|
||||
void removeDisconnectionListener (DisconnectionListener& l)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
disconnectionListeners.remove (&l);
|
||||
}
|
||||
|
||||
~Impl() override
|
||||
{
|
||||
connection.removeDisconnectionListener (*this);
|
||||
connection.removeConsumer (*this);
|
||||
}
|
||||
|
||||
private:
|
||||
Impl (std::shared_ptr<ump::Session> s,
|
||||
ump::Input x,
|
||||
uint8_t g,
|
||||
MidiInput* o,
|
||||
MidiDeviceInfo i,
|
||||
ump::LegacyVirtualInput v)
|
||||
: session (s),
|
||||
virtualEndpoint (std::move (v)),
|
||||
connection (std::move (x)),
|
||||
storedInfo (i),
|
||||
group (g),
|
||||
owner (o)
|
||||
{
|
||||
connection.addConsumer (*this);
|
||||
connection.addDisconnectionListener (*this);
|
||||
}
|
||||
|
||||
void consume (ump::Iterator b, ump::Iterator e, double time) override
|
||||
{
|
||||
const SpinLock::ScopedTryLockType lock { spinLock };
|
||||
|
||||
if (! lock.isLocked() || ! active)
|
||||
return;
|
||||
|
||||
for (const auto& view : makeRange (b, e))
|
||||
{
|
||||
if (ump::Utils::getGroup (view[0]) != group)
|
||||
continue;
|
||||
|
||||
converter.convert (view, time, [this] (ump::BytesOnGroup v, double t)
|
||||
{
|
||||
const MidiMessage msg { v.bytes.data(), (int) v.bytes.size(), t };
|
||||
|
||||
callbacks.call ([&] (MidiInputCallback& l)
|
||||
{
|
||||
l.handleIncomingMidiMessage (owner, msg);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void disconnected() override
|
||||
{
|
||||
disconnectionListeners.call ([&] (auto& l) { l.disconnected(); });
|
||||
}
|
||||
|
||||
std::shared_ptr<ump::Session> session;
|
||||
ump::LegacyVirtualInput virtualEndpoint;
|
||||
std::optional<String> customName;
|
||||
ump::Input connection;
|
||||
MidiDeviceInfo storedInfo;
|
||||
ump::ToBytestreamConverter converter { 4096 };
|
||||
ListenerList<DisconnectionListener> disconnectionListeners;
|
||||
WaitFreeListeners<MidiInputCallback> callbacks;
|
||||
uint8_t group{};
|
||||
MidiInput* owner = nullptr;
|
||||
SpinLock spinLock;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
MidiInput::MidiInput() = default;
|
||||
MidiInput::~MidiInput() = default;
|
||||
|
||||
Array<MidiDeviceInfo> MidiInput::getAvailableDevices()
|
||||
{
|
||||
Array<MidiDeviceInfo> result;
|
||||
MidiDeviceListConnectionBroadcaster::get().getAllMidiDeviceInfo (ump::IOKind::src, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
MidiDeviceInfo MidiInput::getDefaultDevice()
|
||||
{
|
||||
return getAvailableDevices().getFirst();
|
||||
}
|
||||
|
||||
std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback)
|
||||
{
|
||||
const auto address = MidiDeviceListConnectionBroadcaster::get().getEndpointGroupForId (ump::IOKind::src, deviceIdentifier);
|
||||
|
||||
if (! address.has_value())
|
||||
return {};
|
||||
|
||||
const auto info = MidiDeviceListConnectionBroadcaster::get().getInfoForId (ump::IOKind::src, deviceIdentifier);
|
||||
|
||||
if (! info.has_value())
|
||||
return {};
|
||||
|
||||
auto session = getLegacySession();
|
||||
|
||||
if (session == nullptr)
|
||||
return {};
|
||||
|
||||
auto connection = session->connectInput (address->endpointId, ump::PacketProtocol::MIDI_1_0);
|
||||
|
||||
if (! connection.isAlive())
|
||||
return {};
|
||||
|
||||
return Impl::make (session, std::move (connection), address->group, *info, callback, {});
|
||||
}
|
||||
|
||||
static inline bool isValidMidi1VirtualEndpoint (const std::optional<ump::Endpoint>& ep,
|
||||
ump::BlockDirection dir)
|
||||
{
|
||||
if (! ep.has_value())
|
||||
return false;
|
||||
|
||||
if (! ep->hasMidi1Support())
|
||||
return false;
|
||||
|
||||
if (ep->getProtocol() != ump::PacketProtocol::MIDI_1_0)
|
||||
return false;
|
||||
|
||||
if (! ep->hasStaticBlocks())
|
||||
return false;
|
||||
|
||||
auto blocks = ep->getBlocks();
|
||||
const auto iter = std::find_if (blocks.begin(), blocks.end(), [&] (const ump::Block& b)
|
||||
{
|
||||
return b.getDirection() == dir
|
||||
&& b.getNumGroups() == 1
|
||||
&& b.isEnabled()
|
||||
&& b.getMIDI1ProxyKind() != ump::BlockMIDI1ProxyKind::inapplicable;
|
||||
});
|
||||
|
||||
if (iter == blocks.end())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String& name, MidiInputCallback* callback)
|
||||
{
|
||||
auto session = getLegacySession();
|
||||
|
||||
if (! session)
|
||||
return {};
|
||||
|
||||
auto port = session->createLegacyVirtualInput (name);
|
||||
|
||||
if (! port)
|
||||
return {};
|
||||
|
||||
jassert (isValidMidi1VirtualEndpoint (ump::Endpoints::getInstance()->getEndpoint (port.getId()),
|
||||
ump::BlockDirection::receiver));
|
||||
|
||||
auto connection = session->connectInput (port.getId(), ump::PacketProtocol::MIDI_1_0);
|
||||
|
||||
if (! connection)
|
||||
return {};
|
||||
|
||||
const auto portId = port.getId().dst;
|
||||
return Impl::make (session, std::move (connection), 0, { name, portId }, callback, std::move (port));
|
||||
}
|
||||
|
||||
void MidiInput::start()
|
||||
{
|
||||
pimpl->start();
|
||||
}
|
||||
|
||||
void MidiInput::stop()
|
||||
{
|
||||
pimpl->stop();
|
||||
}
|
||||
|
||||
MidiDeviceInfo MidiInput::getDeviceInfo() const noexcept
|
||||
{
|
||||
return pimpl->getDeviceInfo();
|
||||
}
|
||||
|
||||
void MidiInput::setName (const String& newName) noexcept
|
||||
{
|
||||
pimpl->setName (newName);
|
||||
}
|
||||
|
||||
uint8_t MidiInput::getGroup() const
|
||||
{
|
||||
return pimpl->getGroup();
|
||||
}
|
||||
|
||||
ump::EndpointId MidiInput::getEndpointId() const
|
||||
{
|
||||
return pimpl->getEndpointId();
|
||||
}
|
||||
|
||||
void MidiInput::addCallback (MidiInputCallback& callback)
|
||||
{
|
||||
pimpl->addCallback (callback);
|
||||
}
|
||||
|
||||
void MidiInput::removeCallback (MidiInputCallback& callback)
|
||||
{
|
||||
pimpl->removeCallback (callback);
|
||||
}
|
||||
|
||||
void MidiInput::addDisconnectionListener (ump::DisconnectionListener& l)
|
||||
{
|
||||
pimpl->addDisconnectionListener (l);
|
||||
}
|
||||
|
||||
void MidiInput::removeDisconnectionListener (ump::DisconnectionListener& l)
|
||||
{
|
||||
pimpl->removeDisconnectionListener (l);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiOutput::MidiOutput (std::shared_ptr<ump::Session> s,
|
||||
ump::Output x,
|
||||
uint8_t g,
|
||||
const MidiDeviceInfo& i,
|
||||
ump::LegacyVirtualOutput v)
|
||||
: session (s),
|
||||
virtualEndpoint (std::move (v)),
|
||||
connection (std::move (x)),
|
||||
storedInfo (i),
|
||||
group (g)
|
||||
{
|
||||
mainPackets.reserve (2048);
|
||||
connection.addDisconnectionListener (*this);
|
||||
}
|
||||
|
||||
MidiOutput::~MidiOutput()
|
||||
{
|
||||
connection.removeDisconnectionListener (*this);
|
||||
}
|
||||
|
||||
Array<MidiDeviceInfo> MidiOutput::getAvailableDevices()
|
||||
{
|
||||
Array<MidiDeviceInfo> result;
|
||||
MidiDeviceListConnectionBroadcaster::get().getAllMidiDeviceInfo (ump::IOKind::dst, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier)
|
||||
{
|
||||
const auto address = MidiDeviceListConnectionBroadcaster::get().getEndpointGroupForId (ump::IOKind::dst, deviceIdentifier);
|
||||
|
||||
if (! address.has_value())
|
||||
return {};
|
||||
|
||||
const auto info = MidiDeviceListConnectionBroadcaster::get().getInfoForId (ump::IOKind::dst, deviceIdentifier);
|
||||
|
||||
if (! info.has_value())
|
||||
return {};
|
||||
|
||||
auto session = getLegacySession();
|
||||
|
||||
if (session == nullptr)
|
||||
return {};
|
||||
|
||||
auto connection = session->connectOutput (address->endpointId);
|
||||
|
||||
if (! connection.isAlive())
|
||||
return {};
|
||||
|
||||
return rawToUniquePtr (new MidiOutput (session, std::move (connection), address->group, *info, {}));
|
||||
}
|
||||
|
||||
std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String& name)
|
||||
{
|
||||
auto session = getLegacySession();
|
||||
|
||||
if (! session)
|
||||
return {};
|
||||
|
||||
auto port = session->createLegacyVirtualOutput (name);
|
||||
|
||||
if (! port)
|
||||
return {};
|
||||
|
||||
jassert (isValidMidi1VirtualEndpoint (ump::Endpoints::getInstance()->getEndpoint (port.getId()),
|
||||
ump::BlockDirection::sender));
|
||||
|
||||
auto connection = session->connectOutput (port.getId());
|
||||
|
||||
if (! connection)
|
||||
return {};
|
||||
|
||||
const auto portId = port.getId().src;
|
||||
return rawToUniquePtr (new MidiOutput (session, std::move (connection), 0, { name, portId }, std::move (port)));
|
||||
}
|
||||
|
||||
MidiDeviceInfo MidiOutput::getDeviceInfo() const noexcept
|
||||
{
|
||||
return customName.has_value() ? storedInfo.withName (*customName) : storedInfo;
|
||||
}
|
||||
|
||||
bool MidiDeviceInfo::operator== (const MidiDeviceInfo& other) const noexcept
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tuple (x.name, x.identifier); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,518 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/**
|
||||
To find out when the available MIDI devices change, call MidiDeviceListConnection::make(),
|
||||
passing a lambda that will be called on each configuration change.
|
||||
|
||||
To stop the lambda receiving callbacks, destroy the MidiDeviceListConnection instance returned
|
||||
from make(), or call reset() on it.
|
||||
|
||||
@code
|
||||
// Start listening for configuration changes
|
||||
auto connection = MidiDeviceListConnection::make ([]
|
||||
{
|
||||
// This will print a message when devices are connected/disconnected
|
||||
DBG ("MIDI devices changed");
|
||||
});
|
||||
|
||||
// Stop listening
|
||||
connection.reset();
|
||||
@endcode
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class MidiDeviceListConnection
|
||||
{
|
||||
public:
|
||||
using Key = uint64_t;
|
||||
|
||||
/** Constructs an inactive connection.
|
||||
*/
|
||||
MidiDeviceListConnection() = default;
|
||||
|
||||
/** Clears this connection.
|
||||
|
||||
If this object had an active connection, that connection will be deactivated, and the
|
||||
corresponding callback will be removed from the MidiDeviceListConnectionBroadcaster.
|
||||
*/
|
||||
void reset() noexcept
|
||||
{
|
||||
token.reset();
|
||||
}
|
||||
|
||||
/** Registers a function to be called whenever the midi device list changes.
|
||||
|
||||
The callback will only be active for as long as the return MidiDeviceListConnection remains
|
||||
alive. To stop receiving device change notifications, destroy the Connection object, e.g.
|
||||
by allowing it to fall out of scope.
|
||||
*/
|
||||
static MidiDeviceListConnection make (std::function<void()>);
|
||||
|
||||
private:
|
||||
ErasedScopeGuard token;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This struct contains information about a MIDI 1.0 input or output port.
|
||||
|
||||
You can get one of these structs by calling the static getAvailableDevices() or
|
||||
getDefaultDevice() methods of MidiInput and MidiOutput or by calling getDeviceInfo()
|
||||
on an instance of these classes. Devices can be opened by passing the identifier to
|
||||
the openDevice() method.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct MidiDeviceInfo
|
||||
{
|
||||
MidiDeviceInfo() = default;
|
||||
|
||||
MidiDeviceInfo (const String& deviceName, const String& deviceIdentifier)
|
||||
: name (deviceName), identifier (deviceIdentifier)
|
||||
{
|
||||
}
|
||||
|
||||
/** The name of this device.
|
||||
|
||||
This will be provided by the OS unless the device has been created with the
|
||||
createNewDevice() method.
|
||||
|
||||
Note that the name is not guaranteed to be unique and two devices with the
|
||||
same name will be indistinguishable. If you want to address a specific device
|
||||
it is better to use the identifier.
|
||||
*/
|
||||
String name;
|
||||
|
||||
/** The identifier for this device.
|
||||
|
||||
This will be provided by the OS and its format will differ on different systems
|
||||
e.g. on macOS it will be a number whereas on Windows it will be a long alphanumeric string.
|
||||
*/
|
||||
String identifier;
|
||||
|
||||
[[nodiscard]] MidiDeviceInfo withName (String x) const { return withMember (*this, &MidiDeviceInfo::name, x); }
|
||||
[[nodiscard]] MidiDeviceInfo withIdentifier (String x) const { return withMember (*this, &MidiDeviceInfo::identifier, x); }
|
||||
|
||||
//==============================================================================
|
||||
bool operator== (const MidiDeviceInfo& other) const noexcept;
|
||||
|
||||
bool operator!= (const MidiDeviceInfo& other) const noexcept { return ! operator== (other); }
|
||||
};
|
||||
|
||||
class MidiInputCallback;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a midi input device using the old bytestream format.
|
||||
|
||||
To create one of these, use the static getAvailableDevices() method to find out what
|
||||
inputs are available, and then use the openDevice() method to try to open one.
|
||||
|
||||
@see MidiOutput
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiInput final
|
||||
{
|
||||
public:
|
||||
MidiInput (MidiInput&&) = delete;
|
||||
|
||||
MidiInput& operator= (MidiInput&&) = delete;
|
||||
|
||||
~MidiInput();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a list of the available midi input devices.
|
||||
|
||||
You can open one of the devices by passing its identifier into the openDevice() method.
|
||||
|
||||
@see MidiDeviceInfo, getDevices, getDefaultDeviceIndex, openDevice
|
||||
*/
|
||||
static Array<MidiDeviceInfo> getAvailableDevices();
|
||||
|
||||
/** Returns the MidiDeviceInfo of the default midi input device to use. */
|
||||
static MidiDeviceInfo getDefaultDevice();
|
||||
|
||||
/** Tries to open one of the midi input devices.
|
||||
|
||||
This will return a MidiInput object if it manages to open it, you can then
|
||||
call start() and stop() on this device.
|
||||
|
||||
If the device can't be opened, this will return an empty object.
|
||||
|
||||
@param deviceIdentifier the ID of the device to open - use the getAvailableDevices() method to
|
||||
find the available devices that can be opened
|
||||
@param callback the object that will receive the midi messages from this device,
|
||||
you can also add and remove receivers with
|
||||
addCallback() and removeCallback()
|
||||
|
||||
@see MidiInputCallback, getDevices
|
||||
*/
|
||||
static std::unique_ptr<MidiInput> openDevice (const String& deviceIdentifier, MidiInputCallback* callback = nullptr);
|
||||
|
||||
/** This will try to create a new midi input device (only available on Linux, macOS and iOS).
|
||||
|
||||
This will attempt to create a new midi input device with the specified name for other
|
||||
apps to connect to.
|
||||
|
||||
NB - if you are calling this method on iOS you must have enabled the "Audio Background Capability"
|
||||
setting in the iOS exporter otherwise this method will fail.
|
||||
|
||||
Returns an empty object if a device can't be created.
|
||||
|
||||
@param deviceName the name of the device to create
|
||||
@param callback the object that will receive the midi messages from this device
|
||||
*/
|
||||
static std::unique_ptr<MidiInput> createNewDevice (const String& deviceName, MidiInputCallback* callback = nullptr);
|
||||
|
||||
//==============================================================================
|
||||
/** Starts the device running.
|
||||
|
||||
After calling this, the device will start sending midi messages to the MidiInputCallback
|
||||
object that was specified when the openDevice() method was called.
|
||||
|
||||
@see stop
|
||||
*/
|
||||
void start();
|
||||
|
||||
/** Stops the device running.
|
||||
|
||||
@see start
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/** Returns the MidiDeviceInfo struct containing some information about this device. */
|
||||
MidiDeviceInfo getDeviceInfo() const noexcept;
|
||||
|
||||
/** Returns the identifier of this device. */
|
||||
String getIdentifier() const noexcept { return getDeviceInfo().identifier; }
|
||||
|
||||
/** Returns the name of this device. */
|
||||
String getName() const noexcept { return getDeviceInfo().name; }
|
||||
|
||||
/** Sets a custom name for the device. */
|
||||
void setName (const String& newName) noexcept;
|
||||
|
||||
/** In the case that this input refers to a specific group of a UMP input, this returns the
|
||||
index of the group.
|
||||
*/
|
||||
uint8_t getGroup() const;
|
||||
|
||||
/** Returns the EndpointId that uniquely identifies the UMP endpoint that contains this input. */
|
||||
ump::EndpointId getEndpointId() const;
|
||||
|
||||
/** Adds an input listener. */
|
||||
void addCallback (MidiInputCallback&);
|
||||
|
||||
/** Removed an input listener. */
|
||||
void removeCallback (MidiInputCallback&);
|
||||
|
||||
/** Adds a listener, which will be notified if the device gets disconnected. */
|
||||
void addDisconnectionListener (ump::DisconnectionListener&);
|
||||
|
||||
/** Removes a previously-added disconnection listener. */
|
||||
void removeDisconnectionListener (ump::DisconnectionListener&);
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
MidiInput();
|
||||
|
||||
//==============================================================================
|
||||
std::unique_ptr<Impl> pimpl;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Receives incoming messages from a physical MIDI input device.
|
||||
|
||||
This class is overridden to handle incoming midi messages. See the MidiInput
|
||||
class for more details.
|
||||
|
||||
@see MidiInput
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiInputCallback
|
||||
{
|
||||
public:
|
||||
/** Destructor. */
|
||||
virtual ~MidiInputCallback() = default;
|
||||
|
||||
/** Receives an incoming message.
|
||||
|
||||
A MidiInput object will call this method when a midi event arrives. It'll be
|
||||
called on a high-priority system thread, so avoid doing anything time-consuming
|
||||
in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
|
||||
for queueing incoming messages for use later.
|
||||
|
||||
@param source the MidiInput object that generated the message
|
||||
@param message the incoming message. The message's timestamp is set to a value
|
||||
equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
|
||||
time when the message arrived
|
||||
*/
|
||||
virtual void handleIncomingMidiMessage (MidiInput* source,
|
||||
const MidiMessage& message) = 0;
|
||||
|
||||
/** Notification sent each time a packet of a multi-packet sysex message arrives.
|
||||
|
||||
If a long sysex message is broken up into multiple packets, this callback is made
|
||||
for each packet that arrives until the message is finished, at which point
|
||||
the normal handleIncomingMidiMessage() callback will be made with the entire
|
||||
message.
|
||||
|
||||
The message passed in will contain the start of a sysex, but won't be finished
|
||||
with the terminating 0xf7 byte.
|
||||
*/
|
||||
virtual void handlePartialSysexMessage ([[maybe_unused]] MidiInput* source,
|
||||
[[maybe_unused]] const uint8* messageData,
|
||||
[[maybe_unused]] int numBytesSoFar,
|
||||
[[maybe_unused]] double timestamp) {}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a midi output device using the old bytestream format.
|
||||
|
||||
To create one of these, use the static getAvailableDevices() method to find out what
|
||||
outputs are available, and then use the openDevice() method to try to open one.
|
||||
|
||||
@see MidiInput
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiOutput final : private ump::DisconnectionListener
|
||||
{
|
||||
public:
|
||||
/** Destructor */
|
||||
~MidiOutput() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a list of the available midi output devices.
|
||||
|
||||
You can open one of the devices by passing its identifier into the openDevice() method.
|
||||
|
||||
@see MidiDeviceInfo, getDevices, getDefaultDeviceIndex, openDevice
|
||||
*/
|
||||
static Array<MidiDeviceInfo> getAvailableDevices();
|
||||
|
||||
/** Returns the MidiDeviceInfo of the default midi output device to use. */
|
||||
static MidiDeviceInfo getDefaultDevice()
|
||||
{
|
||||
return getAvailableDevices().getFirst();
|
||||
}
|
||||
|
||||
/** Tries to open one of the midi output devices.
|
||||
|
||||
This will return a MidiOutput object if it manages to open it, you can then
|
||||
send messages to this device.
|
||||
|
||||
If the device can't be opened, this will return an empty object.
|
||||
|
||||
@param deviceIdentifier the ID of the device to open - use the getAvailableDevices() method to
|
||||
find the available devices that can be opened
|
||||
@see getDevices
|
||||
*/
|
||||
static std::unique_ptr<MidiOutput> openDevice (const String& deviceIdentifier);
|
||||
|
||||
/** This will try to create a new midi output device (only available on Linux, macOS and iOS).
|
||||
|
||||
This will attempt to create a new midi output device with the specified name that other
|
||||
apps can connect to and use as their midi input.
|
||||
|
||||
NB - if you are calling this method on iOS you must have enabled the "Audio Background Capability"
|
||||
setting in the iOS exporter otherwise this method will fail.
|
||||
|
||||
Returns an empty object if a device can't be created.
|
||||
|
||||
@param deviceName the name of the device to create
|
||||
*/
|
||||
static std::unique_ptr<MidiOutput> createNewDevice (const String& deviceName);
|
||||
|
||||
/** Returns the MidiDeviceInfo struct containing some information about this device. */
|
||||
MidiDeviceInfo getDeviceInfo() const noexcept;
|
||||
|
||||
/** Returns the identifier of this device. */
|
||||
String getIdentifier() const noexcept { return getDeviceInfo().identifier; }
|
||||
|
||||
/** Returns the name of this device. */
|
||||
String getName() const noexcept { return getDeviceInfo().name; }
|
||||
|
||||
/** Sets a custom name for the device. */
|
||||
void setName (const String& newName) noexcept { customName = newName; }
|
||||
|
||||
/** In the case that this output refers to a specific group of a UMP output, this returns the
|
||||
index of the group.
|
||||
*/
|
||||
uint8_t getGroup() const { return group; }
|
||||
|
||||
/** Returns the EndpointId that uniquely identifies the UMP endpoint that contains this output. */
|
||||
ump::EndpointId getEndpointId() const { return connection.getEndpointId(); }
|
||||
|
||||
//==============================================================================
|
||||
/** Sends out a MIDI message immediately. */
|
||||
bool sendMessageNow (const MidiMessage& message)
|
||||
{
|
||||
return convertAndSend (mainPackets, Span { &message, 1 });
|
||||
}
|
||||
|
||||
/** Sends out a sequence of MIDI messages immediately. */
|
||||
bool sendBlockOfMessagesNow (const MidiBuffer& buffer)
|
||||
{
|
||||
return convertAndSend (mainPackets, buffer);
|
||||
}
|
||||
|
||||
/** This lets you supply a block of messages that will be sent out at some point
|
||||
in the future.
|
||||
|
||||
The MidiOutput class has an internal thread that can send out timestamped
|
||||
messages - this appends a set of messages to its internal buffer, ready for
|
||||
sending.
|
||||
|
||||
This will only work if you've already started the thread with startBackgroundThread().
|
||||
|
||||
A time is specified, at which the block of messages should be sent. This time uses
|
||||
the same time base as Time::getMillisecondCounter(), and must be in the future.
|
||||
|
||||
The samplesPerSecondForBuffer parameter indicates the number of samples per second
|
||||
used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
|
||||
samplesPerSecondForBuffer value is needed to convert this sample position to a
|
||||
real time.
|
||||
*/
|
||||
void sendBlockOfMessages (const MidiBuffer& buffer,
|
||||
double millisecondCounterToStartAt,
|
||||
double samplesPerSecondForBuffer)
|
||||
{
|
||||
// This needs to be a value in the future - check the documentation for this function!
|
||||
jassert (millisecondCounterToStartAt > 0);
|
||||
|
||||
const auto timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
|
||||
|
||||
for (const auto item : buffer)
|
||||
{
|
||||
auto msg = item.getMessage();
|
||||
msg.setTimeStamp (millisecondCounterToStartAt + timeScaleFactor * msg.getTimeStamp());
|
||||
outputThread.addEvent (msg);
|
||||
}
|
||||
}
|
||||
|
||||
/** Gets rid of any midi messages that had been added by sendBlockOfMessages().
|
||||
*/
|
||||
void clearAllPendingMessages() { outputThread.clearAllPendingMessages(); }
|
||||
|
||||
/** Starts up a background thread so that the device can send blocks of data.
|
||||
Call this to get the device ready, before using sendBlockOfMessages().
|
||||
*/
|
||||
void startBackgroundThread()
|
||||
{
|
||||
backgroundPackets.reserve (2048);
|
||||
outputThread.start();
|
||||
}
|
||||
|
||||
/** Stops the background thread, and clears any pending midi events.
|
||||
@see startBackgroundThread
|
||||
*/
|
||||
void stopBackgroundThread() { outputThread.stop(); }
|
||||
|
||||
/** Returns true if the background thread used to send blocks of data is running.
|
||||
|
||||
@see startBackgroundThread, stopBackgroundThread
|
||||
*/
|
||||
bool isBackgroundThreadRunning() const { return outputThread.isRunning(); }
|
||||
|
||||
/** Adds a listener, which will be notified if the device gets disconnected. */
|
||||
void addDisconnectionListener (DisconnectionListener& l)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
disconnectionListeners.add (&l);
|
||||
}
|
||||
|
||||
/** Removes a previously-added disconnection listener. */
|
||||
void removeDisconnectionListener (DisconnectionListener& l)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
disconnectionListeners.remove (&l);
|
||||
}
|
||||
|
||||
private:
|
||||
MidiOutput (std::shared_ptr<ump::Session>,
|
||||
ump::Output,
|
||||
uint8_t,
|
||||
const MidiDeviceInfo&,
|
||||
ump::LegacyVirtualOutput);
|
||||
|
||||
void disconnected() override
|
||||
{
|
||||
disconnectionListeners.call ([&] (auto& l) { l.disconnected(); });
|
||||
}
|
||||
|
||||
template <typename Range>
|
||||
bool convertAndSend (ump::Packets& packets, Range&& range)
|
||||
{
|
||||
packets.clear();
|
||||
|
||||
std::for_each (std::begin (range), std::end (range), [&] (const auto& item)
|
||||
{
|
||||
ump::ToUMP1Converter{}.convert ({ group, item.asSpan() }, [&packets] (auto view)
|
||||
{
|
||||
packets.add (view);
|
||||
});
|
||||
});
|
||||
|
||||
return connection.send (packets.begin(), packets.end());
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
std::shared_ptr<ump::Session> session;
|
||||
ump::LegacyVirtualOutput virtualEndpoint;
|
||||
std::optional<String> customName;
|
||||
ump::Output connection;
|
||||
MidiDeviceInfo storedInfo;
|
||||
ump::Packets mainPackets, backgroundPackets;
|
||||
uint8_t group{};
|
||||
ListenerList<DisconnectionListener> disconnectionListeners;
|
||||
ScheduledEventThread<MidiMessage> outputThread { [this] (const MidiMessage& message)
|
||||
{
|
||||
convertAndSend (backgroundPackets, Span { &message, 1 });
|
||||
} };
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
MidiMessageCollector::MidiMessageCollector()
|
||||
{
|
||||
}
|
||||
|
||||
MidiMessageCollector::~MidiMessageCollector()
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiMessageCollector::reset (const double newSampleRate)
|
||||
{
|
||||
const ScopedLock sl (midiCallbackLock);
|
||||
|
||||
jassert (newSampleRate > 0);
|
||||
|
||||
#if JUCE_DEBUG
|
||||
hasCalledReset = true;
|
||||
#endif
|
||||
sampleRate = newSampleRate;
|
||||
incomingMessages.clear();
|
||||
lastCallbackTime = Time::getMillisecondCounterHiRes();
|
||||
}
|
||||
|
||||
void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
|
||||
{
|
||||
const ScopedLock sl (midiCallbackLock);
|
||||
|
||||
#if JUCE_DEBUG
|
||||
jassert (hasCalledReset); // you need to call reset() to set the correct sample rate before using this object
|
||||
#endif
|
||||
|
||||
// the messages that come in here need to be time-stamped correctly - see MidiInput
|
||||
// for details of what the number should be.
|
||||
jassert (! approximatelyEqual (message.getTimeStamp(), 0.0));
|
||||
|
||||
auto sampleNumber = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
|
||||
|
||||
incomingMessages.addEvent (message, sampleNumber);
|
||||
|
||||
// if the messages don't get used for over a second, we'd better
|
||||
// get rid of any old ones to avoid the queue getting too big
|
||||
if (sampleNumber > sampleRate)
|
||||
incomingMessages.clear (0, sampleNumber - (int) sampleRate);
|
||||
}
|
||||
|
||||
void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
|
||||
const int numSamples)
|
||||
{
|
||||
const ScopedLock sl (midiCallbackLock);
|
||||
|
||||
#if JUCE_DEBUG
|
||||
jassert (hasCalledReset); // you need to call reset() to set the correct sample rate before using this object
|
||||
#endif
|
||||
|
||||
jassert (numSamples > 0);
|
||||
|
||||
auto timeNow = Time::getMillisecondCounterHiRes();
|
||||
auto msElapsed = timeNow - lastCallbackTime;
|
||||
|
||||
lastCallbackTime = timeNow;
|
||||
|
||||
if (! incomingMessages.isEmpty())
|
||||
{
|
||||
int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
|
||||
int startSample = 0;
|
||||
int scale = 1 << 16;
|
||||
|
||||
if (numSourceSamples > numSamples)
|
||||
{
|
||||
// if our list of events is longer than the buffer we're being
|
||||
// asked for, scale them down to squeeze them all in
|
||||
const int maxBlockLengthToUse = numSamples << 5;
|
||||
|
||||
auto iter = incomingMessages.cbegin();
|
||||
|
||||
if (numSourceSamples > maxBlockLengthToUse)
|
||||
{
|
||||
startSample = numSourceSamples - maxBlockLengthToUse;
|
||||
numSourceSamples = maxBlockLengthToUse;
|
||||
iter = incomingMessages.findNextSamplePosition (startSample);
|
||||
}
|
||||
|
||||
scale = (numSamples << 10) / numSourceSamples;
|
||||
|
||||
std::for_each (iter, incomingMessages.cend(), [&] (const MidiMessageMetadata& meta)
|
||||
{
|
||||
const auto pos = ((meta.samplePosition - startSample) * scale) >> 10;
|
||||
destBuffer.addEvent (meta.data, meta.numBytes, jlimit (0, numSamples - 1, pos));
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// if our event list is shorter than the number we need, put them
|
||||
// towards the end of the buffer
|
||||
startSample = numSamples - numSourceSamples;
|
||||
|
||||
for (const auto metadata : incomingMessages)
|
||||
destBuffer.addEvent (metadata.data, metadata.numBytes,
|
||||
jlimit (0, numSamples - 1, metadata.samplePosition + startSample));
|
||||
}
|
||||
|
||||
incomingMessages.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void MidiMessageCollector::ensureStorageAllocated (size_t bytes)
|
||||
{
|
||||
incomingMessages.ensureSize (bytes);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
|
||||
{
|
||||
MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
|
||||
m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
|
||||
|
||||
addMessageToQueue (m);
|
||||
}
|
||||
|
||||
void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
|
||||
{
|
||||
MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber, velocity));
|
||||
m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
|
||||
|
||||
addMessageToQueue (m);
|
||||
}
|
||||
|
||||
void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
|
||||
{
|
||||
addMessageToQueue (message);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Collects incoming realtime MIDI messages and turns them into blocks suitable for
|
||||
processing by a block-based audio callback.
|
||||
|
||||
The class can also be used as either a MidiKeyboardState::Listener or a MidiInputCallback
|
||||
so it can easily use a midi input or keyboard component as its source.
|
||||
|
||||
@see MidiMessage, MidiInput
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiMessageCollector : public MidiKeyboardState::Listener,
|
||||
public MidiInputCallback
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a MidiMessageCollector. */
|
||||
MidiMessageCollector();
|
||||
|
||||
/** Destructor. */
|
||||
~MidiMessageCollector() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Clears any messages from the queue.
|
||||
|
||||
You need to call this method before starting to use the collector, so that
|
||||
it knows the correct sample rate to use.
|
||||
*/
|
||||
void reset (double sampleRate);
|
||||
|
||||
/** Takes an incoming real-time message and adds it to the queue.
|
||||
|
||||
The message's timestamp is taken, and it will be ready for retrieval as part
|
||||
of the block returned by the next call to removeNextBlockOfMessages().
|
||||
|
||||
This method is fully thread-safe when overlapping calls are made with
|
||||
removeNextBlockOfMessages().
|
||||
*/
|
||||
void addMessageToQueue (const MidiMessage& message);
|
||||
|
||||
/** Removes all the pending messages from the queue as a buffer.
|
||||
|
||||
This will also correct the messages' timestamps to make sure they're in
|
||||
the range 0 to numSamples - 1.
|
||||
|
||||
This call should be made regularly by something like an audio processing
|
||||
callback, because the time that it happens is used in calculating the
|
||||
midi event positions.
|
||||
|
||||
This method is fully thread-safe when overlapping calls are made with
|
||||
addMessageToQueue().
|
||||
|
||||
Precondition: numSamples must be greater than 0.
|
||||
*/
|
||||
void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
|
||||
|
||||
/** Preallocates storage for collected messages.
|
||||
|
||||
This can be called before audio processing begins to ensure that there
|
||||
is sufficient space for the expected MIDI messages, in order to avoid
|
||||
allocations within the audio callback.
|
||||
*/
|
||||
void ensureStorageAllocated (size_t bytes);
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
void handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
|
||||
/** @internal */
|
||||
void handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
|
||||
/** @internal */
|
||||
void handleIncomingMidiMessage (MidiInput*, const MidiMessage&) override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
double lastCallbackTime = 0;
|
||||
CriticalSection midiCallbackLock;
|
||||
MidiBuffer incomingMessages;
|
||||
double sampleRate = 44100.0;
|
||||
#if JUCE_DEBUG
|
||||
bool hasCalledReset = false;
|
||||
#endif
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/**
|
||||
@internal
|
||||
|
||||
A simple type that allows reporting and waiting for millisecond time intervals.
|
||||
*/
|
||||
struct TimeProvider
|
||||
{
|
||||
uint32_t getMillisecondCounter() const
|
||||
{
|
||||
return Time::getMillisecondCounter();
|
||||
}
|
||||
|
||||
void waitForMillisecondCounter (uint32_t c) const
|
||||
{
|
||||
Time::waitForMillisecondCounter (c);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@internal
|
||||
|
||||
Stores events ordered by their timestamps.
|
||||
Popping an event will not always retrieve the event with the smallest timestamp, since that
|
||||
event might be scheduled after the current timer wraps around. Instead, a read pointer is
|
||||
maintained, and popping an event will return the event at the current position of the read
|
||||
pointer. Adding an event generally does not affect the position of the read pointer, with the
|
||||
exception that adding an event whose time falls between the current time and the next event time
|
||||
will also set the read pointer to reference that added event.
|
||||
|
||||
The Event type must have a getTimeStamp() member function that returns the output time of the
|
||||
event as a uint32_t.
|
||||
*/
|
||||
template <typename Event, typename TimeProvider = TimeProvider>
|
||||
class ScheduledEventQueue
|
||||
{
|
||||
public:
|
||||
explicit ScheduledEventQueue (const TimeProvider* tp)
|
||||
: timeProvider (tp)
|
||||
{
|
||||
}
|
||||
|
||||
void clearAllPendingMessages()
|
||||
{
|
||||
while (! pendingMessages.empty())
|
||||
storage.push_back (pendingMessages.extract (pendingMessages.begin()));
|
||||
|
||||
nextMessage = pendingMessages.end();
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return nextMessage == pendingMessages.end();
|
||||
}
|
||||
|
||||
/* Add a new event to the queue.
|
||||
|
||||
Events are always considered to be scheduled after the time provider's current time, minus
|
||||
some leeway specified by leewayMs.
|
||||
|
||||
An event timestamp that is less than the current provider time minus the leeway value
|
||||
indicates that the event is scheduled after the time provider wraps around.
|
||||
|
||||
The purpose of the leeway is to allow the thread that is popping events to 'catch up' with
|
||||
the thread(s) that are adding events, in the case that the reader gets stalled.
|
||||
It's unlikely for the writer threads to be scheduling events 49.7 days in the future, so new
|
||||
events with timestamps in the past up to leewayMs ago (relative to the time provider)
|
||||
will be scheduled to play as soon as possible.
|
||||
*/
|
||||
void addEvent (const Event& event, uint32_t leewayMs = 1000 * 60 * 60)
|
||||
{
|
||||
if (! storage.empty())
|
||||
{
|
||||
auto extracted = std::move (storage.back());
|
||||
storage.pop_back();
|
||||
extracted.value() = event;
|
||||
pendingMessages.insert (std::move (extracted));
|
||||
}
|
||||
else
|
||||
{
|
||||
pendingMessages.insert (event);
|
||||
}
|
||||
|
||||
if (nextMessage == pendingMessages.end())
|
||||
{
|
||||
nextMessage = pendingMessages.begin();
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto timebase = (uint32_t) timeProvider->getMillisecondCounter() - leewayMs;
|
||||
const auto msToThis = (uint32_t) event.getTimeStamp() - timebase;
|
||||
const auto msToNext = (uint32_t) nextMessage->getTimeStamp() - timebase;
|
||||
|
||||
if (msToThis < msToNext)
|
||||
nextMessage = std::prev (nextMessage == pendingMessages.begin() ? pendingMessages.end() : nextMessage);
|
||||
}
|
||||
}
|
||||
|
||||
using PoppedEvent = std::variant<uint32_t, Event>;
|
||||
|
||||
/* Compares the timestamp of the event currently at the 'next' pointer with the current
|
||||
provider time.
|
||||
- If the next event time is less than leewayMs milliseconds in the future, or slightly
|
||||
in the past, returns that event and removes it from the queue.
|
||||
- If the next event time is more than leewayMs milliseconds in the future, returns a
|
||||
suggested duration to wait in milliseconds before reattempting to retrieve the event, and
|
||||
leaves the event in the queue.
|
||||
- If the next event is a long way in the past, removes the event from the queue and returns
|
||||
a pause duration of 0, indicating that the calling thread should try to retrieve the
|
||||
following event as quickly as possible in order to catch up with the time provider.
|
||||
- If the queue is empty, returns an infinite timeout.
|
||||
*/
|
||||
PoppedEvent popEvent (uint32_t leewayMs = 20)
|
||||
{
|
||||
if (nextMessage == pendingMessages.end())
|
||||
return std::numeric_limits<uint32_t>::max();
|
||||
|
||||
const auto now = (uint32_t) timeProvider->getMillisecondCounter();
|
||||
const auto timestamp = (uint32_t) nextMessage->getTimeStamp();
|
||||
const auto difference = timestamp - now;
|
||||
|
||||
if (leewayMs < difference && difference <= std::numeric_limits<uint32_t>::max() / 2)
|
||||
return difference - leewayMs;
|
||||
|
||||
const ScopeGuard scope { [&]
|
||||
{
|
||||
storage.push_back (pendingMessages.extract (std::exchange (nextMessage, std::next (nextMessage))));
|
||||
|
||||
if (nextMessage == pendingMessages.end())
|
||||
nextMessage = pendingMessages.begin();
|
||||
} };
|
||||
|
||||
if (difference <= leewayMs || std::numeric_limits<uint32_t>::max() - 200 < difference)
|
||||
return std::move (*nextMessage);
|
||||
|
||||
return (uint32_t) 0;
|
||||
}
|
||||
|
||||
uint32_t getTimeOfNextEvent() const
|
||||
{
|
||||
jassert (! empty());
|
||||
return nextMessage->getTimeStamp();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Comparator
|
||||
{
|
||||
bool operator() (const Event& a, const Event& b) const
|
||||
{
|
||||
return (uint32_t) a.getTimeStamp() < (uint32_t) b.getTimeStamp();
|
||||
}
|
||||
};
|
||||
|
||||
const TimeProvider* timeProvider = nullptr;
|
||||
std::multiset<Event, Comparator> pendingMessages;
|
||||
std::vector<typename decltype (pendingMessages)::node_type> storage;
|
||||
typename decltype (pendingMessages)::const_iterator nextMessage = pendingMessages.end();
|
||||
};
|
||||
|
||||
/**
|
||||
@internal
|
||||
|
||||
Allows events to be queued up, then for each event calls the OutputCallback at the time
|
||||
dictated by that event's timestamp.
|
||||
|
||||
The Event type must have a getTimeStamp() member function that returns the output time of the
|
||||
event as a uint32_t.
|
||||
*/
|
||||
template <typename Event, typename TimeProvider = TimeProvider>
|
||||
class ScheduledEventThread : private Thread,
|
||||
private TimeProvider
|
||||
{
|
||||
public:
|
||||
using OutputCallback = std::function<void (const Event&)>;
|
||||
|
||||
explicit ScheduledEventThread (OutputCallback&& c)
|
||||
: Thread (SystemStats::getJUCEVersion() + ": MIDI Out"),
|
||||
outputCallback (std::move (c))
|
||||
{
|
||||
jassert (outputCallback != nullptr);
|
||||
}
|
||||
|
||||
~ScheduledEventThread() override
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void clearAllPendingMessages()
|
||||
{
|
||||
{
|
||||
const std::scoped_lock sl (mutex);
|
||||
queue.clearAllPendingMessages();
|
||||
}
|
||||
|
||||
condvar.notify_one();
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
{
|
||||
const std::scoped_lock sl (mutex);
|
||||
backgroundThreadRunning = true;
|
||||
}
|
||||
|
||||
startThread (Priority::high);
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
{
|
||||
const std::scoped_lock sl (mutex);
|
||||
backgroundThreadRunning = false;
|
||||
}
|
||||
|
||||
condvar.notify_one();
|
||||
stopThread (-1);
|
||||
}
|
||||
|
||||
void addEvent (const Event& event)
|
||||
{
|
||||
// You've got to call startBackgroundThread() for this to actually work.
|
||||
jassert (isThreadRunning());
|
||||
|
||||
{
|
||||
const std::scoped_lock sl (mutex);
|
||||
queue.addEvent (event);
|
||||
}
|
||||
|
||||
condvar.notify_one();
|
||||
}
|
||||
|
||||
bool isRunning() const
|
||||
{
|
||||
const std::scoped_lock sl (mutex);
|
||||
return backgroundThreadRunning;
|
||||
}
|
||||
|
||||
private:
|
||||
void run() override
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
struct Return {};
|
||||
|
||||
const auto loopStatus = std::invoke ([&]() -> std::variant<std::monostate, Return, Event>
|
||||
{
|
||||
std::unique_lock lock (mutex);
|
||||
condvar.wait (lock, [&] { return ! queue.empty() || ! backgroundThreadRunning; });
|
||||
|
||||
if (! backgroundThreadRunning)
|
||||
return Return{};
|
||||
|
||||
auto maybeEvent = queue.popEvent();
|
||||
|
||||
if (auto* event = std::get_if<Event> (&maybeEvent))
|
||||
return std::move (*event);
|
||||
|
||||
// Adding an event always notifies the condition variable, so this should always
|
||||
// get unblocked, even if waiting on an effectively infinite timeout.
|
||||
if (auto* pause = std::get_if<uint32_t> (&maybeEvent))
|
||||
if (*pause != 0)
|
||||
condvar.wait_for (lock, std::chrono::milliseconds { *pause });
|
||||
|
||||
return {};
|
||||
});
|
||||
|
||||
if (std::holds_alternative<Return> (loopStatus))
|
||||
return;
|
||||
|
||||
if (auto* event = std::get_if<Event> (&loopStatus))
|
||||
{
|
||||
const auto eventTime = (uint32_t) event->getTimeStamp();
|
||||
const auto difference = eventTime - (uint32_t) this->getMillisecondCounter();
|
||||
|
||||
// Difference will either be fairly small (for an event in the future), or
|
||||
// huge (for an event in the past). We only want to wait if the difference is small.
|
||||
if (difference < std::numeric_limits<uint32_t>::max() / 2)
|
||||
this->waitForMillisecondCounter (eventTime);
|
||||
|
||||
outputCallback (*event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutable std::mutex mutex;
|
||||
std::condition_variable condvar;
|
||||
ScheduledEventQueue<Event, TimeProvider> queue { this };
|
||||
OutputCallback outputCallback;
|
||||
bool backgroundThreadRunning = false;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class ScheduledEventQueueTests : public UnitTest
|
||||
{
|
||||
public:
|
||||
ScheduledEventQueueTests()
|
||||
: UnitTest ("ScheduledEventQueue", UnitTestCategories::midi)
|
||||
{
|
||||
}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
struct Event
|
||||
{
|
||||
uint32_t getTimeStamp() const { return time; }
|
||||
uint32_t time;
|
||||
};
|
||||
|
||||
struct LocalTimeProvider
|
||||
{
|
||||
uint32_t currentTime;
|
||||
|
||||
uint32_t getMillisecondCounter() const
|
||||
{
|
||||
return currentTime;
|
||||
}
|
||||
};
|
||||
|
||||
LocalTimeProvider timeProvider;
|
||||
ScheduledEventQueue<Event, LocalTimeProvider> queue { &timeProvider };
|
||||
|
||||
testCase ("An empty queue returns an infinite timeout when popping an event", [&]
|
||||
{
|
||||
expect (queue.empty());
|
||||
const auto popped = queue.popEvent();
|
||||
auto* timeout = std::get_if<uint32_t> (&popped);
|
||||
expect (timeout != nullptr);
|
||||
|
||||
if (timeout != nullptr)
|
||||
expect (*timeout == std::numeric_limits<uint32_t>::max());
|
||||
});
|
||||
|
||||
testCase ("Adding an event to an empty queue makes that event the next event", [&]
|
||||
{
|
||||
constexpr uint32_t time = 100;
|
||||
queue.addEvent (Event { time });
|
||||
expect (queue.getTimeOfNextEvent() == time);
|
||||
|
||||
queue.clearAllPendingMessages();
|
||||
expect (queue.empty());
|
||||
});
|
||||
|
||||
testCase ("Adding an event to a single-element queue remains sorted", [&]
|
||||
{
|
||||
queue.addEvent (Event { 100 });
|
||||
queue.addEvent (Event { 200 });
|
||||
|
||||
expect (queue.getTimeOfNextEvent() == 100);
|
||||
|
||||
queue.clearAllPendingMessages();
|
||||
|
||||
queue.addEvent (Event { 100 });
|
||||
queue.addEvent (Event { 50 });
|
||||
|
||||
expect (queue.getTimeOfNextEvent() == 50);
|
||||
|
||||
queue.clearAllPendingMessages();
|
||||
});
|
||||
|
||||
testCase ("Adding an event when the 'next' even is slightly in the past doesn't drop or postpone the next event", [&]
|
||||
{
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { 100 });
|
||||
timeProvider.currentTime = 110;
|
||||
queue.addEvent (Event { 120 });
|
||||
|
||||
expect (queue.getTimeOfNextEvent() == 100);
|
||||
|
||||
queue.clearAllPendingMessages();
|
||||
});
|
||||
|
||||
testCase ("Popping an event returns the next event if it is not too far in the past or future", [&]
|
||||
{
|
||||
constexpr uint32_t eventTime = 100;
|
||||
constexpr uint32_t leeway = 20;
|
||||
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { eventTime });
|
||||
auto popped = queue.popEvent (leeway);
|
||||
|
||||
// In the future, this should be a continue
|
||||
const auto* timeout = std::get_if<uint32_t> (&popped);
|
||||
expect (timeout != nullptr);
|
||||
|
||||
if (timeout != nullptr)
|
||||
expect (*timeout == eventTime - leeway);
|
||||
|
||||
expect (! queue.empty());
|
||||
|
||||
// Within our leeway
|
||||
timeProvider.currentTime = 80;
|
||||
popped = queue.popEvent (leeway);
|
||||
|
||||
const auto* got = std::get_if<Event> (&popped);
|
||||
expect (got != nullptr);
|
||||
|
||||
if (got != nullptr)
|
||||
expect (got->time == eventTime);
|
||||
|
||||
expect (queue.empty());
|
||||
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { eventTime });
|
||||
|
||||
// Exactly on time
|
||||
timeProvider.currentTime = 100;
|
||||
popped = queue.popEvent (leeway);
|
||||
|
||||
const auto* current = std::get_if<Event> (&popped);
|
||||
expect (current != nullptr);
|
||||
|
||||
if (current != nullptr)
|
||||
expect (current->time == eventTime);
|
||||
|
||||
expect (queue.empty());
|
||||
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { eventTime });
|
||||
|
||||
// Missed deadline by a little
|
||||
timeProvider.currentTime = 200;
|
||||
popped = queue.popEvent (leeway);
|
||||
|
||||
const auto* delayed = std::get_if<Event> (&popped);
|
||||
expect (delayed != nullptr);
|
||||
|
||||
if (delayed != nullptr)
|
||||
expect (delayed->time == eventTime);
|
||||
|
||||
expect (queue.empty());
|
||||
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { eventTime });
|
||||
|
||||
// Missed deadline by a lot
|
||||
timeProvider.currentTime = 1'000;
|
||||
popped = queue.popEvent (leeway);
|
||||
|
||||
const auto* missed = std::get_if<uint32_t> (&popped);
|
||||
expect (missed != nullptr);
|
||||
|
||||
if (missed != nullptr)
|
||||
expect (*missed == 0);
|
||||
|
||||
expect (queue.empty());
|
||||
});
|
||||
|
||||
testCase ("Added events are sorted relative to the time provider", [&]
|
||||
{
|
||||
timeProvider.currentTime = 0;
|
||||
queue.addEvent (Event { std::numeric_limits<uint32_t>::max() - 10 });
|
||||
expect (queue.getTimeOfNextEvent() == std::numeric_limits<uint32_t>::max() - 10);
|
||||
|
||||
queue.addEvent (Event { std::numeric_limits<uint32_t>::max() - 11 });
|
||||
expect (queue.getTimeOfNextEvent() == std::numeric_limits<uint32_t>::max() - 11);
|
||||
|
||||
queue.clearAllPendingMessages();
|
||||
|
||||
timeProvider.currentTime = std::numeric_limits<uint32_t>::max() - 20;
|
||||
|
||||
const auto numMsInTwoHours = 1000 * 60 * 60 * 2;
|
||||
queue.addEvent (Event { std::numeric_limits<uint32_t>::max() - numMsInTwoHours });
|
||||
expect (queue.getTimeOfNextEvent() == std::numeric_limits<uint32_t>::max() - numMsInTwoHours);
|
||||
|
||||
queue.addEvent (Event { std::numeric_limits<uint32_t>::max() - 10 });
|
||||
expect (queue.getTimeOfNextEvent() == std::numeric_limits<uint32_t>::max() - 10);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
static ScheduledEventQueueTests scheduledEventQueueTests;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class WaitFreeListenersTest : public UnitTest
|
||||
{
|
||||
public:
|
||||
struct Listener
|
||||
{
|
||||
virtual ~Listener() = default;
|
||||
virtual void notify() = 0;
|
||||
};
|
||||
|
||||
WaitFreeListenersTest() : UnitTest ("WaitFreeListeners", UnitTestCategories::midi) {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
using Receivers = WaitFreeListeners<Listener>;
|
||||
|
||||
struct CountingReceiver : public Listener
|
||||
{
|
||||
void notify() override { ++numCalls; }
|
||||
int numCalls = 0;
|
||||
};
|
||||
|
||||
testCase ("Adding and immediately removing a receiver works", [&]
|
||||
{
|
||||
Receivers receivers;
|
||||
CountingReceiver receiver;
|
||||
receivers.add (receiver);
|
||||
|
||||
expect (receiver.numCalls == 0);
|
||||
|
||||
receivers.remove (receiver);
|
||||
|
||||
expect (receiver.numCalls == 0);
|
||||
});
|
||||
|
||||
testCase ("Notifying receivers works", [&]
|
||||
{
|
||||
Receivers receivers;
|
||||
std::array<CountingReceiver, 63> receiverArray;
|
||||
|
||||
for (size_t i = 0; i < receiverArray.size(); ++i)
|
||||
{
|
||||
receivers.add (receiverArray[i]);
|
||||
|
||||
expect (receiverArray[i].numCalls == 0);
|
||||
|
||||
receivers.call ([] (auto& l) { l.notify(); });
|
||||
|
||||
expect (receiverArray[i].numCalls == 1);
|
||||
}
|
||||
|
||||
expect ((size_t) receiverArray.front().numCalls == receiverArray.size());
|
||||
});
|
||||
|
||||
testCase ("Adding and removing receivers while notifying them works", [&]
|
||||
{
|
||||
std::atomic<bool> exit { false };
|
||||
Receivers receivers;
|
||||
|
||||
std::thread notifier
|
||||
{
|
||||
[&]
|
||||
{
|
||||
while (! exit)
|
||||
receivers.call ([] (auto& l) { l.notify(); });
|
||||
}
|
||||
};
|
||||
|
||||
std::vector<std::thread> responders;
|
||||
|
||||
for (size_t i = 0; i < 10; ++i)
|
||||
{
|
||||
responders.emplace_back ([&]
|
||||
{
|
||||
for (auto attempt = 0; attempt < 100; ++attempt)
|
||||
{
|
||||
CountingReceiver counter;
|
||||
|
||||
receivers.add (counter);
|
||||
receivers.remove (counter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (auto& t : responders)
|
||||
t.join();
|
||||
|
||||
exit = true;
|
||||
notifier.join();
|
||||
});
|
||||
|
||||
testCase ("Concurrent calls work", [&]
|
||||
{
|
||||
Receivers receivers;
|
||||
|
||||
class StageGate
|
||||
{
|
||||
public:
|
||||
void waitForStageThenProceed (int s)
|
||||
{
|
||||
std::unique_lock lock { mutex };
|
||||
condvar.wait (lock, [&] { return stage == s; });
|
||||
stage = s + 1;
|
||||
condvar.notify_all();
|
||||
}
|
||||
|
||||
private:
|
||||
std::condition_variable condvar;
|
||||
std::mutex mutex;
|
||||
int stage = 0;
|
||||
};
|
||||
|
||||
struct TestReceiver : public Listener { void notify() override {} };
|
||||
|
||||
TestReceiver testReceiver;
|
||||
receivers.add (testReceiver);
|
||||
|
||||
std::vector<std::thread> notifiers;
|
||||
|
||||
StageGate gate;
|
||||
|
||||
notifiers.emplace_back ([&]
|
||||
{
|
||||
receivers.call ([&] (auto&)
|
||||
{
|
||||
gate.waitForStageThenProceed (1);
|
||||
gate.waitForStageThenProceed (3);
|
||||
});
|
||||
|
||||
gate.waitForStageThenProceed (4);
|
||||
});
|
||||
|
||||
notifiers.emplace_back ([&]
|
||||
{
|
||||
gate.waitForStageThenProceed (2);
|
||||
|
||||
receivers.call ([&] (auto&)
|
||||
{
|
||||
gate.waitForStageThenProceed (5);
|
||||
});
|
||||
});
|
||||
|
||||
gate.waitForStageThenProceed (0);
|
||||
gate.waitForStageThenProceed (6);
|
||||
|
||||
for (auto& t : notifiers)
|
||||
t.join();
|
||||
|
||||
receivers.remove (testReceiver);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
static WaitFreeListenersTest receiversTest;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/*
|
||||
Similar to ListenerList, but more suitable for the (rare!) cases where
|
||||
updates are triggered from a real-time thread. Triggering updates will
|
||||
never block, but adding and removing listeners might.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
template <typename Listener>
|
||||
class WaitFreeListeners
|
||||
{
|
||||
public:
|
||||
static_assert (alignof (Listener) != 1);
|
||||
|
||||
WaitFreeListeners() = default;
|
||||
|
||||
/** Registers a receiver, *not* wait-free */
|
||||
void add (Listener& r)
|
||||
{
|
||||
auto copy = std::invoke ([&]
|
||||
{
|
||||
const std::scoped_lock lock { mainCopyMutex };
|
||||
mainCopy.emplace (&r, std::make_shared<Entry> (r));
|
||||
|
||||
std::vector<std::shared_ptr<Entry>> entries (mainCopy.size());
|
||||
std::transform (mainCopy.begin(), mainCopy.end(), entries.begin(), [] (const auto& p) { return p.second; });
|
||||
return entries;
|
||||
});
|
||||
|
||||
{
|
||||
const SpinLock::ScopedLockType lock { blockingCopyMutex };
|
||||
blockingCopy = std::move (copy);
|
||||
listChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes a listener, *not* wait-free. */
|
||||
void remove (Listener& l)
|
||||
{
|
||||
const auto entryToClear = std::invoke ([&]
|
||||
{
|
||||
const std::scoped_lock lock { mainCopyMutex };
|
||||
const auto iter = mainCopy.find (&l);
|
||||
return iter != mainCopy.end() ? iter->second : nullptr;
|
||||
});
|
||||
|
||||
if (entryToClear != nullptr)
|
||||
{
|
||||
auto& entry = *entryToClear;
|
||||
|
||||
constexpr size_t expected = 1;
|
||||
auto tmp = expected;
|
||||
|
||||
// If the count is zero, clear the entire entry. If the entry is set to zero
|
||||
// in the meantime, that means someone else has removed this entry, so we can exit
|
||||
// in that case.
|
||||
while (! entry.useCount.compare_exchange_weak (tmp, 0) && tmp != 0)
|
||||
tmp = expected;
|
||||
}
|
||||
|
||||
const std::scoped_lock lock { mainCopyMutex };
|
||||
mainCopy.erase (&l);
|
||||
}
|
||||
|
||||
/** Notifies all registered receivers, wait-free, may be called concurrently with add/remove,
|
||||
and with itself.
|
||||
*/
|
||||
template <typename Callback>
|
||||
void call (Callback&& callback) const
|
||||
{
|
||||
{
|
||||
const SpinLock::ScopedTryLockType lock { blockingCopyMutex };
|
||||
|
||||
if (lock.isLocked() && std::exchange (listChanged, false))
|
||||
std::swap (callerCopy, blockingCopy);
|
||||
}
|
||||
|
||||
for (auto& entry : callerCopy)
|
||||
{
|
||||
const auto oldUseCount = entry->useCount.fetch_add (1);
|
||||
|
||||
if (oldUseCount != 0)
|
||||
callback (*entry->listener);
|
||||
|
||||
entry->useCount -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (WaitFreeListeners)
|
||||
JUCE_DECLARE_NON_MOVEABLE (WaitFreeListeners)
|
||||
|
||||
private:
|
||||
struct Entry
|
||||
{
|
||||
explicit Entry (Listener& l) : listener (&l) {}
|
||||
Listener* listener{};
|
||||
std::atomic<size_t> useCount { 1 };
|
||||
};
|
||||
std::map<Listener*, std::shared_ptr<Entry>> mainCopy;
|
||||
mutable std::vector<std::shared_ptr<Entry>> blockingCopy, callerCopy;
|
||||
|
||||
mutable std::mutex mainCopyMutex;
|
||||
mutable SpinLock blockingCopyMutex;
|
||||
mutable bool listChanged = false;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
bool Block::operator== (const Block& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tuple (x.info, x.name); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool Block::operator!= (const Block& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a Function Block (FB) or Group Terminal Block (GTB).
|
||||
|
||||
GTBs are only available in USB MIDI, so devices on non-USB transports will not expose GTB
|
||||
information. In the case that a device only exposes GTBs and not FBs, default values will
|
||||
be used for any fields that are unavailable in the GTB definition.
|
||||
|
||||
@see BlockInfo
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Block
|
||||
{
|
||||
public:
|
||||
Block() = default;
|
||||
|
||||
[[nodiscard]] Block withName (const String& x) const { return withMember (*this, &Block::name, x); }
|
||||
|
||||
[[nodiscard]] Block withFirstGroup (uint8_t x) const { return withMember (*this, &Block::info, info.withFirstGroup (x)); }
|
||||
[[nodiscard]] Block withNumGroups (uint8_t x) const { return withMember (*this, &Block::info, info.withNumGroups (x)); }
|
||||
[[nodiscard]] Block withMaxSysex8Streams (uint8_t x) const { return withMember (*this, &Block::info, info.withMaxSysex8Streams (x)); }
|
||||
[[nodiscard]] Block withEnabled (bool x = true) const { return withMember (*this, &Block::info, info.withEnabled (x)); }
|
||||
|
||||
[[nodiscard]] Block withUiHint (BlockUiHint x) const
|
||||
{
|
||||
return withMember (*this, &Block::info, info.withUiHint (x));
|
||||
}
|
||||
|
||||
[[nodiscard]] Block withMIDI1ProxyKind (BlockMIDI1ProxyKind x) const
|
||||
{
|
||||
return withMember (*this, &Block::info, info.withMIDI1ProxyKind (x));
|
||||
}
|
||||
|
||||
[[nodiscard]] Block withDirection (BlockDirection x) const
|
||||
{
|
||||
return withMember (*this, &Block::info, info.withDirection (x));
|
||||
}
|
||||
|
||||
/** The name of the block, if any. */
|
||||
String getName() const { return name; }
|
||||
|
||||
/** All info relating to this block. */
|
||||
BlockInfo getInfo() const { return info; }
|
||||
|
||||
/** In the range 0x0 to 0xF inclusive. */
|
||||
uint8_t getFirstGroup() const
|
||||
{
|
||||
return info.getFirstGroup();
|
||||
}
|
||||
|
||||
/** In the range 0x01 to 0x10 inclusive. */
|
||||
uint8_t getNumGroups() const
|
||||
{
|
||||
return info.getNumGroups();
|
||||
}
|
||||
|
||||
/** The number of simultaneous Sysex8 streams that are supported. */
|
||||
uint8_t getMaxSysex8Streams() const
|
||||
{
|
||||
return info.getMaxSysex8Streams();
|
||||
}
|
||||
|
||||
/** Some blocks may support bidirectional communication (e.g. for CI) but function predominantly
|
||||
as a sender or receiver. The direction returned here is a hint to the user that doesn't
|
||||
necessarily reflect the hardware capabilities.
|
||||
*/
|
||||
BlockUiHint getUiHint() const
|
||||
{
|
||||
return info.getUiHint();
|
||||
}
|
||||
|
||||
/** If this block is a proxy for a MIDI 1.0 stream, describes the capabilities of that stream. */
|
||||
BlockMIDI1ProxyKind getMIDI1ProxyKind() const
|
||||
{
|
||||
return info.getMIDI1ProxyKind();
|
||||
}
|
||||
|
||||
/** Returns the message transmission directions that are supported by this block.
|
||||
Use this to determine block capabilities.
|
||||
For information that will be displayed to the user, prefer getUIHint().
|
||||
*/
|
||||
BlockDirection getDirection() const
|
||||
{
|
||||
return info.getDirection();
|
||||
}
|
||||
|
||||
/** True if this block is enabled. */
|
||||
bool isEnabled() const
|
||||
{
|
||||
return info.isEnabled();
|
||||
}
|
||||
|
||||
/** True if the names of the two blocks match. */
|
||||
bool nameMatches (const Block& other) const
|
||||
{
|
||||
return name == other.name;
|
||||
}
|
||||
|
||||
/** True if the BlockInfo of the two blocks match. */
|
||||
bool infoMatches (const Block& other) const
|
||||
{
|
||||
return info == other.info;
|
||||
}
|
||||
|
||||
bool operator== (const Block& other) const;
|
||||
bool operator!= (const Block& other) const;
|
||||
|
||||
private:
|
||||
BlockInfo info;
|
||||
String name;
|
||||
};
|
||||
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An interface class for entities that are interested in disconnection notifications.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct JUCE_API DisconnectionListener
|
||||
{
|
||||
DisconnectionListener() = default;
|
||||
|
||||
DisconnectionListener (const DisconnectionListener&) = default;
|
||||
DisconnectionListener (DisconnectionListener&&) noexcept = default;
|
||||
|
||||
DisconnectionListener& operator= (const DisconnectionListener&) = default;
|
||||
DisconnectionListener& operator= (DisconnectionListener&&) noexcept = default;
|
||||
|
||||
virtual ~DisconnectionListener() = default;
|
||||
|
||||
/** Called to notify that the system has destroyed/disconnected a resource. */
|
||||
virtual void disconnected() = 0;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
bool Endpoint::operator== (const Endpoint& other) const
|
||||
{
|
||||
const auto selfBlocks = getBlocks();
|
||||
const auto otherBlocks = other.getBlocks();
|
||||
|
||||
return std::equal (selfBlocks.begin(), selfBlocks.end(), otherBlocks.begin(), otherBlocks.end())
|
||||
&& other.name == name
|
||||
&& other.productInstanceId == productInstanceId
|
||||
&& other.endpointInfo == endpointInfo
|
||||
&& other.deviceInfo == deviceInfo
|
||||
&& other.streamConfig == streamConfig;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a single MIDI endpoint, which may have up to one input and up to one output.
|
||||
|
||||
An Endpoint object just holds a snapshot of the physical endpoint's last known state at the
|
||||
point when the Endpoint instance was created.
|
||||
Instead of storing Endpoint instances, it's a better idea to store an EndpointId, and to call
|
||||
Endpoints::getEndpoint() to get an up-to-date snapshot.
|
||||
|
||||
To connect to an endpoint, use Session::connectInput() or Session::connectOutput() to create
|
||||
a connection in the context of a particular session.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Endpoint
|
||||
{
|
||||
public:
|
||||
Endpoint() = default;
|
||||
|
||||
[[nodiscard]] Endpoint withName (String x) const { return withMember (*this, &Endpoint::name, x); }
|
||||
[[nodiscard]] Endpoint withProtocol (std::optional<PacketProtocol> x) const { return withMember (*this, &Endpoint::streamConfig, StreamConfigFlags ((streamConfig & ~maskProtocol) | asFlags (x))); }
|
||||
[[nodiscard]] Endpoint withDeviceInfo (DeviceInfo x) const { return withMember (*this, &Endpoint::deviceInfo, std::move (x)); }
|
||||
[[nodiscard]] Endpoint withProductInstanceId (String x) const { return withMember (*this, &Endpoint::productInstanceId, std::move (x)); }
|
||||
[[nodiscard]] Endpoint withUMPVersion (uint8_t major, uint8_t minor) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withVersion (major, minor)); }
|
||||
[[nodiscard]] Endpoint withStaticBlocks (bool x = true) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withStaticFunctionBlocks (x)); }
|
||||
[[nodiscard]] Endpoint withMidi1Support (bool x = true) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withMidi1Support (x)); }
|
||||
[[nodiscard]] Endpoint withMidi2Support (bool x = true) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withMidi2Support (x)); }
|
||||
[[nodiscard]] Endpoint withReceiveJRSupport (bool x = true) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withReceiveJRSupport (x)); }
|
||||
[[nodiscard]] Endpoint withTransmitJRSupport (bool x = true) const { return withMember (*this, &Endpoint::endpointInfo, endpointInfo.withTransmitJRSupport (x)); }
|
||||
|
||||
[[nodiscard]] Endpoint withReceiveJREnabled (bool x = true) const { return withMember (*this, &Endpoint::streamConfig, StreamConfigFlags (x ? (streamConfig | maskRxjr) : (streamConfig & ~maskRxjr))); }
|
||||
[[nodiscard]] Endpoint withTransmitJREnabled (bool x = true) const { return withMember (*this, &Endpoint::streamConfig, StreamConfigFlags (x ? (streamConfig | maskTxjr) : (streamConfig & ~maskTxjr))); }
|
||||
|
||||
/** The block index is used to uniquely identify the block, so be sure to always declare
|
||||
blocks in a consistent order.
|
||||
*/
|
||||
[[nodiscard]] Endpoint withBlocks (Span<const Block> x) const
|
||||
{
|
||||
auto result = withNumBlocks (x.size());
|
||||
std::copy (x.begin(), x.end(), result.blocks.begin());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The number of blocks on this endpoint. */
|
||||
[[nodiscard]] Endpoint withNumBlocks (size_t x) const
|
||||
{
|
||||
jassert (x <= blocks.size());
|
||||
auto result = *this;
|
||||
result.endpointInfo = result.endpointInfo.withNumFunctionBlocks ((uint8_t) std::min (blocks.size(), x));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Returns the name of this endpoint. */
|
||||
String getName() const { return name; }
|
||||
|
||||
/** Returns properties of the device that owns the endpoint. */
|
||||
DeviceInfo getDeviceInfo() const
|
||||
{
|
||||
return deviceInfo;
|
||||
}
|
||||
|
||||
/** Returns the product instance ID if available, or an empty string otherwise.
|
||||
The product instance ID should match the device serial number, and should be unique per
|
||||
manufacturer, family, and model.
|
||||
|
||||
This ID can be used to distinguish between separate devices that have the same DeviceInfo.
|
||||
It can also be used to determine whether separate endpoints are associated with the same
|
||||
device.
|
||||
*/
|
||||
String getProductInstanceId() const
|
||||
{
|
||||
return productInstanceId;
|
||||
}
|
||||
|
||||
/** The protocol that the endpoint currently expects to send and receive; endpoints are allowed
|
||||
to switch protocols, so this won't always return the same value.
|
||||
May return nullopt if the protocol is unknown, perhaps because negotiation has not taken place.
|
||||
*/
|
||||
std::optional<PacketProtocol> getProtocol() const
|
||||
{
|
||||
switch (streamConfig & maskProtocol)
|
||||
{
|
||||
case 1: return PacketProtocol::MIDI_1_0;
|
||||
case 2: return PacketProtocol::MIDI_2_0;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
uint8_t getUMPVersionMajor() const { return endpointInfo.getVersionMajor(); }
|
||||
uint8_t getUMPVersionMinor() const { return endpointInfo.getVersionMinor(); }
|
||||
bool hasStaticBlocks() const { return endpointInfo.hasStaticFunctionBlocks(); }
|
||||
bool hasMidi1Support() const { return endpointInfo.hasMidi1Support(); }
|
||||
bool hasMidi2Support() const { return endpointInfo.hasMidi2Support(); }
|
||||
bool hasReceiveJRSupport() const { return endpointInfo.hasReceiveJRSupport(); }
|
||||
bool hasTransmitJRSupport() const { return endpointInfo.hasTransmitJRSupport(); }
|
||||
|
||||
bool isReceiveJREnabled() const { return streamConfig & maskRxjr; }
|
||||
bool isTransmitJREnabled() const { return streamConfig & maskTxjr; }
|
||||
|
||||
/** There can be a maximum of 32 blocks.
|
||||
This may return an empty span if the endpoint has neither function blocks nor group terminal
|
||||
blocks.
|
||||
*/
|
||||
Span<const Block> getBlocks() const&
|
||||
{
|
||||
return { blocks.data(), endpointInfo.getNumFunctionBlocks() };
|
||||
}
|
||||
|
||||
/** Returns a mutable view over the blocks in this endpoint. */
|
||||
Span<Block> getBlocks() &
|
||||
{
|
||||
return { blocks.data(), endpointInfo.getNumFunctionBlocks() };
|
||||
}
|
||||
|
||||
// These are deleted because it's probably not a good idea to create a span over a temporary
|
||||
Span<const Block> getBlocks() const&& = delete;
|
||||
Span<Block> getBlocks() && = delete;
|
||||
|
||||
bool operator== (const Endpoint&) const;
|
||||
bool operator!= (const Endpoint& other) { return ! operator== (other); }
|
||||
|
||||
private:
|
||||
enum StreamConfigFlags : uint16_t
|
||||
{
|
||||
maskProtocol = 0x00ff,
|
||||
maskTxjr = 0x0100,
|
||||
maskRxjr = 0x0200,
|
||||
};
|
||||
|
||||
static StreamConfigFlags asFlags (std::optional<PacketProtocol> p)
|
||||
{
|
||||
if (! p.has_value())
|
||||
return {};
|
||||
|
||||
switch (*p)
|
||||
{
|
||||
case PacketProtocol::MIDI_1_0: return StreamConfigFlags (1);
|
||||
case PacketProtocol::MIDI_2_0: return StreamConfigFlags (2);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::array<Block, 32> blocks;
|
||||
String name;
|
||||
String productInstanceId;
|
||||
EndpointInfo endpointInfo;
|
||||
DeviceInfo deviceInfo;
|
||||
StreamConfigFlags streamConfig{};
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
auto EndpointId::tie() const { return std::tuple (src, dst); }
|
||||
bool EndpointId::operator== (const EndpointId& x) const { return tie() == x.tie(); }
|
||||
bool EndpointId::operator!= (const EndpointId& x) const { return tie() != x.tie(); }
|
||||
bool EndpointId::operator< (const EndpointId& x) const { return tie() < x.tie(); }
|
||||
bool EndpointId::operator<= (const EndpointId& x) const { return tie() <= x.tie(); }
|
||||
bool EndpointId::operator> (const EndpointId& x) const { return tie() > x.tie(); }
|
||||
bool EndpointId::operator>= (const EndpointId& x) const { return tie() >= x.tie(); }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/** Directional properties of a MIDI endpoint. */
|
||||
enum class IOKind : uint8_t
|
||||
{
|
||||
src, ///< A source of MIDI events
|
||||
dst, ///< A destination for MIDI events
|
||||
};
|
||||
|
||||
/** All possible MIDI directions. */
|
||||
constexpr IOKind ioKinds[] { IOKind::src, IOKind::dst };
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Identifies a MIDI endpoint. This is intended to be an opaque type that can only be compared with
|
||||
other instances.
|
||||
|
||||
For backwards compatibility, we need to ensure that port identifier strings that used to work
|
||||
with MidiInput and MidiOutput continue to function in the same way. However, the old identifiers
|
||||
weren't necessarily unique between inputs and outputs (a MIDI 1.0 input and output could have
|
||||
the same ID), which means that a single id string isn't enough to uniquely identify an input
|
||||
or output port.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class EndpointId
|
||||
{
|
||||
auto tie() const;
|
||||
|
||||
public:
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
EndpointId() = default;
|
||||
|
||||
bool operator== (const EndpointId& x) const;
|
||||
bool operator!= (const EndpointId& x) const;
|
||||
bool operator< (const EndpointId& x) const;
|
||||
bool operator<= (const EndpointId& x) const;
|
||||
bool operator> (const EndpointId& x) const;
|
||||
bool operator>= (const EndpointId& x) const;
|
||||
|
||||
String get (IOKind k) const { return k == IOKind::src ? src : dst; }
|
||||
|
||||
static EndpointId make (IOKind dir, const String& id)
|
||||
{
|
||||
return dir == IOKind::src ? makeSrcDst (id, {}) : makeSrcDst ({}, id);
|
||||
}
|
||||
|
||||
static EndpointId makeSrcDst (const String& s, const String& d)
|
||||
{
|
||||
return { s, d };
|
||||
}
|
||||
|
||||
String src, dst;
|
||||
|
||||
private:
|
||||
EndpointId (const String& s, const String& d) : src (s), dst (d) {}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class Endpoints::Impl : private EndpointsListener
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
virtual Backend getBackend() const = 0;
|
||||
virtual bool isVirtualMidiBytestreamServiceActive() const = 0;
|
||||
virtual bool isVirtualMidiUmpServiceActive() const = 0;
|
||||
virtual void setVirtualMidiBytestreamServiceActive (bool) {}
|
||||
virtual void setVirtualMidiUmpServiceActive (bool) {}
|
||||
virtual void getEndpoints (std::vector<EndpointId>&) const = 0;
|
||||
virtual std::optional<Endpoint> getEndpoint (const EndpointId&) const = 0;
|
||||
virtual std::optional<StaticDeviceInfo> getStaticDeviceInfo (const EndpointId&) const = 0;
|
||||
virtual std::unique_ptr<Session::Impl::Native> makeSession (const String&) = 0;
|
||||
|
||||
static std::unique_ptr<Native> make (EndpointsListener&);
|
||||
};
|
||||
|
||||
Backend getBackend() const
|
||||
{
|
||||
return native->getBackend();
|
||||
}
|
||||
|
||||
bool isVirtualMidiBytestreamServiceActive() const
|
||||
{
|
||||
return native->isVirtualMidiBytestreamServiceActive();
|
||||
}
|
||||
|
||||
bool isVirtualMidiUmpServiceActive() const
|
||||
{
|
||||
return native->isVirtualMidiUmpServiceActive();
|
||||
}
|
||||
|
||||
void setVirtualMidiBytestreamServiceActive (bool x)
|
||||
{
|
||||
native->setVirtualMidiBytestreamServiceActive (x);
|
||||
}
|
||||
|
||||
void setVirtualMidiUmpServiceActive (bool x)
|
||||
{
|
||||
native->setVirtualMidiUmpServiceActive (x);
|
||||
}
|
||||
|
||||
void getEndpoints (std::vector<EndpointId>& x) const
|
||||
{
|
||||
native->getEndpoints (x);
|
||||
}
|
||||
|
||||
std::optional<Endpoint> getEndpoint (const EndpointId& x) const
|
||||
{
|
||||
return native->getEndpoint (x);
|
||||
}
|
||||
|
||||
std::optional<StaticDeviceInfo> getStaticDeviceInfo (const EndpointId& x) const
|
||||
{
|
||||
return native->getStaticDeviceInfo (x);
|
||||
}
|
||||
|
||||
std::unique_ptr<Session::Impl::Native> makeSession (const String& x)
|
||||
{
|
||||
return native->makeSession (x);
|
||||
}
|
||||
|
||||
void addListener (EndpointsListener& x)
|
||||
{
|
||||
listeners.add (&x);
|
||||
}
|
||||
|
||||
void removeListener (EndpointsListener& x)
|
||||
{
|
||||
listeners.remove (&x);
|
||||
}
|
||||
|
||||
static std::unique_ptr<Impl> make()
|
||||
{
|
||||
auto result = rawToUniquePtr (new Impl);
|
||||
result->native = Native::make (*result);
|
||||
|
||||
if (result->native == nullptr)
|
||||
return {};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static String getGlobalMidiClientName()
|
||||
{
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
return app->getApplicationName();
|
||||
|
||||
return "JUCE";
|
||||
}
|
||||
|
||||
private:
|
||||
void endpointsChanged() override
|
||||
{
|
||||
listeners.call ([] (auto& l) { l.endpointsChanged(); });
|
||||
}
|
||||
|
||||
void virtualMidiServiceActiveChanged() override
|
||||
{
|
||||
listeners.call ([] (auto& l) { l.virtualMidiServiceActiveChanged(); });
|
||||
}
|
||||
|
||||
Impl() = default;
|
||||
|
||||
ListenerList<EndpointsListener> listeners;
|
||||
std::unique_ptr<Native> native;
|
||||
};
|
||||
|
||||
void Endpoints::getEndpoints (std::vector<EndpointId>& x) const
|
||||
{
|
||||
x.clear();
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->getEndpoints (x);
|
||||
}
|
||||
|
||||
std::vector<EndpointId> Endpoints::getEndpoints() const
|
||||
{
|
||||
std::vector<EndpointId> result;
|
||||
getEndpoints (result);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<Endpoint> Endpoints::getEndpoint (const EndpointId& x) const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getEndpoint (x);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<StaticDeviceInfo> Endpoints::getStaticDeviceInfo (const EndpointId& x) const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getStaticDeviceInfo (x);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void Endpoints::addListener (EndpointsListener& x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
impl->addListener (x);
|
||||
}
|
||||
|
||||
void Endpoints::removeListener (EndpointsListener& x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
impl->removeListener (x);
|
||||
}
|
||||
|
||||
Session Endpoints::makeSession (const String& x) const
|
||||
{
|
||||
return Session::Impl::makeSession (impl != nullptr ? impl->makeSession (x) : nullptr);
|
||||
}
|
||||
|
||||
std::optional<Backend> Endpoints::getBackend() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getBackend();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool Endpoints::isVirtualMidiBytestreamServiceActive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isVirtualMidiBytestreamServiceActive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Endpoints::isVirtualMidiUmpServiceActive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isVirtualMidiUmpServiceActive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Endpoints::setVirtualMidiBytestreamServiceActive (bool x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
impl->setVirtualMidiBytestreamServiceActive (x);
|
||||
}
|
||||
|
||||
void Endpoints::setVirtualMidiUmpServiceActive (bool x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
impl->setVirtualMidiUmpServiceActive (x);
|
||||
}
|
||||
|
||||
Endpoints::Endpoints()
|
||||
: impl (Impl::make())
|
||||
{
|
||||
}
|
||||
|
||||
Endpoints::~Endpoints()
|
||||
{
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
An interface class for types that are interested in receiving updates
|
||||
about changes to available MIDI endpoints.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct EndpointsListener
|
||||
{
|
||||
EndpointsListener() = default;
|
||||
|
||||
EndpointsListener (const EndpointsListener&) = default;
|
||||
EndpointsListener (EndpointsListener&&) noexcept = default;
|
||||
|
||||
EndpointsListener& operator= (const EndpointsListener&) = default;
|
||||
EndpointsListener& operator= (EndpointsListener&&) noexcept = default;
|
||||
|
||||
virtual ~EndpointsListener() = default;
|
||||
|
||||
/** Called on each platform to notify listeners that some aspect of the MIDI configuration
|
||||
has changed, including device connection, disconnection, and property changes.
|
||||
*/
|
||||
virtual void endpointsChanged() = 0;
|
||||
|
||||
/** Called on Android to indicate that the service managing the virtual MIDI ports
|
||||
was started or stopped.
|
||||
Creating a virtual endpoint will fail if the service is not running, so you may wish to
|
||||
listen for this event, and to create the virtual ports after this function has been called.
|
||||
You can query the current state of the service using Endpoints::isVirtualUmpServiceActive()
|
||||
and Endpoints::isVirtualBytestreamServiceActive().
|
||||
*/
|
||||
virtual void virtualMidiServiceActiveChanged() {}
|
||||
};
|
||||
|
||||
/** MIDI implementation technologies
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
enum class Backend
|
||||
{
|
||||
alsa, ///< linux
|
||||
android, ///< android
|
||||
coremidi, ///< macOS, iOS
|
||||
winmm, ///< classic Windows MIDI
|
||||
winrt, ///< Windows WinRT MIDI 1.0 (experimental)
|
||||
wms, ///< Windows MIDI Services (experimental)
|
||||
};
|
||||
|
||||
/**
|
||||
Endpoints known to the system.
|
||||
|
||||
Use this to locate hardware and software devices that are capable of sending and
|
||||
receiving MIDI messages.
|
||||
|
||||
Call makeSession() to create a session that manages connections to those devices.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Endpoints : public DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
/** Fetch endpoint ids. */
|
||||
std::vector<EndpointId> getEndpoints() const;
|
||||
|
||||
/** Fetch endpoint ids into the provided buffer. */
|
||||
void getEndpoints (std::vector<EndpointId>&) const;
|
||||
|
||||
/** Fetches information about a particular endpoint, or nullopt if the information
|
||||
is unavailable.
|
||||
|
||||
Currently, this function may return nullopt on Android for UMP devices that are
|
||||
connected but not opened.
|
||||
|
||||
If you're displaying endpoint names in a user-facing list, it's probably a good idea to
|
||||
use the Endpoint name if getEndpoint() returns a value. Otherwise, you can use the
|
||||
StaticDeviceInformation name if getStaticDeviceInformation() returns a value. If both
|
||||
functions return nullopt, this implies that the device is unknown/disconnected.
|
||||
*/
|
||||
std::optional<Endpoint> getEndpoint (const EndpointId&) const;
|
||||
|
||||
/** Fetches static information about a particular endpoint, or nullopt if the endpoint is
|
||||
unavailable, which might happen if the endpoint has been disconnected.
|
||||
*/
|
||||
std::optional<StaticDeviceInfo> getStaticDeviceInfo (const EndpointId&) const;
|
||||
|
||||
/** Adds a listener that will receive notifications when endpoints are added, removed,
|
||||
or otherwise changed.
|
||||
*/
|
||||
void addListener (EndpointsListener&);
|
||||
|
||||
/** Removes a listener that was previously added with addListener().
|
||||
*/
|
||||
void removeListener (EndpointsListener&);
|
||||
|
||||
/** Creates a session to manage connections to endpoints.
|
||||
It's possible for this function to fail, in which case Session::isAlive() will return false.
|
||||
*/
|
||||
Session makeSession (const String& name) const;
|
||||
|
||||
/** Returns the technology that is being used to communicate with MIDI devices on this platform.
|
||||
This is mainly relevant on Windows, where there are several different MIDI implementations.
|
||||
|
||||
The intended use of this getter is to allow programs to detect whether the Windows MIDI
|
||||
Services (WMS) are active and running. If initialisation of WMS failed, the implementation
|
||||
will fall back to an earlier, more limited implementation. Programs may wish to detect this
|
||||
situation so that they can direct users to install the WMS SDK.
|
||||
|
||||
If no MIDI technology is available, this returns nullopt.
|
||||
*/
|
||||
std::optional<Backend> getBackend() const;
|
||||
|
||||
/** Creating a virtual legacy port will only succeed if this function returns true.
|
||||
On platforms that support virtual MIDI connections (macOS, iOS, ALSA, Windows MIDI Services),
|
||||
this will normally return true.
|
||||
On platforms that don't support virtual MIDI (older Windows MIDI APIs), this will always
|
||||
return false.
|
||||
On Android, this will return false until the virtual MIDI service has started, and will
|
||||
return true while the service is running.
|
||||
You can listen for virtualMidiServiceActiveChanged() to take actions (e.g. creating or
|
||||
destroying virtual ports) when the service status changes.
|
||||
*/
|
||||
bool isVirtualMidiBytestreamServiceActive() const;
|
||||
|
||||
/** Creating a virtual UMP endpoint will only succeed if this function returns true.
|
||||
On recent platforms that support virtual MIDI connections (recent macOS and iOS, recent ALSA,
|
||||
Windows MIDI Services), this will normally return true.
|
||||
On platforms that don't support virtual MIDI (older Windows MIDI APIs), this will always
|
||||
return false.
|
||||
On Android, this will return false until the virtual MIDI service has started, and will
|
||||
return true while the service is running.
|
||||
You can listen for virtualMidiServiceActiveChanged() to take actions (e.g. creating or
|
||||
destroying virtual ports) when the service status changes.
|
||||
*/
|
||||
bool isVirtualMidiUmpServiceActive() const;
|
||||
|
||||
/** By default, Android MIDI services are initially disabled, but can be enabled by calling
|
||||
this function, passing true.
|
||||
This function is *not synchronous*, so the service will start or stop at some point after
|
||||
this function has returned.
|
||||
To find out when the service state changes, listen for virtualMidiServiceActiveChanged()
|
||||
and check the result of isVirtualMidiBytestreamServiceActive().
|
||||
|
||||
On platforms other than Android, this call does nothing.
|
||||
*/
|
||||
void setVirtualMidiBytestreamServiceActive (bool);
|
||||
|
||||
/** By default, Android MIDI services are initially disabled, but can be enabled by calling
|
||||
this function, passing true.
|
||||
This function is *not synchronous*, so the service will start or stop at some point after
|
||||
this function has returned.
|
||||
To find out when the service state changes, listen for virtualMidiServiceActiveChanged()
|
||||
and check the result of isVirtualMidiUmpServiceActive().
|
||||
On Android versions that don't support virtual UMP (API level < 35), this call does nothing.
|
||||
|
||||
On platforms other than Android, this call does nothing.
|
||||
*/
|
||||
void setVirtualMidiUmpServiceActive (bool);
|
||||
|
||||
JUCE_DECLARE_SINGLETON_INLINE (Endpoints, false)
|
||||
|
||||
~Endpoints() override;
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
Endpoints();
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
struct EndpointAndStaticInfo
|
||||
{
|
||||
Endpoint endpoint;
|
||||
StaticDeviceInfo info;
|
||||
EndpointId id;
|
||||
|
||||
auto tie() const { return std::tuple (endpoint, info, id); }
|
||||
|
||||
bool operator== (const EndpointAndStaticInfo& other) const { return tie() == other.tie(); }
|
||||
bool operator!= (const EndpointAndStaticInfo& other) const { return tie() != other.tie(); }
|
||||
};
|
||||
|
||||
class IOHelpers
|
||||
{
|
||||
public:
|
||||
IOHelpers() = delete;
|
||||
|
||||
static Block makeLegacyBlock (bool isInput)
|
||||
{
|
||||
const auto direction = isInput ? BlockDirection::receiver : BlockDirection::sender;
|
||||
const auto hint = isInput ? BlockUiHint::receiver : BlockUiHint::sender;
|
||||
return Block{}.withName ("Legacy MIDI 1.0")
|
||||
.withEnabled (true)
|
||||
.withFirstGroup (0)
|
||||
.withNumGroups (1)
|
||||
.withMIDI1ProxyKind (BlockMIDI1ProxyKind::unrestrictedBandwidth)
|
||||
.withDirection (direction)
|
||||
.withUiHint (hint);
|
||||
}
|
||||
|
||||
static EndpointAndStaticInfo makeProxyEndpoint (const MidiDeviceInfo& info, BlockDirection direction)
|
||||
{
|
||||
jassert (direction != BlockDirection::unknown);
|
||||
|
||||
const auto hint = std::invoke ([&]
|
||||
{
|
||||
switch (direction)
|
||||
{
|
||||
case BlockDirection::bidirectional: return BlockUiHint::bidirectional;
|
||||
case BlockDirection::sender: return BlockUiHint::sender;
|
||||
case BlockDirection::receiver: return BlockUiHint::receiver;
|
||||
case BlockDirection::unknown: break;
|
||||
}
|
||||
|
||||
return BlockUiHint::unknown;
|
||||
});
|
||||
|
||||
const auto block = Block{}.withDirection (direction)
|
||||
.withUiHint (hint)
|
||||
.withEnabled (true)
|
||||
.withFirstGroup (0)
|
||||
.withNumGroups (1)
|
||||
.withMIDI1ProxyKind (BlockMIDI1ProxyKind::unrestrictedBandwidth);
|
||||
const auto id = std::invoke ([&]
|
||||
{
|
||||
switch (direction)
|
||||
{
|
||||
case BlockDirection::bidirectional:
|
||||
return EndpointId::makeSrcDst (info.identifier, info.identifier);
|
||||
case BlockDirection::receiver:
|
||||
return EndpointId::make (IOKind::dst, info.identifier);
|
||||
case BlockDirection::sender:
|
||||
return EndpointId::make (IOKind::src, info.identifier);
|
||||
case BlockDirection::unknown: break;
|
||||
}
|
||||
|
||||
return EndpointId{};
|
||||
});
|
||||
|
||||
const auto srcId = direction != BlockDirection::receiver ? info.identifier : "";
|
||||
const auto dstId = direction != BlockDirection::sender ? info.identifier : "";
|
||||
|
||||
std::array<String, 16> srcIds { srcId };
|
||||
std::array<String, 16> dstIds { dstId };
|
||||
|
||||
const auto baseEndpoint = Endpoint{}.withName (info.name)
|
||||
.withProtocol (PacketProtocol::MIDI_1_0)
|
||||
.withUMPVersion (1, 1)
|
||||
.withMidi1Support (true)
|
||||
.withStaticBlocks (true)
|
||||
.withBlocks (std::array { block });
|
||||
|
||||
const auto staticInfo = StaticDeviceInfo{}.withLegacyIdentifiersSrc (srcIds)
|
||||
.withLegacyIdentifiersDst (dstIds)
|
||||
.withHasSource (direction == BlockDirection::sender)
|
||||
.withHasDestination (direction == BlockDirection::receiver)
|
||||
.withName (info.name)
|
||||
.withTransport (Transport::bytestream);
|
||||
|
||||
return { baseEndpoint, staticInfo, id };
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class Input::Impl final : private Consumer,
|
||||
private DisconnectionListener
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
/* Returns the ID of the endpoint to which this connection is connected. */
|
||||
virtual EndpointId getEndpointId() const = 0;
|
||||
|
||||
/* The protocol to which incoming messages are converted. */
|
||||
virtual PacketProtocol getProtocol() const = 0;
|
||||
};
|
||||
|
||||
~Impl() override
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
}
|
||||
|
||||
EndpointId getEndpointId() const
|
||||
{
|
||||
return identifier;
|
||||
}
|
||||
|
||||
PacketProtocol getProtocol() const
|
||||
{
|
||||
return protocol;
|
||||
}
|
||||
|
||||
void addConsumer (Consumer& x)
|
||||
{
|
||||
consumers.add (x);
|
||||
}
|
||||
|
||||
void removeConsumer (Consumer& x)
|
||||
{
|
||||
consumers.remove (x);
|
||||
}
|
||||
|
||||
void addDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
disconnectListeners.add (&x);
|
||||
}
|
||||
|
||||
void removeDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
disconnectListeners.remove (&x);
|
||||
}
|
||||
|
||||
bool isAlive() const
|
||||
{
|
||||
return connected && native != nullptr;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
static Input makeInput (Callback&& callback)
|
||||
{
|
||||
auto impl = rawToUniquePtr (new Impl);
|
||||
impl->native = callback (static_cast<DisconnectionListener&> (*impl), static_cast<Consumer&> (*impl));
|
||||
|
||||
if (impl->native == nullptr)
|
||||
return {};
|
||||
|
||||
impl->identifier = impl->native->getEndpointId();
|
||||
impl->protocol = impl->native->getProtocol();
|
||||
return Input { std::move (impl) };
|
||||
}
|
||||
|
||||
private:
|
||||
Impl()
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
}
|
||||
|
||||
void consume (Iterator b, Iterator e, double t) override
|
||||
{
|
||||
consumers.call ([&] (auto& l) { l.consume (b, e, t); });
|
||||
}
|
||||
|
||||
void disconnected() override
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
connected = false;
|
||||
disconnectListeners.call ([] (auto& x) { x.disconnected(); });
|
||||
}
|
||||
|
||||
ListenerList<DisconnectionListener> disconnectListeners;
|
||||
WaitFreeListeners<Consumer> consumers;
|
||||
EndpointId identifier;
|
||||
PacketProtocol protocol;
|
||||
std::unique_ptr<Native> native;
|
||||
std::atomic<bool> connected { true };
|
||||
};
|
||||
|
||||
Input::Input() = default;
|
||||
Input::~Input() = default;
|
||||
Input::Input (std::unique_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
Input::Input (Input&&) noexcept = default;
|
||||
Input& Input::operator= (Input&&) noexcept = default;
|
||||
|
||||
EndpointId Input::getEndpointId() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getEndpointId();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
PacketProtocol Input::getProtocol() const
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
if (impl != nullptr)
|
||||
return impl->getProtocol();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void Input::addConsumer (Consumer& x)
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->addConsumer (x);
|
||||
}
|
||||
|
||||
void Input::removeConsumer (Consumer& x)
|
||||
{
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->removeConsumer (x);
|
||||
}
|
||||
|
||||
void Input::addDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->addDisconnectionListener (x);
|
||||
}
|
||||
|
||||
void Input::removeDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->removeDisconnectionListener (x);
|
||||
}
|
||||
|
||||
bool Input::isAlive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isAlive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An interface class for entities that consume Universal MIDI Packets from some producer.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct Consumer
|
||||
{
|
||||
Consumer() = default;
|
||||
|
||||
Consumer (const Consumer&) = default;
|
||||
Consumer (Consumer&&) noexcept = default;
|
||||
|
||||
Consumer& operator= (const Consumer&) = default;
|
||||
Consumer& operator= (Consumer&&) noexcept = default;
|
||||
|
||||
virtual ~Consumer() noexcept = default;
|
||||
|
||||
/** This will be called each time a new packet is ready for processing. */
|
||||
virtual void consume (Iterator b, Iterator e, double time) = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An input (from the JUCE project's perspective) that receives messages sent by an endpoint.
|
||||
|
||||
An Input is conceptually similar to a unique_ptr, in that it's a nullable move-only type.
|
||||
You can check the null state of an instance by calling isAlive().
|
||||
isAlive() will return true for an Input that's currently connected, or false otherwise.
|
||||
In particular, isAlive() will return false for a default-constructed Input.
|
||||
If isAlive() returns false, you should avoid calling other member functions:
|
||||
although this won't result in undefined behaviour, none of the functions will produce useful
|
||||
results in this state.
|
||||
|
||||
In the case that the device connected to the Input becomes unavailable (e.g. it is unplugged or
|
||||
the bluetooth connection is dropped), the Input will null itself, and calls to isAlive() will
|
||||
return false. You can register a callback to handle this event by calling
|
||||
addDisconnectionListener().
|
||||
|
||||
A particular pitfall to watch out for is calling addConsumer(), removeConsumer(),
|
||||
addDisconnectionListener(), and removeDisconnectionListener() on a default-constructed Input
|
||||
or other Input for which isAlive() returns false. This will have no effect. Instead, if you want
|
||||
to attach listeners to an Input, you should use Session::connectInput() to create an Input,
|
||||
and ensure that isAlive() returns true on that Input before attaching listeners.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Input
|
||||
{
|
||||
public:
|
||||
/** Creates a disconnected input.
|
||||
A default-constructed input will never receive any messages.
|
||||
|
||||
Instances should only be created on the main thread.
|
||||
*/
|
||||
Input();
|
||||
|
||||
/** Destructor.
|
||||
|
||||
Instances should only be destroyed on the main thread in order to avoid potential races
|
||||
with disconnection callbacks, which also happen on the main thread.
|
||||
*/
|
||||
~Input();
|
||||
|
||||
Input (Input&&) noexcept;
|
||||
Input& operator= (Input&&) noexcept;
|
||||
|
||||
Input (const Input&) = delete;
|
||||
Input& operator= (const Input&) = delete;
|
||||
|
||||
/** Returns this connection's endpoint. */
|
||||
EndpointId getEndpointId() const;
|
||||
|
||||
/** Returns the protocol that was requested when creating this connection. */
|
||||
PacketProtocol getProtocol() const;
|
||||
|
||||
/** Attaches a receiver that will receive MIDI messages from this input.
|
||||
|
||||
Incoming messages will be converted to the protocol that was requested when
|
||||
opening the Input.
|
||||
|
||||
If isAlive() returns false at the point where this function is called, this function
|
||||
will have no effect. This can commonly happen when attempting to add listeners to a
|
||||
default-constructed Input, or if the input device got disconnected.
|
||||
|
||||
It is an error to add or remove a consumer from within the consumer callback.
|
||||
This will cause deadlocks, so be careful!
|
||||
|
||||
You should only add and remove consumers from the main thread.
|
||||
|
||||
Calls to Consumer::consume() will happen on a separate thread, often with high
|
||||
or even realtime priority.
|
||||
*/
|
||||
void addConsumer (Consumer& r);
|
||||
|
||||
/** Detaches the receiver so that it will no longer receive MIDI messages from this
|
||||
Input.
|
||||
|
||||
It is an error to add or remove a consumer from within the consumer callback.
|
||||
This will cause deadlocks, so be careful!
|
||||
|
||||
@see addConsumer()
|
||||
*/
|
||||
void removeConsumer (Consumer& r);
|
||||
|
||||
/** Attaches a listener that will be notified when this endpoint is disconnected.
|
||||
|
||||
Disconnection notifications will be sent on the main thread, and listeners should
|
||||
only be added or removed on the main thread in order to avoid potential data races.
|
||||
|
||||
Calling this function on an instance for which isAlive() returns false has no effect.
|
||||
*/
|
||||
void addDisconnectionListener (DisconnectionListener& r);
|
||||
|
||||
/** Removes a disconnection listener.
|
||||
|
||||
@see addDisconnectionListener()
|
||||
*/
|
||||
void removeDisconnectionListener (DisconnectionListener& r);
|
||||
|
||||
/** True if this connection is currently active.
|
||||
|
||||
This function returns false for a default-constructed instance.
|
||||
*/
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit Input (std::unique_ptr<Impl>);
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class LegacyVirtualInput::Impl final
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
virtual EndpointId getId() const = 0;
|
||||
};
|
||||
|
||||
EndpointId getId() const
|
||||
{
|
||||
return identifier;
|
||||
}
|
||||
|
||||
bool isAlive() const
|
||||
{
|
||||
return native != nullptr;
|
||||
}
|
||||
|
||||
static LegacyVirtualInput makeLegacyVirtualInput (std::unique_ptr<Native> x)
|
||||
{
|
||||
if (x != nullptr)
|
||||
return LegacyVirtualInput { rawToUniquePtr (new Impl (std::move (x))) };
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
explicit Impl (std::unique_ptr<Native> n)
|
||||
: native (std::move (n)),
|
||||
identifier (native->getId())
|
||||
{
|
||||
}
|
||||
|
||||
std::unique_ptr<Native> native;
|
||||
EndpointId identifier;
|
||||
};
|
||||
|
||||
LegacyVirtualInput::LegacyVirtualInput() = default;
|
||||
LegacyVirtualInput::~LegacyVirtualInput() = default;
|
||||
LegacyVirtualInput::LegacyVirtualInput (std::unique_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
LegacyVirtualInput::LegacyVirtualInput (LegacyVirtualInput&&) noexcept = default;
|
||||
LegacyVirtualInput& LegacyVirtualInput::operator= (LegacyVirtualInput&&) noexcept = default;
|
||||
|
||||
EndpointId LegacyVirtualInput::getId() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getId();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool LegacyVirtualInput::isAlive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isAlive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Represents a virtual MIDI 1.0 input port.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class LegacyVirtualInput
|
||||
{
|
||||
public:
|
||||
/** Creates an invalid virtual port that doesn't correspond to any virtual device. */
|
||||
LegacyVirtualInput();
|
||||
~LegacyVirtualInput();
|
||||
|
||||
LegacyVirtualInput (LegacyVirtualInput&&) noexcept;
|
||||
LegacyVirtualInput& operator= (LegacyVirtualInput&&) noexcept;
|
||||
|
||||
LegacyVirtualInput (const LegacyVirtualInput&) = delete;
|
||||
LegacyVirtualInput& operator= (const LegacyVirtualInput&) = delete;
|
||||
|
||||
/** Retrieves the unique id of this input.
|
||||
|
||||
You can pass this ID to Session::connectInput() in order to receive messages sent to this
|
||||
input.
|
||||
|
||||
Note that this ID is *not* guaranteed to be stable - creating the 'same' virtual device
|
||||
across several program invocations may produce a different ID each time.
|
||||
|
||||
To fetch the current details of this device, you can pass this ID to Endpoints::getEndpoint().
|
||||
*/
|
||||
EndpointId getId() const;
|
||||
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit LegacyVirtualInput (std::unique_ptr<Impl>);
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class LegacyVirtualOutput::Impl final
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
virtual EndpointId getId() const = 0;
|
||||
};
|
||||
|
||||
EndpointId getId() const
|
||||
{
|
||||
return identifier;
|
||||
}
|
||||
|
||||
bool isAlive() const
|
||||
{
|
||||
return native != nullptr;
|
||||
}
|
||||
|
||||
static LegacyVirtualOutput makeLegacyVirtualOutput (std::unique_ptr<Native> x)
|
||||
{
|
||||
if (x != nullptr)
|
||||
return LegacyVirtualOutput { rawToUniquePtr (new Impl (std::move (x))) };
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
explicit Impl (std::unique_ptr<Native> n)
|
||||
: native (std::move (n)),
|
||||
identifier (native->getId())
|
||||
{
|
||||
}
|
||||
|
||||
std::unique_ptr<Native> native;
|
||||
EndpointId identifier;
|
||||
};
|
||||
|
||||
LegacyVirtualOutput::LegacyVirtualOutput() = default;
|
||||
LegacyVirtualOutput::~LegacyVirtualOutput() = default;
|
||||
LegacyVirtualOutput::LegacyVirtualOutput (std::unique_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
LegacyVirtualOutput::LegacyVirtualOutput (LegacyVirtualOutput&&) noexcept = default;
|
||||
LegacyVirtualOutput& LegacyVirtualOutput::operator= (LegacyVirtualOutput&&) noexcept = default;
|
||||
|
||||
EndpointId LegacyVirtualOutput::getId() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getId();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool LegacyVirtualOutput::isAlive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isAlive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Represents a virtual MIDI 1.0 output port.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class LegacyVirtualOutput
|
||||
{
|
||||
public:
|
||||
/** Creates an invalid virtual port that doesn't correspond to any virtual device. */
|
||||
LegacyVirtualOutput();
|
||||
~LegacyVirtualOutput();
|
||||
|
||||
LegacyVirtualOutput (LegacyVirtualOutput&&) noexcept;
|
||||
LegacyVirtualOutput& operator= (LegacyVirtualOutput&&) noexcept;
|
||||
|
||||
LegacyVirtualOutput (const LegacyVirtualOutput&) = delete;
|
||||
LegacyVirtualOutput& operator= (const LegacyVirtualOutput&) = delete;
|
||||
|
||||
/** Retrieves the unique id of this input.
|
||||
|
||||
You can pass this ID to Session::connectOutput() in order to send messages to this output.
|
||||
|
||||
Note that this ID is *not* guaranteed to be stable - creating the 'same' virtual device
|
||||
across several program invocations may produce a different ID each time.
|
||||
|
||||
To fetch the current details of this device, you can pass this ID to Endpoints::getEndpoint().
|
||||
*/
|
||||
EndpointId getId() const;
|
||||
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit LegacyVirtualOutput (std::unique_ptr<Impl>);
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class Output::Impl final : private DisconnectionListener
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
virtual EndpointId getEndpointId() const = 0;
|
||||
|
||||
virtual bool send (Iterator b, Iterator e) = 0;
|
||||
};
|
||||
|
||||
~Impl() override
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
}
|
||||
|
||||
EndpointId getEndpointId() const
|
||||
{
|
||||
return identifier;
|
||||
}
|
||||
|
||||
bool send (Iterator beginIterator, Iterator endIterator)
|
||||
{
|
||||
return isAlive() && native->send (beginIterator, endIterator);
|
||||
}
|
||||
|
||||
void addDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
disconnectListeners.add (&x);
|
||||
}
|
||||
|
||||
void removeDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
disconnectListeners.remove (&x);
|
||||
}
|
||||
|
||||
bool isAlive() const
|
||||
{
|
||||
return connected && native != nullptr;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
static Output makeOutput (Callback&& callback)
|
||||
{
|
||||
auto impl = rawToUniquePtr (new Impl);
|
||||
impl->native = callback (static_cast<DisconnectionListener&> (*impl));
|
||||
|
||||
if (impl->native == nullptr)
|
||||
return {};
|
||||
|
||||
impl->identifier = impl->native->getEndpointId();
|
||||
return Output { std::move (impl) };
|
||||
}
|
||||
|
||||
private:
|
||||
Impl()
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
}
|
||||
|
||||
void disconnected() override
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
connected = false;
|
||||
disconnectListeners.call ([] (auto& x) { x.disconnected(); });
|
||||
}
|
||||
|
||||
ListenerList<DisconnectionListener> disconnectListeners;
|
||||
std::unique_ptr<Native> native;
|
||||
EndpointId identifier;
|
||||
std::atomic<bool> connected { true };
|
||||
};
|
||||
|
||||
Output::Output() = default;
|
||||
Output::~Output() = default;
|
||||
Output::Output (std::unique_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
Output::Output (Output&&) noexcept = default;
|
||||
Output& Output::operator= (Output&&) noexcept = default;
|
||||
|
||||
EndpointId Output::getEndpointId() const
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
if (impl != nullptr)
|
||||
return impl->getEndpointId();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool Output::send (Iterator beginIterator, Iterator endIterator)
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
if (impl != nullptr)
|
||||
return impl->send (beginIterator, endIterator);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Output::addDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
// You should ensure that isAlive() returns true before calling other member functions!
|
||||
jassert (isAlive());
|
||||
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->addDisconnectionListener (x);
|
||||
}
|
||||
|
||||
void Output::removeDisconnectionListener (DisconnectionListener& x)
|
||||
{
|
||||
// This function should only be called on the main thread!
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
if (impl != nullptr)
|
||||
impl->removeDisconnectionListener (x);
|
||||
}
|
||||
|
||||
bool Output::isAlive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isAlive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
An output (from the JUCE project's perspective) that sends messages to an endpoint.
|
||||
|
||||
An Output is conceptually similar to a unique_ptr, in that it's a nullable move-only type.
|
||||
You can check the null state of an instance by calling isAlive().
|
||||
isAlive() will return true for an Output that's currently connected, or false otherwise.
|
||||
In particular, isAlive() will return false for a default-constructed Output.
|
||||
If isAlive() returns false, you should avoid calling other member functions:
|
||||
although this won't result in undefined behaviour, none of the functions will produce useful
|
||||
results in this state.
|
||||
|
||||
In the case that the device connected to the Output becomes unavailable (e.g. it is unplugged or
|
||||
the bluetooth connection is dropped), the Output will null itself, and calls to isAlive() will
|
||||
return false. You can register a callback to handle this event by calling
|
||||
addDisconnectionListener().
|
||||
|
||||
A particular pitfall to watch out for is calling addDisconnectionListener() and
|
||||
removeDisconnectionListener() on a default-constructed Output or other Output for which
|
||||
isAlive() returns false. This will have no effect. Instead, if you want
|
||||
to attach listeners to an Output, you should use Session::connectOutput() to create an Output,
|
||||
and ensure that isAlive() returns true on that Output before attaching listeners.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Output
|
||||
{
|
||||
public:
|
||||
/** Creates a disconnected output.
|
||||
Sending messages to a default-constructed output won't do anything.
|
||||
|
||||
Instances should only be created on the main thread.
|
||||
*/
|
||||
Output();
|
||||
|
||||
/** Destructor.
|
||||
|
||||
Instances should only be destroyed on the main thread in order to avoid potential races
|
||||
with disconnection callbacks, which also happen on the main thread.
|
||||
*/
|
||||
~Output();
|
||||
|
||||
Output (Output&&) noexcept;
|
||||
Output& operator= (Output&&) noexcept;
|
||||
|
||||
Output (const Output&) = delete;
|
||||
Output& operator= (const Output&) = delete;
|
||||
|
||||
/** Returns this connection's endpoint. */
|
||||
EndpointId getEndpointId() const;
|
||||
|
||||
/** Sends a range of messages to this endpoint.
|
||||
If isAlive() returns false at the point where this function is called, then this
|
||||
function has no effect.
|
||||
|
||||
Returns true on success, false on failure.
|
||||
|
||||
You may send messages using any protocol, and they will be converted automatically
|
||||
to the protocol expected by the receiver.
|
||||
|
||||
This function may be called from a background thread (i.e. not the main thread).
|
||||
*/
|
||||
bool send (Iterator beginIterator, Iterator endIterator);
|
||||
|
||||
/** Attaches a listener that will be notified when this endpoint is disconnected.
|
||||
|
||||
Disconnection notifications will be sent on the main thread, and listeners should
|
||||
only be added or removed on the main thread in order to avoid potential data races.
|
||||
|
||||
Calling this function on an instance for which isAlive() returns false has no effect.
|
||||
*/
|
||||
void addDisconnectionListener (DisconnectionListener& r);
|
||||
|
||||
/** Removes a disconnection listener.
|
||||
|
||||
@see addDisconnectionListener()
|
||||
*/
|
||||
void removeDisconnectionListener (DisconnectionListener& r);
|
||||
|
||||
/** True if this connection is currently active.
|
||||
|
||||
This function returns false for a default-constructed instance.
|
||||
*/
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit Output (std::unique_ptr<Impl>);
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class Session::Impl
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
virtual String getName() const = 0;
|
||||
virtual std::unique_ptr<Input::Impl::Native> connectInput (DisconnectionListener&,
|
||||
const EndpointId&,
|
||||
PacketProtocol,
|
||||
Consumer&) = 0;
|
||||
virtual std::unique_ptr<Output::Impl::Native> connectOutput (DisconnectionListener&,
|
||||
const EndpointId&) = 0;
|
||||
|
||||
/* Creates a full MIDI 2.0 UMP endpoint, or returns nullptr on failure. */
|
||||
virtual std::unique_ptr<VirtualEndpoint::Impl::Native> createNativeVirtualEndpoint (const String&,
|
||||
const DeviceInfo&,
|
||||
const String&,
|
||||
PacketProtocol,
|
||||
Span<const Block>,
|
||||
BlocksAreStatic)
|
||||
{
|
||||
// If this is hit, you're trying to create a virtual (app-to-app) MIDI 2.0 endpoint, but
|
||||
// the current MIDI backend does not implement this feature.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Creates a virtual MIDI 1.0 port. This is intended for use on platforms that don't
|
||||
support virtual MIDI 2.0.
|
||||
*/
|
||||
virtual std::unique_ptr<LegacyVirtualInput::Impl::Native> createLegacyVirtualInput (const String&)
|
||||
{
|
||||
// If this is hit, you're trying to create a virtual (app-to-app) MIDI 1.0 endpoint, but
|
||||
// the current MIDI backend does not implement this feature.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Creates a virtual MIDI 1.0 port. This is intended for use on platforms that don't
|
||||
support virtual MIDI 2.0.
|
||||
*/
|
||||
virtual std::unique_ptr<LegacyVirtualOutput::Impl::Native> createLegacyVirtualOutput (const String&)
|
||||
{
|
||||
// If this is hit, you're trying to create a virtual (app-to-app) MIDI 1.0 endpoint, but
|
||||
// the current MIDI backend does not implement this feature.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
String getName() const
|
||||
{
|
||||
return native->getName();
|
||||
}
|
||||
|
||||
Input makeInput (const EndpointId& endpointId, PacketProtocol protocol)
|
||||
{
|
||||
return Input::Impl::makeInput ([&] (DisconnectionListener& d, Consumer& c)
|
||||
{
|
||||
return native->connectInput (d, endpointId, protocol, c);
|
||||
});
|
||||
}
|
||||
|
||||
Output makeOutput (const EndpointId& endpointId)
|
||||
{
|
||||
return Output::Impl::makeOutput ([&] (DisconnectionListener& d)
|
||||
{
|
||||
return native->connectOutput (d, endpointId);
|
||||
});
|
||||
}
|
||||
|
||||
VirtualEndpoint createVirtualEndpoint (const String& name,
|
||||
const DeviceInfo& info,
|
||||
const String& productInstance,
|
||||
PacketProtocol protocol,
|
||||
Span<const Block> blocks,
|
||||
BlocksAreStatic areStatic)
|
||||
{
|
||||
if (blocks.size() > 32)
|
||||
{
|
||||
// UMP endpoints support a maximum of 32 function blocks
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
if (name.getNumBytesAsUTF8() > 98)
|
||||
{
|
||||
// Per the spec, there's a length restriction on endpoint names
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
const auto isBlockNameTooLong = [] (const Block& b)
|
||||
{
|
||||
return b.getName().getNumBytesAsUTF8() > 91;
|
||||
};
|
||||
|
||||
if (std::any_of (blocks.begin(), blocks.end(), isBlockNameTooLong))
|
||||
{
|
||||
// Per the spec, there's a length restriction on block names
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
const auto isBlockDisabled = [] (const Block& b) { return ! b.isEnabled(); };
|
||||
|
||||
if (areStatic == BlocksAreStatic::yes && std::any_of (blocks.begin(), blocks.end(), isBlockDisabled))
|
||||
{
|
||||
// You may not request a disabled function block if the function block topology is static
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto umpEndpointNative = native->createNativeVirtualEndpoint (name,
|
||||
info,
|
||||
productInstance,
|
||||
protocol,
|
||||
blocks,
|
||||
areStatic);
|
||||
|
||||
if (umpEndpointNative == nullptr)
|
||||
return {};
|
||||
|
||||
auto result = VirtualEndpoint::Impl::makeVirtualEndpoint (std::move (umpEndpointNative));
|
||||
|
||||
if (! result)
|
||||
return {};
|
||||
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
if (const auto endpoint = Endpoints::getInstance()->getEndpoint (result.getId()))
|
||||
{
|
||||
jassert (endpoint->getName() == name);
|
||||
jassert (endpoint->getProductInstanceId() == productInstance);
|
||||
jassert (endpoint->getProtocol() == protocol);
|
||||
jassert (endpoint->hasStaticBlocks() == (areStatic == BlocksAreStatic::yes));
|
||||
jassert (std::equal (blocks.begin(),
|
||||
blocks.end(),
|
||||
endpoint->getBlocks().begin(),
|
||||
endpoint->getBlocks().end()));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Unable to find this endpoint, even though we just created it!
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
if (const auto staticInfo = Endpoints::getInstance()->getStaticDeviceInfo (result.getId()))
|
||||
{
|
||||
jassert (staticInfo->getTransport() == Transport::ump);
|
||||
}
|
||||
else
|
||||
{
|
||||
jassertfalse;
|
||||
}
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
LegacyVirtualInput createLegacyVirtualInput (const String& name)
|
||||
{
|
||||
if (auto result = native->createLegacyVirtualInput (name))
|
||||
{
|
||||
[[maybe_unused]] const auto id = result->getId();
|
||||
jassert (id.dst.isNotEmpty());
|
||||
return LegacyVirtualInput::Impl::makeLegacyVirtualInput (std::move (result));
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
LegacyVirtualOutput createLegacyVirtualOutput (const String& name)
|
||||
{
|
||||
if (auto result = native->createLegacyVirtualOutput (name))
|
||||
{
|
||||
[[maybe_unused]] const auto id = result->getId();
|
||||
jassert (id.src.isNotEmpty());
|
||||
return LegacyVirtualOutput::Impl::makeLegacyVirtualOutput (std::move (result));
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
static Session makeSession (std::unique_ptr<Native> x)
|
||||
{
|
||||
if (x == nullptr)
|
||||
return Session { nullptr };
|
||||
|
||||
return Session { rawToUniquePtr (new Impl (std::move (x))) };
|
||||
}
|
||||
|
||||
private:
|
||||
explicit Impl (std::unique_ptr<Native> n) : native (std::move (n)) {}
|
||||
|
||||
// Order of data members is important to ensure that all inputs+outputs are destroyed before the
|
||||
// native session
|
||||
std::unique_ptr<Native> native;
|
||||
};
|
||||
|
||||
String Session::getName() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getName();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Input Session::connectInput (const EndpointId& x, PacketProtocol p)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->makeInput (x, p);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Output Session::connectOutput (const EndpointId& x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->makeOutput (x);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
VirtualEndpoint Session::createVirtualEndpoint (const String& name,
|
||||
const DeviceInfo& deviceInfo,
|
||||
const String& productInstanceID,
|
||||
PacketProtocol protocol,
|
||||
Span<const Block> initialBlocks,
|
||||
BlocksAreStatic areStatic)
|
||||
{
|
||||
if (impl == nullptr)
|
||||
return {};
|
||||
|
||||
return impl->createVirtualEndpoint (name,
|
||||
deviceInfo,
|
||||
productInstanceID,
|
||||
protocol,
|
||||
initialBlocks,
|
||||
areStatic);
|
||||
}
|
||||
|
||||
LegacyVirtualInput Session::createLegacyVirtualInput (const juce::String& name)
|
||||
{
|
||||
if (impl == nullptr)
|
||||
return {};
|
||||
|
||||
return impl->createLegacyVirtualInput (name);
|
||||
}
|
||||
|
||||
LegacyVirtualOutput Session::createLegacyVirtualOutput (const juce::String& name)
|
||||
{
|
||||
if (impl == nullptr)
|
||||
return {};
|
||||
|
||||
return impl->createLegacyVirtualOutput (name);
|
||||
}
|
||||
|
||||
bool Session::isAlive() const
|
||||
{
|
||||
return impl != nullptr;
|
||||
}
|
||||
|
||||
Session::Session (std::shared_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
Session::Session (const Session&) = default;
|
||||
Session::Session (Session&&) noexcept = default;
|
||||
Session& Session::operator= (const Session&) = default;
|
||||
Session& Session::operator= (Session&&) noexcept = default;
|
||||
Session::~Session() = default;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/** This type is passed when creating a virtual endpoint to request static or dynamic blocks. */
|
||||
enum class BlocksAreStatic : uint8_t
|
||||
{
|
||||
no, ///< Indicates that block layouts will not change after construction.
|
||||
yes, ///< Indicates that the block layout may be modified after construction.
|
||||
};
|
||||
|
||||
/**
|
||||
Allows creating new connections to endpoints, and also creating new virtual endpoints.
|
||||
|
||||
The session is internally reference counted, meaning that the system resources represented
|
||||
by the session won't be released until the Session object, along with every Input, Output,
|
||||
VirtualEndpoint, LegacyVirtualInput, and LegacyVirtualOutput that it created has been
|
||||
destroyed.
|
||||
|
||||
Internally, sessions cache open connections, so that multiple Inputs
|
||||
or Outputs to the same endpoint will share resources associated with that connection.
|
||||
Therefore, in order to minimise resource usage, you should create as few sessions as possible,
|
||||
and re-use them when creating new connections. It may still make sense to have a separate
|
||||
session for logically discrete components of your project, e.g. a multi-window application
|
||||
where each window has its own document with an associated MIDI configuration.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Session
|
||||
{
|
||||
public:
|
||||
/** Returns the name that was provided when creating this session, or an empty string
|
||||
if the session is not alive.
|
||||
*/
|
||||
String getName() const;
|
||||
|
||||
/** Creates a connection to a particular endpoint.
|
||||
On failure, returns a disconnected connection (i.e. isAlive() returns false).
|
||||
Passing an EndpointId denoting an endpoint that can only receive messages will fail.
|
||||
|
||||
Incoming messages will be automatically converted to the specified protocol, regardless
|
||||
of their actual protocol 'on the wire'.
|
||||
|
||||
If the session is not alive, this will always fail and return an Input that is not alive.
|
||||
*/
|
||||
Input connectInput (const EndpointId&, PacketProtocol);
|
||||
|
||||
/** Creates a connection to a particular endpoint.
|
||||
On failure, returns a disconnected connection (i.e. isAlive() returns false).
|
||||
Passing an EndpointId denoting an endpoint that can only send messages will fail.
|
||||
|
||||
If the session is not alive, this will always fail and return an Output that is not alive.
|
||||
*/
|
||||
Output connectOutput (const EndpointId&);
|
||||
|
||||
/** Returns a new VirtualEndpoint if virtual endpoints are supported and the configuration is
|
||||
valid. If creating the endpoint fails, this will return an invalid VirtualEndpoint.
|
||||
|
||||
To actually send and receive messages through this endpoint, use connectInput()
|
||||
and connectOutput(), passing the result of VirtualEndpoint::getId(). This will create
|
||||
an Input or Output that can be used in the same way as for any other kind of device.
|
||||
|
||||
If the function blocks are static, all blocks must be marked as active.
|
||||
If the function blocks are not static, then blocks may be initially inactive.
|
||||
The number of declared function blocks may not change while the device is active,
|
||||
so if you need a dynamic number of blocks, mark the block layout as non-static
|
||||
and mark any initially unused blocks as inactive.
|
||||
|
||||
Only a maximum of 32 blocks are allowed on an endpoint. If you pass more than 32
|
||||
blocks, this function will fail.
|
||||
|
||||
This function may also fail if virtual devices are not available on the current platform.
|
||||
|
||||
Some platforms (older macOS, older Linux) support virtual MIDI 1.0 devices but not
|
||||
virtual UMP devices. On such platforms, this function will fail. You may wish to check
|
||||
for this case, and to call createLegacyVirtualInput() and/or createLegacyVirtualOutput()
|
||||
as a fall-back.
|
||||
|
||||
If the session is not alive, this will always fail and return a VirtualEndpoint that is not
|
||||
alive.
|
||||
|
||||
On Android, this function will only ever succeed on newer platforms (API level >= 35).
|
||||
You may need to call Endpoints::setVirtualMidiUmpServiceActive() to make the virtual UMP
|
||||
service available. You can listen for state changes in the virtual MIDI service using
|
||||
EndpointsListener::virtualMidiServiceActiveChanged(). A maximum of one VirtualEndpoint may
|
||||
be alive at any time on Android, and attempting to create additional virtual endpoints will
|
||||
fail.
|
||||
*/
|
||||
VirtualEndpoint createVirtualEndpoint (const String& name,
|
||||
const DeviceInfo& deviceInfo,
|
||||
const String& productInstanceID,
|
||||
PacketProtocol protocol,
|
||||
Span<const Block> initialBlocks,
|
||||
BlocksAreStatic);
|
||||
|
||||
/** Creates a MIDI 1.0-compatible input port.
|
||||
|
||||
Where supported by platform APIs, this will explicitly create a single-group MIDI 1.0 port.
|
||||
|
||||
To use the input, pass the result of LegacyVirtualInput::getId() to connectInput().
|
||||
|
||||
There are some special cases to keep in mind:
|
||||
|
||||
- Windows MIDI Services only allows creation of UMP endpoints, not MIDI 1.0 ports, so on
|
||||
that platform we create an endpoint with a single MIDI 1.0 Block.
|
||||
- Android requires that virtual ports are declared in the app manifest. JUCE declares a
|
||||
virtual bytestream device with a single input and output, and a virtual UMP device with
|
||||
a single bidirectional port. By default, these virtual devices are disabled, but they
|
||||
can be enabled by calling Endpoints::setVirtualMidiBytestreamServiceActive() and
|
||||
Endpoints::setVirtualMidiUmpServiceActive(). After each service becomes available, you
|
||||
may create exactly one VirtualEndpoint, one LegacyVirtualInput, and/or one
|
||||
LegacyVirtualOutput. Additional virtual ports are not supported.
|
||||
*/
|
||||
LegacyVirtualInput createLegacyVirtualInput (const String& name);
|
||||
|
||||
/** Creates a MIDI 1.0-compatible output port.
|
||||
|
||||
Where supported by platform APIs, this will explicitly create a single-group MIDI 1.0 port.
|
||||
|
||||
To use the output, pass the result of LegacyVirtualOutput::getId() to connectOutput().
|
||||
|
||||
There are some special cases to keep in mind:
|
||||
|
||||
- Windows MIDI Services only allows creation of UMP endpoints, not MIDI 1.0 ports, so on
|
||||
that platform we create an endpoint with a single MIDI 1.0 Block.
|
||||
- Android requires that virtual ports are declared in the app manifest. JUCE declares a
|
||||
virtual bytestream device with a single input and output, and a virtual UMP device with
|
||||
a single bidirectional port. By default, these virtual devices are disabled, but they
|
||||
can be enabled by calling Endpoints::setVirtualMidiBytestreamServiceActive() and
|
||||
Endpoints::setVirtualMidiUmpServiceActive(). After each service becomes available, you
|
||||
may create exactly one VirtualEndpoint, one LegacyVirtualInput, and/or one
|
||||
LegacyVirtualOutput. Additional virtual ports are not supported.
|
||||
*/
|
||||
LegacyVirtualOutput createLegacyVirtualOutput (const String& name);
|
||||
|
||||
/** True if this session was created successfully and is currently alive. */
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
Session (const Session&);
|
||||
Session (Session&&) noexcept;
|
||||
Session& operator= (const Session&);
|
||||
Session& operator= (Session&&) noexcept;
|
||||
~Session();
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit Session (std::shared_ptr<Impl>);
|
||||
|
||||
std::shared_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
auto StaticDeviceInfo::tie() const
|
||||
{
|
||||
return std::tie (identifierSrc, identifierDst, name, manufacturer, product, transport, source, destination);
|
||||
}
|
||||
|
||||
bool StaticDeviceInfo::operator== (const StaticDeviceInfo& other) const
|
||||
{
|
||||
return tie() == other.tie();
|
||||
}
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Static information about a particular MIDI device that can be queried without opening a
|
||||
connection to the device.
|
||||
|
||||
This information differs from the detailed information in the Endpoint struct, in that
|
||||
the StaticDeviceInformation is communicated out-of-band, whereas Endpoint information is
|
||||
communicated in-band, i.e. it is sent as MIDI messages after establishing a connection to the
|
||||
device.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class StaticDeviceInfo
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] StaticDeviceInfo withName (const String& x) const { return withMember (*this, &StaticDeviceInfo::name, x); }
|
||||
[[nodiscard]] StaticDeviceInfo withManufacturer (const String& x) const { return withMember (*this, &StaticDeviceInfo::manufacturer, x); }
|
||||
[[nodiscard]] StaticDeviceInfo withProduct (const String& x) const { return withMember (*this, &StaticDeviceInfo::product, x); }
|
||||
[[nodiscard]] StaticDeviceInfo withHasSource (bool x) const { return withMember (*this, &StaticDeviceInfo::source, x); }
|
||||
[[nodiscard]] StaticDeviceInfo withHasDestination (bool x) const { return withMember (*this, &StaticDeviceInfo::destination, x); }
|
||||
[[nodiscard]] StaticDeviceInfo withTransport (Transport x) const { return withMember (*this, &StaticDeviceInfo::transport, x); }
|
||||
|
||||
[[nodiscard]] StaticDeviceInfo withLegacyIdentifiersSrc (Span<const String, 16> x) const
|
||||
{
|
||||
auto copy = *this;
|
||||
std::copy (x.begin(), x.end(), copy.identifierSrc.begin());
|
||||
return copy;
|
||||
}
|
||||
|
||||
[[nodiscard]] StaticDeviceInfo withLegacyIdentifiersDst (Span<const String, 16> x) const
|
||||
{
|
||||
auto copy = *this;
|
||||
std::copy (x.begin(), x.end(), copy.identifierDst.begin());
|
||||
return copy;
|
||||
}
|
||||
|
||||
[[nodiscard]] StaticDeviceInfo withLegacyIdentifiers (IOKind k, Span<const String, 16> x) const
|
||||
{
|
||||
return k == IOKind::src ? withLegacyIdentifiersSrc (x) : withLegacyIdentifiersDst (x);
|
||||
}
|
||||
|
||||
String getName() const { return name; }
|
||||
String getManufacturer() const { return manufacturer; }
|
||||
String getProduct() const { return product; }
|
||||
bool hasSource() const { return source; }
|
||||
bool hasDestination() const { return destination; }
|
||||
Transport getTransport() const { return transport; }
|
||||
|
||||
/** Returns an identifier to uniquely identify each group, for use with the legacy MIDI API. */
|
||||
Span<const String, 16> getLegacyIdentifiersSrc() const& { return identifierSrc; }
|
||||
/** Returns an identifier to uniquely identify each group, for use with the legacy MIDI API. */
|
||||
Span<const String, 16> getLegacyIdentifiersDst() const& { return identifierDst; }
|
||||
|
||||
Span<const String, 16> getLegacyIdentifiers (IOKind k) const&
|
||||
{
|
||||
return k == IOKind::src ? getLegacyIdentifiersSrc() : getLegacyIdentifiersDst();
|
||||
}
|
||||
|
||||
Span<const String, 16> getLegacyIdentifiersSrc() const&& = delete;
|
||||
Span<const String, 16> getLegacyIdentifiersDst() const&& = delete;
|
||||
Span<const String, 16> getLegacyIdentifiers (IOKind) const&& = delete;
|
||||
|
||||
bool operator== (const StaticDeviceInfo&) const;
|
||||
bool operator!= (const StaticDeviceInfo& other) const { return ! operator== (other); }
|
||||
|
||||
private:
|
||||
auto tie() const;
|
||||
|
||||
std::array<String, 16> identifierSrc, identifierDst;
|
||||
String name; ///< The full human-readable name of this device
|
||||
String manufacturer; ///< The name of the organisation that produced this device
|
||||
String product; ///< The human-readable product name
|
||||
Transport transport{}; ///< The format used for MIDI messages in transit
|
||||
uint8_t source = false; ///< True if the device can send messages
|
||||
uint8_t destination = false; ///< True if the device can receive messages
|
||||
};
|
||||
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
class VirtualEndpoint::Impl final
|
||||
{
|
||||
public:
|
||||
class Native
|
||||
{
|
||||
public:
|
||||
virtual ~Native() = default;
|
||||
|
||||
virtual EndpointId getId() const = 0;
|
||||
virtual bool setBlock (uint8_t, const Block&) = 0;
|
||||
virtual bool setName (const String&) = 0;
|
||||
};
|
||||
|
||||
EndpointId getId() const
|
||||
{
|
||||
return identifier;
|
||||
}
|
||||
|
||||
bool setBlock (uint8_t i, const Block& b)
|
||||
{
|
||||
if (native != nullptr)
|
||||
return native->setBlock (i, b);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool setName (const String& n)
|
||||
{
|
||||
if (native != nullptr)
|
||||
return native->setName (n);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isAlive() const
|
||||
{
|
||||
return native != nullptr;
|
||||
}
|
||||
|
||||
static VirtualEndpoint makeVirtualEndpoint (std::unique_ptr<Native> x)
|
||||
{
|
||||
if (x != nullptr)
|
||||
return VirtualEndpoint { rawToUniquePtr (new Impl (std::move (x))) };
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
explicit Impl (std::unique_ptr<Native> n)
|
||||
: native (std::move (n)),
|
||||
identifier (native->getId())
|
||||
{
|
||||
}
|
||||
|
||||
std::unique_ptr<Native> native;
|
||||
EndpointId identifier;
|
||||
};
|
||||
|
||||
VirtualEndpoint::VirtualEndpoint() = default;
|
||||
VirtualEndpoint::~VirtualEndpoint() = default;
|
||||
VirtualEndpoint::VirtualEndpoint (std::unique_ptr<Impl> x) : impl (std::move (x)) {}
|
||||
VirtualEndpoint::VirtualEndpoint (VirtualEndpoint&&) noexcept = default;
|
||||
VirtualEndpoint& VirtualEndpoint::operator= (VirtualEndpoint&&) noexcept = default;
|
||||
|
||||
EndpointId VirtualEndpoint::getId() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->getId();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool VirtualEndpoint::setBlock (uint8_t i, const Block& b)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->setBlock (i, b);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool VirtualEndpoint::setName (const String& x)
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->setName (x);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool VirtualEndpoint::isAlive() const
|
||||
{
|
||||
if (impl != nullptr)
|
||||
return impl->isAlive();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Represents a virtual device that allows this program to advertise itself to other MIDI-aware
|
||||
applications on the system.
|
||||
|
||||
Creating a VirtualEndpoint will install a new endpoint on the system. This endpoint will
|
||||
be visible when enumerating endpoints using the Endpoints singleton. If you're displaying
|
||||
a list of endpoints in your UI, it's probably a good idea to omit any virtual endpoints
|
||||
created by the current application in order to avoid confusion.
|
||||
|
||||
After creating a VirtualEndpoint, it can be opened like any other connection, by calling
|
||||
Session::connectInput() and Session::connectOutput(), passing the EndpointId for the
|
||||
virtual endpoint.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class VirtualEndpoint
|
||||
{
|
||||
public:
|
||||
/** Creates an invalid virtual endpoint that doesn't correspond to any virtual device.
|
||||
|
||||
isAlive() will return false for a default-constructed VirtualEndpoint.
|
||||
*/
|
||||
VirtualEndpoint();
|
||||
~VirtualEndpoint();
|
||||
|
||||
VirtualEndpoint (VirtualEndpoint&&) noexcept;
|
||||
VirtualEndpoint& operator= (VirtualEndpoint&&) noexcept;
|
||||
|
||||
VirtualEndpoint (const VirtualEndpoint&) = delete;
|
||||
VirtualEndpoint& operator= (const VirtualEndpoint&) = delete;
|
||||
|
||||
/** Retrieves the unique id of this endpoint.
|
||||
|
||||
Pass this ID to Session::connectInput() and/or Session::connectOutput in order to send and
|
||||
receive messages through the virtual endpoint.
|
||||
|
||||
Note that this ID is *not* guaranteed to be stable - creating the 'same' virtual device
|
||||
across several program invocations may produce a different ID each time.
|
||||
|
||||
To fetch the current details of this device, you can pass this ID to Endpoints::getEndpoint().
|
||||
*/
|
||||
EndpointId getId() const;
|
||||
|
||||
/** Sets new properties for the block at the given zero-based index. The number of function
|
||||
blocks on an endpoint may not change.
|
||||
|
||||
Returns true on success, or false otherwise.
|
||||
|
||||
This may fail for several reasons, including:
|
||||
- attempting to modify an endpoint with static function blocks
|
||||
- attempting to update a block index that doesn't exist on this endpoint
|
||||
- attempting to set a block with invalid properties, e.g. the sum of the start index and
|
||||
number of included groups is greater than 16
|
||||
- platform-specific reasons, e.g. macOS doesn't currently allow changing the number of
|
||||
spanned groups in a block
|
||||
*/
|
||||
bool setBlock (uint8_t index, const Block& newBlock);
|
||||
|
||||
/** Assigns a new name to this endpoint, and sends a notification to connected endpoints. */
|
||||
bool setName (const String&);
|
||||
|
||||
/** Returns true if this object represents an endpoint that is currently alive, or false if
|
||||
the endpoint is not alive. This can happen because the endpoint failed to open, or
|
||||
if the session holding the endpoint was closed.
|
||||
|
||||
This function returns false for a default-constructed instance.
|
||||
*/
|
||||
bool isAlive() const;
|
||||
|
||||
explicit operator bool() const { return isAlive(); }
|
||||
|
||||
/** @internal */
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
explicit VirtualEndpoint (std::unique_ptr<Impl>);
|
||||
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//-----------------------------------------------------------------------------
|
||||
// LICENSE
|
||||
// (c) 2025, Steinberg Media Technologies GmbH, All Rights Reserved
|
||||
//-----------------------------------------------------------------------------
|
||||
This license applies only to files referencing this license,
|
||||
for other files of the Software Development Kit the respective embedded license text
|
||||
is applicable.
|
||||
|
||||
This Software Development Kit is licensed under the terms of the Steinberg ASIO License,
|
||||
or alternatively under the terms of the General Public License (GPL) Version 3.
|
||||
You may use the Software Development Kit according to either of these licenses as it is
|
||||
most appropriate for your project on a case-by-case basis (commercial or not).
|
||||
|
||||
a) Proprietary Steinberg ASIO License
|
||||
The Software Development Kit may not be distributed in parts or its entirety
|
||||
without prior written agreement by Steinberg Media Technologies GmbH.
|
||||
The SDK must not be used to re-engineer or manipulate any technology used
|
||||
in any Steinberg or Third-party application or software module,
|
||||
unless permitted by law.
|
||||
Neither the name of the Steinberg Media Technologies GmbH nor the names of its
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
Before publishing a software under the proprietary license, you need to obtain a copy
|
||||
of the License Agreement signed by Steinberg Media Technologies GmbH.
|
||||
The Steinberg ASIO SDK License Agreement can be found at:
|
||||
www.steinberg.net/en/company/developers.html
|
||||
|
||||
THE SDK IS PROVIDED BY STEINBERG MEDIA TECHNOLOGIES GMBH "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
IN NO EVENT SHALL STEINBERG MEDIA TECHNOLOGIES GMBH BE LIABLE FOR ANY DIRECT,
|
||||
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
|
||||
OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
b) General Public License (GPL) Version 3
|
||||
Details of these licenses can be found at: www.gnu.org/licenses/gpl-3.0.html
|
||||
|
||||
Best Practice recommendation:
|
||||
Please refer to the Steinberg ASIO usage guidelines for the use of ASIO, ASIO logo and ASIO
|
||||
compatible logos.
|
||||
//----------------------------------------------------------------------------------
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,97 @@
|
||||
//------------------------------------------------------------------------
|
||||
// Project : ASIO SDK
|
||||
//
|
||||
// Category : Interfaces
|
||||
// Filename : common/asiosys.h
|
||||
// Created by : Steinberg, 05/1996
|
||||
// Description : Steinberg Audio Stream I/O
|
||||
//
|
||||
//-----------------------------------------------------------------------------
|
||||
// This file is part of a Steinberg SDK. It is subject to the license terms
|
||||
// in the LICENSE file found in the top-level directory of this distribution
|
||||
// and at www.steinberg.net/sdklicenses.
|
||||
// No part of the SDK, including this file, may be copied, modified, propagated,
|
||||
// or distributed except according to the terms contained in the LICENSE file.
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef __asiosys__
|
||||
#define __asiosys__
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
#undef MAC
|
||||
#define PPC 0
|
||||
#define WINDOWS 1
|
||||
#define SGI 0
|
||||
#define SUN 0
|
||||
#define LINUX 0
|
||||
#define BEOS 0
|
||||
|
||||
#define NATIVE_INT64 0
|
||||
#define IEEE754_64FLOAT 1
|
||||
|
||||
#elif BEOS
|
||||
#define MAC 0
|
||||
#define PPC 0
|
||||
#define WINDOWS 0
|
||||
#define PC 0
|
||||
#define SGI 0
|
||||
#define SUN 0
|
||||
#define LINUX 0
|
||||
|
||||
#define NATIVE_INT64 0
|
||||
#define IEEE754_64FLOAT 1
|
||||
|
||||
#ifndef DEBUG
|
||||
#define DEBUG 0
|
||||
#if DEBUG
|
||||
void DEBUGGERMESSAGE(char *string);
|
||||
#else
|
||||
#define DEBUGGERMESSAGE(a)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#elif SGI
|
||||
#define MAC 0
|
||||
#define PPC 0
|
||||
#define WINDOWS 0
|
||||
#define PC 0
|
||||
#define SUN 0
|
||||
#define LINUX 0
|
||||
#define BEOS 0
|
||||
|
||||
#define NATIVE_INT64 0
|
||||
#define IEEE754_64FLOAT 1
|
||||
|
||||
#ifndef DEBUG
|
||||
#define DEBUG 0
|
||||
#if DEBUG
|
||||
void DEBUGGERMESSAGE(char *string);
|
||||
#else
|
||||
#define DEBUGGERMESSAGE(a)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#else // MAC
|
||||
#define MAC 1
|
||||
#define PPC 1
|
||||
#define WINDOWS 0
|
||||
#define PC 0
|
||||
#define SGI 0
|
||||
#define SUN 0
|
||||
#define LINUX 0
|
||||
#define BEOS 0
|
||||
|
||||
#define NATIVE_INT64 0
|
||||
#define IEEE754_64FLOAT 1
|
||||
|
||||
#ifndef DEBUG
|
||||
#define DEBUG 0
|
||||
#if DEBUG
|
||||
void DEBUGGERMESSAGE(char *string);
|
||||
#else
|
||||
#define DEBUGGERMESSAGE(a)
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
//------------------------------------------------------------------------
|
||||
// Project : ASIO SDK
|
||||
//
|
||||
// Category : Interfaces
|
||||
// Filename : common/iasiodrv.h
|
||||
// Created by : Steinberg, 05/1996
|
||||
// Description : Steinberg Audio Stream I/O API v2.3
|
||||
//
|
||||
//-----------------------------------------------------------------------------
|
||||
// This file is part of a Steinberg SDK. It is subject to the license terms
|
||||
// in the LICENSE file found in the top-level directory of this distribution
|
||||
// and at www.steinberg.net/sdklicenses.
|
||||
// No part of the SDK, including this file, may be copied, modified, propagated,
|
||||
// or distributed except according to the terms contained in the LICENSE file.
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include "asiosys.h"
|
||||
#include "asio.h"
|
||||
|
||||
/* Forward Declarations */
|
||||
|
||||
#ifndef __ASIODRIVER_FWD_DEFINED__
|
||||
#define __ASIODRIVER_FWD_DEFINED__
|
||||
typedef interface IASIO IASIO;
|
||||
#endif /* __ASIODRIVER_FWD_DEFINED__ */
|
||||
|
||||
interface IASIO : public IUnknown
|
||||
{
|
||||
|
||||
virtual ASIOBool init(void *sysHandle) = 0;
|
||||
virtual void getDriverName(char *name) = 0;
|
||||
virtual long getDriverVersion() = 0;
|
||||
virtual void getErrorMessage(char *string) = 0;
|
||||
virtual ASIOError start() = 0;
|
||||
virtual ASIOError stop() = 0;
|
||||
virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels) = 0;
|
||||
virtual ASIOError getLatencies(long *inputLatency, long *outputLatency) = 0;
|
||||
virtual ASIOError getBufferSize(long *minSize, long *maxSize,
|
||||
long *preferredSize, long *granularity) = 0;
|
||||
virtual ASIOError canSampleRate(ASIOSampleRate sampleRate) = 0;
|
||||
virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate) = 0;
|
||||
virtual ASIOError setSampleRate(ASIOSampleRate sampleRate) = 0;
|
||||
virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources) = 0;
|
||||
virtual ASIOError setClockSource(long reference) = 0;
|
||||
virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0;
|
||||
virtual ASIOError getChannelInfo(ASIOChannelInfo *info) = 0;
|
||||
virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels,
|
||||
long bufferSize, ASIOCallbacks *callbacks) = 0;
|
||||
virtual ASIOError disposeBuffers() = 0;
|
||||
virtual ASIOError controlPanel() = 0;
|
||||
virtual ASIOError future(long selector,void *opt) = 0;
|
||||
virtual ASIOError outputReady() = 0;
|
||||
};
|
||||
Vendored
+1228
File diff suppressed because it is too large
Load Diff
Vendored
+181
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
|
||||
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
|
||||
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
|
||||
import static android.content.pm.PackageManager.DONT_KILL_APP;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.media.midi.MidiDeviceService;
|
||||
import android.media.midi.MidiReceiver;
|
||||
import android.media.midi.MidiUmpDeviceService;
|
||||
import android.os.Build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class VirtualMidiServices
|
||||
{
|
||||
/** Argument is the receiver that should be sent outgoing messages.
|
||||
The return value is a newly-created receiver that will receive incoming messages.
|
||||
*/
|
||||
private static native MidiReceiver addVirtualPort (MidiReceiver output, boolean isUmp);
|
||||
|
||||
/** Argument is a receiver previously returned from addVirtualPort. */
|
||||
private static native void removeVirtualPort (MidiReceiver output);
|
||||
|
||||
public static class VirtualPort extends MidiReceiver
|
||||
{
|
||||
@Override
|
||||
public void onSend (byte[] msg, int offset, int count, long timestamp) throws IOException
|
||||
{
|
||||
if (onSend != null)
|
||||
onSend.send (msg, offset, count, timestamp);
|
||||
}
|
||||
|
||||
public MidiReceiver onSend;
|
||||
}
|
||||
|
||||
public static class VirtualBytestreamService extends MidiDeviceService
|
||||
{
|
||||
@Override
|
||||
public MidiReceiver[] onGetInputPortReceivers()
|
||||
{
|
||||
return new MidiReceiver[] { port };
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate()
|
||||
{
|
||||
super.onCreate();
|
||||
MidiReceiver[] receivers = getOutputPortReceivers();
|
||||
port.onSend = addVirtualPort (receivers != null && receivers.length > 0 ? receivers[0] : null, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy()
|
||||
{
|
||||
removeVirtualPort (port.onSend);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private final VirtualPort port = new VirtualPort();
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
|
||||
public static class VirtualUmpService extends MidiUmpDeviceService
|
||||
{
|
||||
@Override
|
||||
public List<MidiReceiver> onGetInputPortReceivers()
|
||||
{
|
||||
return Collections.singletonList (port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate()
|
||||
{
|
||||
super.onCreate();
|
||||
List<MidiReceiver> receivers = getOutputPortReceivers();
|
||||
port.onSend = addVirtualPort (! receivers.isEmpty() ? receivers.getFirst() : null, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy()
|
||||
{
|
||||
removeVirtualPort (port.onSend);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private final VirtualPort port = new VirtualPort();
|
||||
}
|
||||
|
||||
private static void setVirtualMidiServiceEnabled (Context context, Class<?> klass, boolean x)
|
||||
{
|
||||
PackageManager pm = context.getPackageManager();
|
||||
|
||||
if (pm == null)
|
||||
return;
|
||||
|
||||
ComponentName componentName = new ComponentName (context, klass);
|
||||
|
||||
int desiredState = x ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
|
||||
int actualState = pm.getComponentEnabledSetting (componentName);
|
||||
|
||||
if (desiredState == actualState)
|
||||
return;
|
||||
|
||||
pm.setComponentEnabledSetting (componentName, desiredState, DONT_KILL_APP);
|
||||
}
|
||||
|
||||
public static void setVirtualMidiBytestreamEnabled (Context context, boolean x)
|
||||
{
|
||||
setVirtualMidiServiceEnabled (context, VirtualBytestreamService.class, x);
|
||||
}
|
||||
|
||||
public static void setVirtualMidiUmpEnabled (Context context, boolean x)
|
||||
{
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM)
|
||||
setVirtualMidiServiceEnabled (context, VirtualUmpService.class, x);
|
||||
}
|
||||
|
||||
private static boolean isServiceAvailable (Context context, Class k)
|
||||
{
|
||||
PackageManager packageManager = context.getPackageManager();
|
||||
Intent intent = new Intent (context, k);
|
||||
List services = packageManager.queryIntentServices (intent, PackageManager.MATCH_DEFAULT_ONLY);
|
||||
|
||||
return services != null && ! services.isEmpty();
|
||||
}
|
||||
|
||||
public static boolean isVirtualBytestreamAvailable (Context context)
|
||||
{
|
||||
return isServiceAvailable (context, VirtualBytestreamService.class);
|
||||
}
|
||||
|
||||
public static boolean isVirtualUmpAvailable (Context context)
|
||||
{
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM)
|
||||
return false;
|
||||
|
||||
return isServiceAvailable (context, VirtualUmpService.class);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
// This header holds definitions for ALSA symbols that are only present in newer library versions.
|
||||
// It also contains weak definitions for functions that are only present in newer library versions.
|
||||
// By requesting the functions to weak-link, it's possible to build UMP-aware programs on Linux
|
||||
// versions that don't have up-to-date copies of ALSA, and it's also possible to run software
|
||||
// built on older Linux platforms, even if that software was built on a more recent system.
|
||||
|
||||
#if SND_LIB_VERSION < ((1 << 16) | (2 << 8) | 10)
|
||||
|
||||
struct snd_seq_ump_event_t
|
||||
{
|
||||
snd_seq_event_type_t type;
|
||||
unsigned char flags;
|
||||
unsigned char tag;
|
||||
unsigned char queue;
|
||||
snd_seq_timestamp_t time;
|
||||
snd_seq_addr_t source;
|
||||
snd_seq_addr_t dest;
|
||||
|
||||
union
|
||||
{
|
||||
decltype (snd_seq_event_t::data) data; // Older headers don't define snd_seq_event_data_t
|
||||
unsigned int ump[4];
|
||||
};
|
||||
};
|
||||
|
||||
struct snd_ump_endpoint_info_t;
|
||||
struct snd_ump_block_info_t;
|
||||
|
||||
#define snd_ump_block_info_alloca(ptr) __snd_alloca (ptr, snd_ump_block_info)
|
||||
#define snd_ump_endpoint_info_alloca(ptr) __snd_alloca (ptr, snd_ump_endpoint_info)
|
||||
|
||||
constexpr auto SND_SEQ_CLIENT_LEGACY_MIDI = 0;
|
||||
constexpr auto SND_SEQ_CLIENT_UMP_MIDI_1_0 = 1;
|
||||
constexpr auto SND_SEQ_CLIENT_UMP_MIDI_2_0 = 2;
|
||||
|
||||
constexpr auto SND_UMP_EP_INFO_STATIC_BLOCKS = 0x1;
|
||||
constexpr auto SND_UMP_EP_INFO_PROTO_MIDI1 = 0x100;
|
||||
constexpr auto SND_UMP_EP_INFO_PROTO_MIDI2 = 0x200;
|
||||
|
||||
constexpr auto SND_SEQ_PORT_CAP_INACTIVE = 1 << 8;
|
||||
|
||||
constexpr auto SND_SEQ_EVENT_UMP = 1 << 5;
|
||||
|
||||
constexpr auto SND_SEQ_PORT_DIR_INPUT = 1;
|
||||
constexpr auto SND_SEQ_PORT_DIR_OUTPUT = 2;
|
||||
constexpr auto SND_SEQ_PORT_DIR_BIDIRECTION = 3;
|
||||
|
||||
constexpr auto SND_UMP_BLOCK_UI_HINT_UNKNOWN = 0;
|
||||
constexpr auto SND_UMP_BLOCK_UI_HINT_RECEIVER = 1;
|
||||
constexpr auto SND_UMP_BLOCK_UI_HINT_SENDER = 2;
|
||||
constexpr auto SND_UMP_BLOCK_UI_HINT_BOTH = 3;
|
||||
|
||||
constexpr auto SND_UMP_BLOCK_IS_MIDI1 = 1U << 0;
|
||||
constexpr auto SND_UMP_BLOCK_IS_LOWSPEED = 1U << 1;
|
||||
|
||||
constexpr auto SND_UMP_DIR_INPUT = 1;
|
||||
constexpr auto SND_UMP_DIR_OUTPUT = 2;
|
||||
constexpr auto SND_UMP_DIR_BIDIRECTION = 3;
|
||||
|
||||
constexpr auto SND_UMP_EP_INFO_PROTO_JRTS_TX = 1;
|
||||
constexpr auto SND_UMP_EP_INFO_PROTO_JRTS_RX = 2;
|
||||
#endif
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wredundant-decls")
|
||||
|
||||
extern "C"
|
||||
{
|
||||
[[gnu::weak]] int snd_seq_client_info_get_midi_version (const snd_seq_client_info_t*);
|
||||
[[gnu::weak]] int snd_seq_set_client_midi_version (snd_seq_t*, int);
|
||||
[[gnu::weak]] int snd_seq_set_client_ump_conversion (snd_seq_t*, int);
|
||||
[[gnu::weak]] int snd_seq_ump_event_input (snd_seq_t*, snd_seq_ump_event_t**);
|
||||
[[gnu::weak]] int snd_seq_ump_event_output_direct (snd_seq_t*, snd_seq_ump_event_t*);
|
||||
[[gnu::weak]] int snd_seq_port_info_get_ump_is_midi1 (const snd_seq_port_info_t*);
|
||||
[[gnu::weak]] int snd_seq_port_info_get_ump_group (const snd_seq_port_info_t*);
|
||||
[[gnu::weak]] int snd_seq_create_ump_endpoint (snd_seq_t*, const snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] int snd_seq_create_ump_block (snd_seq_t*, int, const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] int snd_seq_set_ump_block_info (snd_seq_t*, int, const void*);
|
||||
[[gnu::weak]] int snd_seq_get_ump_block_info (snd_seq_t*, int, int, void*);
|
||||
[[gnu::weak]] int snd_seq_get_ump_endpoint_info (snd_seq_t*, int, void*);
|
||||
|
||||
[[gnu::weak]] const char* snd_ump_endpoint_info_get_product_id (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] const unsigned char* snd_ump_endpoint_info_get_sw_revision (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_family_id (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_flags (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_manufacturer_id (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_model_id (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_num_blocks (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_protocol (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_protocol_caps (const snd_ump_endpoint_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_endpoint_info_get_version (const snd_ump_endpoint_info_t*);
|
||||
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_product_id (snd_ump_endpoint_info_t*, const char*);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_sw_revision (snd_ump_endpoint_info_t*, const unsigned char*);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_family_id (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_flags (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_manufacturer_id (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_model_id (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_name (snd_ump_endpoint_info_t*, const char*);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_num_blocks (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_protocol (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_protocol_caps (snd_ump_endpoint_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_endpoint_info_set_version (snd_ump_endpoint_info_t*, unsigned int);
|
||||
|
||||
[[gnu::weak]] const char* snd_ump_block_info_get_name (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_active (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_direction (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_first_group (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_flags (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_num_groups (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_sysex8_streams (const snd_ump_block_info_t*);
|
||||
[[gnu::weak]] unsigned int snd_ump_block_info_get_ui_hint (const snd_ump_block_info_t*);
|
||||
|
||||
[[gnu::weak]] void snd_ump_block_info_set_name (snd_ump_block_info_t*, const char*);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_active (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_direction (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_first_group (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_flags (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_num_groups (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_sysex8_streams (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_ui_hint (snd_ump_block_info_t*, unsigned int);
|
||||
[[gnu::weak]] void snd_ump_block_info_set_block_id (snd_ump_block_info_t*, unsigned int);
|
||||
|
||||
[[gnu::weak]] int snd_seq_port_info_get_direction (const snd_seq_port_info_t*);
|
||||
|
||||
[[gnu::weak]] size_t snd_ump_block_info_sizeof (void);
|
||||
[[gnu::weak]] size_t snd_ump_endpoint_info_sizeof (void);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,481 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
|
||||
STATICMETHOD (getNativeOutputSampleRate, "getNativeOutputSampleRate", "(I)I") \
|
||||
METHOD (constructor, "<init>", "(IIIIII)V") \
|
||||
METHOD (getState, "getState", "()I") \
|
||||
METHOD (play, "play", "()V") \
|
||||
METHOD (stop, "stop", "()V") \
|
||||
METHOD (release, "release", "()V") \
|
||||
METHOD (flush, "flush", "()V") \
|
||||
METHOD (write, "write", "([SII)I") \
|
||||
|
||||
DECLARE_JNI_CLASS (AudioTrack, "android/media/AudioTrack")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
//==============================================================================
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
|
||||
METHOD (constructor, "<init>", "(IIIII)V") \
|
||||
METHOD (getState, "getState", "()I") \
|
||||
METHOD (startRecording, "startRecording", "()V") \
|
||||
METHOD (stop, "stop", "()V") \
|
||||
METHOD (read, "read", "([SII)I") \
|
||||
METHOD (release, "release", "()V") \
|
||||
|
||||
DECLARE_JNI_CLASS (AudioRecord, "android/media/AudioRecord")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
//==============================================================================
|
||||
enum
|
||||
{
|
||||
CHANNEL_OUT_STEREO = 12,
|
||||
CHANNEL_IN_STEREO = 12,
|
||||
CHANNEL_IN_MONO = 16,
|
||||
ENCODING_PCM_16BIT = 2,
|
||||
STREAM_MUSIC = 3,
|
||||
MODE_STREAM = 1,
|
||||
STATE_UNINITIALIZED = 0
|
||||
};
|
||||
|
||||
const char* const javaAudioTypeName = "Android Audio";
|
||||
|
||||
//==============================================================================
|
||||
class AndroidAudioIODevice final : public AudioIODevice,
|
||||
public Thread
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
AndroidAudioIODevice (const String& deviceName)
|
||||
: AudioIODevice (deviceName, javaAudioTypeName),
|
||||
Thread (SystemStats::getJUCEVersion() + ": audio"),
|
||||
minBufferSizeOut (0), minBufferSizeIn (0), callback (nullptr), sampleRate (0),
|
||||
numClientInputChannels (0), numDeviceInputChannels (0), numDeviceInputChannelsAvailable (2),
|
||||
numClientOutputChannels (0), numDeviceOutputChannels (0),
|
||||
actualBufferSize (0), isRunning (false),
|
||||
inputChannelBuffer (1, 1),
|
||||
outputChannelBuffer (1, 1)
|
||||
{
|
||||
JNIEnv* env = getEnv();
|
||||
sampleRate = env->CallStaticIntMethod (AudioTrack, AudioTrack.getNativeOutputSampleRate, MODE_STREAM);
|
||||
|
||||
minBufferSizeOut = (int) env->CallStaticIntMethod (AudioTrack, AudioTrack.getMinBufferSize, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT);
|
||||
minBufferSizeIn = (int) env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_STEREO, ENCODING_PCM_16BIT);
|
||||
|
||||
if (minBufferSizeIn <= 0)
|
||||
{
|
||||
minBufferSizeIn = env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_MONO, ENCODING_PCM_16BIT);
|
||||
|
||||
if (minBufferSizeIn > 0)
|
||||
numDeviceInputChannelsAvailable = 1;
|
||||
else
|
||||
numDeviceInputChannelsAvailable = 0;
|
||||
}
|
||||
|
||||
DBG ("Audio device - min buffers: " << minBufferSizeOut << ", " << minBufferSizeIn << "; "
|
||||
<< sampleRate << " Hz; input chans: " << numDeviceInputChannelsAvailable);
|
||||
}
|
||||
|
||||
~AndroidAudioIODevice() override
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
StringArray getOutputChannelNames() override
|
||||
{
|
||||
StringArray s;
|
||||
s.add ("Left");
|
||||
s.add ("Right");
|
||||
return s;
|
||||
}
|
||||
|
||||
StringArray getInputChannelNames() override
|
||||
{
|
||||
StringArray s;
|
||||
|
||||
if (numDeviceInputChannelsAvailable == 2)
|
||||
{
|
||||
s.add ("Left");
|
||||
s.add ("Right");
|
||||
}
|
||||
else if (numDeviceInputChannelsAvailable == 1)
|
||||
{
|
||||
s.add ("Audio Input");
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
Array<double> getAvailableSampleRates() override
|
||||
{
|
||||
Array<double> r;
|
||||
r.add ((double) sampleRate);
|
||||
return r;
|
||||
}
|
||||
|
||||
Array<int> getAvailableBufferSizes() override
|
||||
{
|
||||
Array<int> b;
|
||||
int n = 16;
|
||||
|
||||
for (int i = 0; i < 50; ++i)
|
||||
{
|
||||
b.add (n);
|
||||
n += n < 64 ? 16
|
||||
: (n < 512 ? 32
|
||||
: (n < 1024 ? 64
|
||||
: (n < 2048 ? 128 : 256)));
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
int getDefaultBufferSize() override { return 2048; }
|
||||
|
||||
String open (const BigInteger& inputChannels,
|
||||
const BigInteger& outputChannels,
|
||||
double requestedSampleRate,
|
||||
int bufferSize) override
|
||||
{
|
||||
close();
|
||||
|
||||
if (sampleRate != (int) requestedSampleRate)
|
||||
return "Sample rate not allowed";
|
||||
|
||||
lastError.clear();
|
||||
int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
|
||||
|
||||
numDeviceInputChannels = 0;
|
||||
numDeviceOutputChannels = 0;
|
||||
|
||||
activeOutputChans = outputChannels;
|
||||
activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
|
||||
numClientOutputChannels = activeOutputChans.countNumberOfSetBits();
|
||||
|
||||
activeInputChans = inputChannels;
|
||||
activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
|
||||
numClientInputChannels = activeInputChans.countNumberOfSetBits();
|
||||
|
||||
actualBufferSize = preferredBufferSize;
|
||||
inputChannelBuffer.setSize (2, actualBufferSize);
|
||||
inputChannelBuffer.clear();
|
||||
outputChannelBuffer.setSize (2, actualBufferSize);
|
||||
outputChannelBuffer.clear();
|
||||
|
||||
JNIEnv* env = getEnv();
|
||||
|
||||
if (numClientOutputChannels > 0)
|
||||
{
|
||||
numDeviceOutputChannels = 2;
|
||||
outputDevice = GlobalRef (LocalRef<jobject> (env->NewObject (AudioTrack, AudioTrack.constructor,
|
||||
STREAM_MUSIC, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT,
|
||||
(jint) (minBufferSizeOut * numDeviceOutputChannels * static_cast<int> (sizeof (int16))), MODE_STREAM)));
|
||||
|
||||
getUnderrunCount = env->GetMethodID (AudioTrack, "getUnderrunCount", "()I");
|
||||
|
||||
int outputDeviceState = env->CallIntMethod (outputDevice, AudioTrack.getState);
|
||||
if (outputDeviceState > 0)
|
||||
{
|
||||
isRunning = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// failed to open the device
|
||||
outputDevice.clear();
|
||||
lastError = "Error opening audio output device: android.media.AudioTrack failed with state = " + String (outputDeviceState);
|
||||
}
|
||||
}
|
||||
|
||||
if (numClientInputChannels > 0 && numDeviceInputChannelsAvailable > 0)
|
||||
{
|
||||
if (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
|
||||
{
|
||||
// If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
|
||||
// before trying to open an audio input device. This is not going to work!
|
||||
jassertfalse;
|
||||
|
||||
inputDevice.clear();
|
||||
lastError = "Error opening audio input device: the app was not granted android.permission.RECORD_AUDIO";
|
||||
}
|
||||
else
|
||||
{
|
||||
numDeviceInputChannels = jmin (numClientInputChannels, numDeviceInputChannelsAvailable);
|
||||
inputDevice = GlobalRef (LocalRef<jobject> (env->NewObject (AudioRecord, AudioRecord.constructor,
|
||||
0 /* (default audio source) */, sampleRate,
|
||||
numDeviceInputChannelsAvailable > 1 ? CHANNEL_IN_STEREO : CHANNEL_IN_MONO,
|
||||
ENCODING_PCM_16BIT,
|
||||
(jint) (minBufferSizeIn * numDeviceInputChannels * static_cast<int> (sizeof (int16))))));
|
||||
|
||||
int inputDeviceState = env->CallIntMethod (inputDevice, AudioRecord.getState);
|
||||
if (inputDeviceState > 0)
|
||||
{
|
||||
isRunning = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// failed to open the device
|
||||
inputDevice.clear();
|
||||
lastError = "Error opening audio input device: android.media.AudioRecord failed with state = " + String (inputDeviceState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isRunning)
|
||||
{
|
||||
if (outputDevice != nullptr)
|
||||
env->CallVoidMethod (outputDevice, AudioTrack.play);
|
||||
|
||||
if (inputDevice != nullptr)
|
||||
env->CallVoidMethod (inputDevice, AudioRecord.startRecording);
|
||||
|
||||
startThread (Priority::high);
|
||||
}
|
||||
else
|
||||
{
|
||||
closeDevices();
|
||||
}
|
||||
|
||||
return lastError;
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
if (isRunning)
|
||||
{
|
||||
stopThread (2000);
|
||||
isRunning = false;
|
||||
closeDevices();
|
||||
}
|
||||
}
|
||||
|
||||
int getOutputLatencyInSamples() override { return (minBufferSizeOut * 3) / 4; }
|
||||
int getInputLatencyInSamples() override { return (minBufferSizeIn * 3) / 4; }
|
||||
bool isOpen() override { return isRunning; }
|
||||
int getCurrentBufferSizeSamples() override { return actualBufferSize; }
|
||||
int getCurrentBitDepth() override { return 16; }
|
||||
double getCurrentSampleRate() override { return sampleRate; }
|
||||
BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
|
||||
BigInteger getActiveInputChannels() const override { return activeInputChans; }
|
||||
String getLastError() override { return lastError; }
|
||||
bool isPlaying() override { return isRunning && callback != nullptr; }
|
||||
|
||||
int getXRunCount() const noexcept override
|
||||
{
|
||||
if (outputDevice != nullptr && getUnderrunCount != nullptr)
|
||||
return getEnv()->CallIntMethod (outputDevice, getUnderrunCount);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void start (AudioIODeviceCallback* newCallback) override
|
||||
{
|
||||
if (isRunning && callback != newCallback)
|
||||
{
|
||||
if (newCallback != nullptr)
|
||||
newCallback->audioDeviceAboutToStart (this);
|
||||
|
||||
const ScopedLock sl (callbackLock);
|
||||
callback = newCallback;
|
||||
}
|
||||
}
|
||||
|
||||
void stop() override
|
||||
{
|
||||
if (isRunning)
|
||||
{
|
||||
AudioIODeviceCallback* lastCallback;
|
||||
|
||||
{
|
||||
const ScopedLock sl (callbackLock);
|
||||
lastCallback = callback;
|
||||
callback = nullptr;
|
||||
}
|
||||
|
||||
if (lastCallback != nullptr)
|
||||
lastCallback->audioDeviceStopped();
|
||||
}
|
||||
}
|
||||
|
||||
void run() override
|
||||
{
|
||||
JNIEnv* env = getEnv();
|
||||
jshortArray audioBuffer = env->NewShortArray (actualBufferSize * jmax (numDeviceOutputChannels, numDeviceInputChannels));
|
||||
|
||||
using NativeInt16 = AudioData::Format<AudioData::Int16, AudioData::NativeEndian>;
|
||||
using NativeFloat32 = AudioData::Format<AudioData::Float32, AudioData::NativeEndian>;
|
||||
|
||||
while (! threadShouldExit())
|
||||
{
|
||||
if (inputDevice != nullptr)
|
||||
{
|
||||
jint numRead = env->CallIntMethod (inputDevice, AudioRecord.read, audioBuffer, 0, actualBufferSize * numDeviceInputChannels);
|
||||
|
||||
if (numRead < actualBufferSize * numDeviceInputChannels)
|
||||
{
|
||||
DBG ("Audio read under-run! " << numRead);
|
||||
}
|
||||
|
||||
jshort* const src = env->GetShortArrayElements (audioBuffer, nullptr);
|
||||
|
||||
AudioData::deinterleaveSamples (AudioData::InterleavedSource<NativeInt16> { reinterpret_cast<const uint16*> (src), numDeviceInputChannels },
|
||||
AudioData::NonInterleavedDest<NativeFloat32> { inputChannelBuffer.getArrayOfWritePointers(), inputChannelBuffer.getNumChannels() },
|
||||
actualBufferSize);
|
||||
|
||||
env->ReleaseShortArrayElements (audioBuffer, src, 0);
|
||||
}
|
||||
|
||||
if (threadShouldExit())
|
||||
break;
|
||||
|
||||
{
|
||||
const ScopedLock sl (callbackLock);
|
||||
|
||||
if (callback != nullptr)
|
||||
{
|
||||
callback->audioDeviceIOCallbackWithContext (inputChannelBuffer.getArrayOfReadPointers(),
|
||||
numClientInputChannels,
|
||||
outputChannelBuffer.getArrayOfWritePointers(),
|
||||
numClientOutputChannels,
|
||||
actualBufferSize, {});
|
||||
}
|
||||
else
|
||||
{
|
||||
outputChannelBuffer.clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (outputDevice != nullptr)
|
||||
{
|
||||
if (threadShouldExit())
|
||||
break;
|
||||
|
||||
jshort* const dest = env->GetShortArrayElements (audioBuffer, nullptr);
|
||||
|
||||
AudioData::interleaveSamples (AudioData::NonInterleavedSource<NativeFloat32> { outputChannelBuffer.getArrayOfReadPointers(), outputChannelBuffer.getNumChannels() },
|
||||
AudioData::InterleavedDest<NativeInt16> { reinterpret_cast<uint16*> (dest), numDeviceOutputChannels },
|
||||
actualBufferSize);
|
||||
|
||||
env->ReleaseShortArrayElements (audioBuffer, dest, 0);
|
||||
jint numWritten = env->CallIntMethod (outputDevice, AudioTrack.write, audioBuffer, 0, actualBufferSize * numDeviceOutputChannels);
|
||||
|
||||
if (numWritten < actualBufferSize * numDeviceOutputChannels)
|
||||
{
|
||||
DBG ("Audio write underrun! " << numWritten);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int minBufferSizeOut, minBufferSizeIn;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
CriticalSection callbackLock;
|
||||
AudioIODeviceCallback* callback;
|
||||
jint sampleRate;
|
||||
int numClientInputChannels, numDeviceInputChannels, numDeviceInputChannelsAvailable;
|
||||
int numClientOutputChannels, numDeviceOutputChannels;
|
||||
int actualBufferSize;
|
||||
bool isRunning;
|
||||
String lastError;
|
||||
BigInteger activeOutputChans, activeInputChans;
|
||||
GlobalRef outputDevice, inputDevice;
|
||||
AudioBuffer<float> inputChannelBuffer, outputChannelBuffer;
|
||||
jmethodID getUnderrunCount = nullptr;
|
||||
|
||||
void closeDevices()
|
||||
{
|
||||
if (outputDevice != nullptr)
|
||||
{
|
||||
outputDevice.callVoidMethod (AudioTrack.stop);
|
||||
outputDevice.callVoidMethod (AudioTrack.release);
|
||||
outputDevice.clear();
|
||||
}
|
||||
|
||||
if (inputDevice != nullptr)
|
||||
{
|
||||
inputDevice.callVoidMethod (AudioRecord.stop);
|
||||
inputDevice.callVoidMethod (AudioRecord.release);
|
||||
inputDevice.clear();
|
||||
}
|
||||
}
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class AndroidAudioIODeviceType final : public AudioIODeviceType
|
||||
{
|
||||
public:
|
||||
AndroidAudioIODeviceType() : AudioIODeviceType (javaAudioTypeName) {}
|
||||
|
||||
//==============================================================================
|
||||
void scanForDevices() {}
|
||||
StringArray getDeviceNames (bool) const { return StringArray (javaAudioTypeName); }
|
||||
int getDefaultDeviceIndex (bool) const { return 0; }
|
||||
int getIndexOfDevice (AudioIODevice* device, bool) const { return device != nullptr ? 0 : -1; }
|
||||
bool hasSeparateInputsAndOutputs() const { return false; }
|
||||
|
||||
AudioIODevice* createDevice (const String& outputDeviceName,
|
||||
const String& inputDeviceName)
|
||||
{
|
||||
std::unique_ptr<AndroidAudioIODevice> dev;
|
||||
|
||||
if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
|
||||
{
|
||||
dev.reset (new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
|
||||
: inputDeviceName));
|
||||
|
||||
if (dev->getCurrentSampleRate() <= 0 || dev->getDefaultBufferSize() <= 0)
|
||||
dev = nullptr;
|
||||
}
|
||||
|
||||
return dev.release();
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType)
|
||||
};
|
||||
|
||||
|
||||
//==============================================================================
|
||||
extern bool isOboeAvailable();
|
||||
extern bool isOpenSLAvailable();
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class iOSAudioIODeviceType;
|
||||
|
||||
class iOSAudioIODevice : public AudioIODevice
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
String open (const BigInteger&, const BigInteger&, double, int) override;
|
||||
void close() override;
|
||||
|
||||
void start (AudioIODeviceCallback*) override;
|
||||
void stop() override;
|
||||
|
||||
Array<double> getAvailableSampleRates() override;
|
||||
Array<int> getAvailableBufferSizes() override;
|
||||
|
||||
bool setAudioPreprocessingEnabled (bool) override;
|
||||
|
||||
//==============================================================================
|
||||
bool isPlaying() override;
|
||||
bool isOpen() override;
|
||||
String getLastError() override;
|
||||
|
||||
//==============================================================================
|
||||
StringArray getOutputChannelNames() override;
|
||||
StringArray getInputChannelNames() override;
|
||||
|
||||
int getDefaultBufferSize() override;
|
||||
int getCurrentBufferSizeSamples() override;
|
||||
|
||||
double getCurrentSampleRate() override;
|
||||
|
||||
int getCurrentBitDepth() override;
|
||||
|
||||
BigInteger getActiveOutputChannels() const override;
|
||||
BigInteger getActiveInputChannels() const override;
|
||||
|
||||
int getOutputLatencyInSamples() override;
|
||||
int getInputLatencyInSamples() override;
|
||||
|
||||
int getXRunCount() const noexcept override;
|
||||
|
||||
AudioWorkgroup getWorkgroup() const override;
|
||||
|
||||
//==============================================================================
|
||||
void setMidiMessageCollector (MidiMessageCollector*);
|
||||
AudioPlayHead* getAudioPlayHead() const;
|
||||
|
||||
//==============================================================================
|
||||
bool isInterAppAudioConnected() const;
|
||||
#if JUCE_MODULE_AVAILABLE_juce_graphics
|
||||
Image getIcon (int size);
|
||||
#endif
|
||||
void switchApplication();
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
iOSAudioIODevice (iOSAudioIODeviceType*, const String&, const String&);
|
||||
|
||||
//==============================================================================
|
||||
friend class iOSAudioIODeviceType;
|
||||
friend struct AudioSessionHolder;
|
||||
|
||||
struct Pimpl;
|
||||
std::unique_ptr<Pimpl> pimpl;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (iOSAudioIODevice)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+1304
File diff suppressed because it is too large
Load Diff
+137
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Some shared helpers methods for using the high-performance audio paths on
|
||||
Android devices (OpenSL and Oboe).
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
namespace juce::AndroidHighPerformanceAudioHelpers
|
||||
{
|
||||
//==============================================================================
|
||||
static double getNativeSampleRate()
|
||||
{
|
||||
return audioManagerGetProperty ("android.media.property.OUTPUT_SAMPLE_RATE").getDoubleValue();
|
||||
}
|
||||
|
||||
static int getNativeBufferSizeHint()
|
||||
{
|
||||
// This property is a hint of a native buffer size but it does not guarantee the size used.
|
||||
auto deviceBufferSize = audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER").getIntValue();
|
||||
|
||||
if (deviceBufferSize == 0)
|
||||
return 192;
|
||||
|
||||
return deviceBufferSize;
|
||||
}
|
||||
|
||||
static bool isProAudioDevice()
|
||||
{
|
||||
static bool isSapaSupported = SystemStats::getDeviceManufacturer().containsIgnoreCase ("SAMSUNG")
|
||||
&& DynamicLibrary().open ("libapa_jni.so");
|
||||
|
||||
return androidHasSystemFeature ("android.hardware.audio.pro") || isSapaSupported;
|
||||
}
|
||||
|
||||
static bool hasLowLatencyAudioPath()
|
||||
{
|
||||
return androidHasSystemFeature ("android.hardware.audio.low_latency");
|
||||
}
|
||||
|
||||
static bool canUseHighPerformanceAudioPath (int nativeBufferSize, int requestedBufferSize, int requestedSampleRate)
|
||||
{
|
||||
return ((requestedBufferSize % nativeBufferSize) == 0)
|
||||
&& approximatelyEqual ((double) requestedSampleRate, getNativeSampleRate())
|
||||
&& isProAudioDevice();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static int getMinimumBuffersToEnqueue (int nativeBufferSize, double requestedSampleRate)
|
||||
{
|
||||
if (canUseHighPerformanceAudioPath (nativeBufferSize, nativeBufferSize, (int) requestedSampleRate))
|
||||
{
|
||||
// see https://developer.android.com/ndk/guides/audio/opensl/opensl-prog-notes.html#sandp
|
||||
// > Beginning with Android 4.3 (API level 18), a buffer count of one is sufficient for lower latency.
|
||||
return 1;
|
||||
}
|
||||
|
||||
// not using low-latency path so we can use the absolute minimum number of buffers to queue
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int buffersToQueueForBufferDuration (int nativeBufferSize, int bufferDurationInMs, double sampleRate) noexcept
|
||||
{
|
||||
auto maxBufferFrames = static_cast<int> (std::ceil (bufferDurationInMs * sampleRate / 1000.0));
|
||||
auto maxNumBuffers = static_cast<int> (std::ceil (static_cast<double> (maxBufferFrames)
|
||||
/ static_cast<double> (nativeBufferSize)));
|
||||
|
||||
return jmax (getMinimumBuffersToEnqueue (nativeBufferSize, sampleRate), maxNumBuffers);
|
||||
}
|
||||
|
||||
static int getMaximumBuffersToEnqueue (int nativeBufferSize, double maximumSampleRate) noexcept
|
||||
{
|
||||
static constexpr int maxBufferSizeMs = 200;
|
||||
|
||||
return jmax (8, buffersToQueueForBufferDuration (nativeBufferSize, maxBufferSizeMs, maximumSampleRate));
|
||||
}
|
||||
|
||||
static Array<int> getAvailableBufferSizes (int nativeBufferSize, Array<double> availableSampleRates)
|
||||
{
|
||||
auto minBuffersToQueue = getMinimumBuffersToEnqueue (nativeBufferSize, getNativeSampleRate());
|
||||
auto maxBuffersToQueue = getMaximumBuffersToEnqueue (nativeBufferSize, findMaximum (availableSampleRates.getRawDataPointer(),
|
||||
availableSampleRates.size()));
|
||||
|
||||
Array<int> bufferSizes;
|
||||
|
||||
for (int i = minBuffersToQueue; i <= maxBuffersToQueue; ++i)
|
||||
bufferSizes.add (i * nativeBufferSize);
|
||||
|
||||
return bufferSizes;
|
||||
}
|
||||
|
||||
static int getDefaultBufferSize (int nativeBufferSize, double currentSampleRate)
|
||||
{
|
||||
static constexpr int defaultBufferSizeForLowLatencyDeviceMs = 40;
|
||||
static constexpr int defaultBufferSizeForStandardLatencyDeviceMs = 100;
|
||||
|
||||
auto defaultBufferLength = (hasLowLatencyAudioPath() ? defaultBufferSizeForLowLatencyDeviceMs
|
||||
: defaultBufferSizeForStandardLatencyDeviceMs);
|
||||
|
||||
auto defaultBuffersToEnqueue = buffersToQueueForBufferDuration (nativeBufferSize, defaultBufferLength, currentSampleRate);
|
||||
return defaultBuffersToEnqueue * nativeBufferSize;
|
||||
}
|
||||
|
||||
} // namespace juce::AndroidHighPerformanceAudioHelpers
|
||||
@@ -0,0 +1,700 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
static void* juce_libjackHandle = nullptr;
|
||||
|
||||
static void* juce_loadJackFunction (const char* const name)
|
||||
{
|
||||
if (juce_libjackHandle == nullptr)
|
||||
return nullptr;
|
||||
|
||||
#if JUCE_WINDOWS
|
||||
return GetProcAddress ((HMODULE) juce_libjackHandle, name);
|
||||
#else
|
||||
return dlsym (juce_libjackHandle, name);
|
||||
#endif
|
||||
}
|
||||
|
||||
#define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
|
||||
static inline return_type fn_name argument_types \
|
||||
{ \
|
||||
using ReturnType = return_type; \
|
||||
typedef return_type (*fn_type) argument_types; \
|
||||
static fn_type fn = (fn_type) juce_loadJackFunction (#fn_name); \
|
||||
jassert (fn != nullptr); \
|
||||
return (fn != nullptr) ? ((*fn) arguments) : ReturnType(); \
|
||||
}
|
||||
|
||||
#define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
|
||||
static inline void fn_name argument_types \
|
||||
{ \
|
||||
typedef void (*fn_type) argument_types; \
|
||||
static fn_type fn = (fn_type) juce_loadJackFunction (#fn_name); \
|
||||
jassert (fn != nullptr); \
|
||||
if (fn != nullptr) (*fn) arguments; \
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status, ...), (client_name, options, status))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client))
|
||||
JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client))
|
||||
JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client))
|
||||
JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function) (void* arg), void* arg), (client, function, arg))
|
||||
JUCE_DECL_VOID_JACK_FUNCTION (jack_on_info_shutdown, (jack_client_t* client, JackInfoShutdownCallback function, void* arg), (client, function, arg))
|
||||
JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes))
|
||||
JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port))
|
||||
JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size))
|
||||
JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func) (const char*)), (func))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg))
|
||||
JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port))
|
||||
JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port))
|
||||
JUCE_DECL_JACK_FUNCTION (void*, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_set_xrun_callback, (jack_client_t* client, JackXRunCallback xrun_callback, void* arg), (client, xrun_callback, arg))
|
||||
JUCE_DECL_JACK_FUNCTION (int, jack_port_flags, (const jack_port_t* port), (port))
|
||||
JUCE_DECL_JACK_FUNCTION (jack_port_t*, jack_port_by_name, (jack_client_t* client, const char* name), (client, name))
|
||||
JUCE_DECL_VOID_JACK_FUNCTION (jack_free, (void* ptr), (ptr))
|
||||
|
||||
#if JUCE_DEBUG
|
||||
#define JACK_LOGGING_ENABLED 1
|
||||
#endif
|
||||
|
||||
#if JACK_LOGGING_ENABLED
|
||||
namespace
|
||||
{
|
||||
void jack_Log (const String& s)
|
||||
{
|
||||
std::cerr << s << std::endl;
|
||||
}
|
||||
|
||||
const char* getJackErrorMessage (const jack_status_t status)
|
||||
{
|
||||
if (status & JackServerFailed
|
||||
|| status & JackServerError) return "Unable to connect to JACK server";
|
||||
if (status & JackVersionError) return "Client's protocol version does not match";
|
||||
if (status & JackInvalidOption) return "The operation contained an invalid or unsupported option";
|
||||
if (status & JackNameNotUnique) return "The desired client name was not unique";
|
||||
if (status & JackNoSuchClient) return "Requested client does not exist";
|
||||
if (status & JackInitFailure) return "Unable to initialize client";
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
#define JUCE_JACK_LOG_STATUS(x) { if (const char* m = getJackErrorMessage (x)) jack_Log (m); }
|
||||
#define JUCE_JACK_LOG(x) jack_Log(x)
|
||||
#else
|
||||
#define JUCE_JACK_LOG_STATUS(x) {}
|
||||
#define JUCE_JACK_LOG(x) {}
|
||||
#endif
|
||||
|
||||
|
||||
//==============================================================================
|
||||
#ifndef JUCE_JACK_CLIENT_NAME
|
||||
#ifdef JucePlugin_Name
|
||||
#define JUCE_JACK_CLIENT_NAME JucePlugin_Name
|
||||
#else
|
||||
#define JUCE_JACK_CLIENT_NAME "JUCEJack"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
struct JackPortIterator
|
||||
{
|
||||
JackPortIterator (jack_client_t* const client, const bool forInput)
|
||||
{
|
||||
if (client != nullptr)
|
||||
ports.reset (juce::jack_get_ports (client, nullptr, nullptr,
|
||||
forInput ? JackPortIsInput : JackPortIsOutput));
|
||||
}
|
||||
|
||||
bool next()
|
||||
{
|
||||
if (ports == nullptr || ports.get()[index + 1] == nullptr)
|
||||
return false;
|
||||
|
||||
name = CharPointer_UTF8 (ports.get()[++index]);
|
||||
return true;
|
||||
}
|
||||
|
||||
String getClientName() const
|
||||
{
|
||||
return name.upToFirstOccurrenceOf (":", false, false);
|
||||
}
|
||||
|
||||
String getChannelName() const
|
||||
{
|
||||
return name.fromFirstOccurrenceOf (":", false, false);
|
||||
}
|
||||
|
||||
struct Free
|
||||
{
|
||||
void operator() (const char** ptr) const noexcept { juce::jack_free (ptr); }
|
||||
};
|
||||
|
||||
std::unique_ptr<const char*, Free> ports;
|
||||
int index = -1;
|
||||
String name;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class JackAudioIODevice final : public AudioIODevice
|
||||
{
|
||||
public:
|
||||
JackAudioIODevice (const String& inName,
|
||||
const String& outName,
|
||||
std::function<void()> notifyIn)
|
||||
: AudioIODevice (outName.isEmpty() ? inName : outName, "JACK"),
|
||||
inputName (inName),
|
||||
outputName (outName),
|
||||
notifyChannelsChanged (std::move (notifyIn))
|
||||
{
|
||||
jassert (outName.isNotEmpty() || inName.isNotEmpty());
|
||||
|
||||
jack_status_t status = {};
|
||||
client = juce::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
|
||||
|
||||
if (client == nullptr)
|
||||
{
|
||||
JUCE_JACK_LOG_STATUS (status);
|
||||
}
|
||||
else
|
||||
{
|
||||
juce::jack_set_error_function (errorCallback);
|
||||
|
||||
// open input ports
|
||||
const StringArray inputChannels (getInputChannelNames());
|
||||
for (int i = 0; i < inputChannels.size(); ++i)
|
||||
{
|
||||
String inputChannelName;
|
||||
inputChannelName << "in_" << ++totalNumberOfInputChannels;
|
||||
|
||||
inputPorts.add (juce::jack_port_register (client, inputChannelName.toUTF8(),
|
||||
JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
|
||||
}
|
||||
|
||||
// open output ports
|
||||
const StringArray outputChannels (getOutputChannelNames());
|
||||
for (int i = 0; i < outputChannels.size(); ++i)
|
||||
{
|
||||
String outputChannelName;
|
||||
outputChannelName << "out_" << ++totalNumberOfOutputChannels;
|
||||
|
||||
outputPorts.add (juce::jack_port_register (client, outputChannelName.toUTF8(),
|
||||
JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
|
||||
}
|
||||
|
||||
inChans.calloc (totalNumberOfInputChannels + 2);
|
||||
outChans.calloc (totalNumberOfOutputChannels + 2);
|
||||
}
|
||||
}
|
||||
|
||||
~JackAudioIODevice() override
|
||||
{
|
||||
close();
|
||||
if (client != nullptr)
|
||||
{
|
||||
juce::jack_client_close (client);
|
||||
client = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
StringArray getChannelNames (const String& clientName, bool forInput) const
|
||||
{
|
||||
StringArray names;
|
||||
|
||||
for (JackPortIterator i (client, forInput); i.next();)
|
||||
if (i.getClientName() == clientName)
|
||||
names.add (i.getChannelName());
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
StringArray getOutputChannelNames() override { return getChannelNames (outputName, true); }
|
||||
StringArray getInputChannelNames() override { return getChannelNames (inputName, false); }
|
||||
|
||||
Array<double> getAvailableSampleRates() override
|
||||
{
|
||||
Array<double> rates;
|
||||
|
||||
if (client != nullptr)
|
||||
rates.add (juce::jack_get_sample_rate (client));
|
||||
|
||||
return rates;
|
||||
}
|
||||
|
||||
Array<int> getAvailableBufferSizes() override
|
||||
{
|
||||
Array<int> sizes;
|
||||
|
||||
if (client != nullptr)
|
||||
sizes.add (static_cast<int> (juce::jack_get_buffer_size (client)));
|
||||
|
||||
return sizes;
|
||||
}
|
||||
|
||||
int getDefaultBufferSize() override { return getCurrentBufferSizeSamples(); }
|
||||
int getCurrentBufferSizeSamples() override { return client != nullptr ? static_cast<int> (juce::jack_get_buffer_size (client)) : 0; }
|
||||
double getCurrentSampleRate() override { return client != nullptr ? static_cast<int> (juce::jack_get_sample_rate (client)) : 0; }
|
||||
|
||||
template <typename Fn>
|
||||
void forEachClientChannel (const String& clientName, bool isInput, Fn&& fn)
|
||||
{
|
||||
auto index = 0;
|
||||
|
||||
for (JackPortIterator i (client, isInput); i.next();)
|
||||
{
|
||||
if (i.getClientName() != clientName)
|
||||
continue;
|
||||
|
||||
fn (i.ports.get()[i.index], index);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
|
||||
double /* sampleRate */, int /* bufferSizeSamples */) override
|
||||
{
|
||||
if (client == nullptr)
|
||||
{
|
||||
lastError = "No JACK client running";
|
||||
return lastError;
|
||||
}
|
||||
|
||||
lastError.clear();
|
||||
close();
|
||||
|
||||
xruns.store (0, std::memory_order_relaxed);
|
||||
juce::jack_set_process_callback (client, processCallback, this);
|
||||
juce::jack_set_port_connect_callback (client, portConnectCallback, this);
|
||||
juce::jack_on_shutdown (client, shutdownCallback, this);
|
||||
juce::jack_on_info_shutdown (client, infoShutdownCallback, this);
|
||||
juce::jack_set_xrun_callback (client, xrunCallback, this);
|
||||
|
||||
if (juce::jack_activate (client) != 0)
|
||||
{
|
||||
lastError = "Failed to activate JACK client";
|
||||
return lastError;
|
||||
}
|
||||
|
||||
deviceIsOpen = true;
|
||||
|
||||
if (! inputChannels.isZero())
|
||||
{
|
||||
forEachClientChannel (inputName, false, [&] (const char* portName, int index)
|
||||
{
|
||||
if (! inputChannels[index])
|
||||
return;
|
||||
|
||||
jassert (index < inputPorts.size());
|
||||
|
||||
const auto* source = portName;
|
||||
const auto* inputPort = inputPorts[index];
|
||||
|
||||
jassert (juce::jack_port_flags (juce::jack_port_by_name (client, source)) & JackPortIsOutput);
|
||||
jassert (juce::jack_port_flags (inputPort) & JackPortIsInput);
|
||||
|
||||
auto error = juce::jack_connect (client, source, juce::jack_port_name (inputPort));
|
||||
if (error != 0)
|
||||
JUCE_JACK_LOG ("Cannot connect input port " + String (index) + " (" + portName + "), error " + String (error));
|
||||
});
|
||||
}
|
||||
|
||||
if (! outputChannels.isZero())
|
||||
{
|
||||
forEachClientChannel (outputName, true, [&] (const char* portName, int index)
|
||||
{
|
||||
if (! outputChannels[index])
|
||||
return;
|
||||
|
||||
jassert (index < outputPorts.size());
|
||||
|
||||
const auto* outputPort = outputPorts[index];
|
||||
const auto* destination = portName;
|
||||
|
||||
jassert (juce::jack_port_flags (outputPort) & JackPortIsOutput);
|
||||
jassert (juce::jack_port_flags (juce::jack_port_by_name (client, destination)) & JackPortIsInput);
|
||||
|
||||
auto error = juce::jack_connect (client, juce::jack_port_name (outputPort), destination);
|
||||
if (error != 0)
|
||||
JUCE_JACK_LOG ("Cannot connect output port " + String (index) + " (" + portName + "), error " + String (error));
|
||||
});
|
||||
}
|
||||
|
||||
updateActivePorts();
|
||||
|
||||
return lastError;
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
stop();
|
||||
|
||||
if (client != nullptr)
|
||||
{
|
||||
[[maybe_unused]] const auto result = juce::jack_deactivate (client);
|
||||
jassert (result == 0);
|
||||
|
||||
juce::jack_set_xrun_callback (client, xrunCallback, nullptr);
|
||||
juce::jack_set_process_callback (client, processCallback, nullptr);
|
||||
juce::jack_set_port_connect_callback (client, portConnectCallback, nullptr);
|
||||
juce::jack_on_shutdown (client, shutdownCallback, nullptr);
|
||||
juce::jack_on_info_shutdown (client, infoShutdownCallback, nullptr);
|
||||
}
|
||||
|
||||
deviceIsOpen = false;
|
||||
}
|
||||
|
||||
void start (AudioIODeviceCallback* newCallback) override
|
||||
{
|
||||
if (deviceIsOpen && newCallback != callback)
|
||||
{
|
||||
if (newCallback != nullptr)
|
||||
newCallback->audioDeviceAboutToStart (this);
|
||||
|
||||
AudioIODeviceCallback* const oldCallback = callback;
|
||||
|
||||
{
|
||||
const ScopedLock sl (callbackLock);
|
||||
callback = newCallback;
|
||||
}
|
||||
|
||||
if (oldCallback != nullptr)
|
||||
oldCallback->audioDeviceStopped();
|
||||
}
|
||||
}
|
||||
|
||||
void stop() override
|
||||
{
|
||||
start (nullptr);
|
||||
}
|
||||
|
||||
bool isOpen() override { return deviceIsOpen; }
|
||||
bool isPlaying() override { return callback != nullptr; }
|
||||
int getCurrentBitDepth() override { return 32; }
|
||||
String getLastError() override { return lastError; }
|
||||
int getXRunCount() const noexcept override { return xruns.load (std::memory_order_relaxed); }
|
||||
|
||||
BigInteger getActiveOutputChannels() const override { return activeOutputChannels; }
|
||||
BigInteger getActiveInputChannels() const override { return activeInputChannels; }
|
||||
|
||||
int getOutputLatencyInSamples() override
|
||||
{
|
||||
int latency = 0;
|
||||
|
||||
for (int i = 0; i < outputPorts.size(); i++)
|
||||
latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, outputPorts[i]));
|
||||
|
||||
return latency;
|
||||
}
|
||||
|
||||
int getInputLatencyInSamples() override
|
||||
{
|
||||
int latency = 0;
|
||||
|
||||
for (int i = 0; i < inputPorts.size(); i++)
|
||||
latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, inputPorts[i]));
|
||||
|
||||
return latency;
|
||||
}
|
||||
|
||||
String inputName, outputName;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class MainThreadDispatcher final : private AsyncUpdater
|
||||
{
|
||||
public:
|
||||
explicit MainThreadDispatcher (JackAudioIODevice& device) : ref (device) {}
|
||||
~MainThreadDispatcher() override { cancelPendingUpdate(); }
|
||||
|
||||
void updateActivePorts()
|
||||
{
|
||||
if (MessageManager::getInstance()->isThisTheMessageThread())
|
||||
handleAsyncUpdate();
|
||||
else
|
||||
triggerAsyncUpdate();
|
||||
}
|
||||
|
||||
private:
|
||||
void handleAsyncUpdate() override { ref.updateActivePorts(); }
|
||||
|
||||
JackAudioIODevice& ref;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
void process (const int numSamples)
|
||||
{
|
||||
int numActiveInChans = 0, numActiveOutChans = 0;
|
||||
|
||||
for (int i = 0; i < totalNumberOfInputChannels; ++i)
|
||||
{
|
||||
if (activeInputChannels[i])
|
||||
if (auto* in = (jack_default_audio_sample_t*) juce::jack_port_get_buffer (inputPorts.getUnchecked (i),
|
||||
static_cast<jack_nframes_t> (numSamples)))
|
||||
inChans[numActiveInChans++] = (float*) in;
|
||||
}
|
||||
|
||||
for (int i = 0; i < totalNumberOfOutputChannels; ++i)
|
||||
{
|
||||
if (activeOutputChannels[i])
|
||||
if (auto* out = (jack_default_audio_sample_t*) juce::jack_port_get_buffer (outputPorts.getUnchecked (i),
|
||||
static_cast<jack_nframes_t> (numSamples)))
|
||||
outChans[numActiveOutChans++] = (float*) out;
|
||||
}
|
||||
|
||||
const ScopedLock sl (callbackLock);
|
||||
|
||||
if (callback != nullptr)
|
||||
{
|
||||
if ((numActiveInChans + numActiveOutChans) > 0)
|
||||
callback->audioDeviceIOCallbackWithContext (inChans.getData(),
|
||||
numActiveInChans,
|
||||
outChans,
|
||||
numActiveOutChans,
|
||||
numSamples,
|
||||
{});
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < numActiveOutChans; ++i)
|
||||
zeromem (outChans[i], static_cast<size_t> (numSamples) * sizeof (float));
|
||||
}
|
||||
}
|
||||
|
||||
static int processCallback (jack_nframes_t nframes, void* callbackArgument)
|
||||
{
|
||||
if (callbackArgument != nullptr)
|
||||
((JackAudioIODevice*) callbackArgument)->process (static_cast<int> (nframes));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int xrunCallback (void* callbackArgument)
|
||||
{
|
||||
if (callbackArgument != nullptr)
|
||||
((JackAudioIODevice*) callbackArgument)->xruns++;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void updateActivePorts()
|
||||
{
|
||||
BigInteger newOutputChannels, newInputChannels;
|
||||
|
||||
for (int i = 0; i < outputPorts.size(); ++i)
|
||||
if (juce::jack_port_connected (outputPorts.getUnchecked (i)))
|
||||
newOutputChannels.setBit (i);
|
||||
|
||||
for (int i = 0; i < inputPorts.size(); ++i)
|
||||
if (juce::jack_port_connected (inputPorts.getUnchecked (i)))
|
||||
newInputChannels.setBit (i);
|
||||
|
||||
if (newOutputChannels != activeOutputChannels
|
||||
|| newInputChannels != activeInputChannels)
|
||||
{
|
||||
AudioIODeviceCallback* const oldCallback = callback;
|
||||
|
||||
stop();
|
||||
|
||||
activeOutputChannels = newOutputChannels;
|
||||
activeInputChannels = newInputChannels;
|
||||
|
||||
if (oldCallback != nullptr)
|
||||
start (oldCallback);
|
||||
|
||||
NullCheckedInvocation::invoke (notifyChannelsChanged);
|
||||
}
|
||||
}
|
||||
|
||||
static void portConnectCallback (jack_port_id_t, jack_port_id_t, int, void* arg)
|
||||
{
|
||||
if (JackAudioIODevice* device = static_cast<JackAudioIODevice*> (arg))
|
||||
device->mainThreadDispatcher.updateActivePorts();
|
||||
}
|
||||
|
||||
static void threadInitCallback (void* /* callbackArgument */)
|
||||
{
|
||||
JUCE_JACK_LOG ("JackAudioIODevice::initialise");
|
||||
}
|
||||
|
||||
static void shutdownCallback (void* callbackArgument)
|
||||
{
|
||||
JUCE_JACK_LOG ("JackAudioIODevice::shutdown");
|
||||
|
||||
if (JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument)
|
||||
{
|
||||
device->client = nullptr;
|
||||
device->close();
|
||||
}
|
||||
}
|
||||
|
||||
static void infoShutdownCallback ([[maybe_unused]] jack_status_t code, [[maybe_unused]] const char* reason, void* arg)
|
||||
{
|
||||
jassert (code == 0);
|
||||
|
||||
JUCE_JACK_LOG ("Shutting down with message:");
|
||||
JUCE_JACK_LOG (reason);
|
||||
|
||||
shutdownCallback (arg);
|
||||
}
|
||||
|
||||
static void errorCallback ([[maybe_unused]] const char* msg)
|
||||
{
|
||||
JUCE_JACK_LOG ("JackAudioIODevice::errorCallback " + String (msg));
|
||||
}
|
||||
|
||||
bool deviceIsOpen = false;
|
||||
jack_client_t* client = nullptr;
|
||||
String lastError;
|
||||
AudioIODeviceCallback* callback = nullptr;
|
||||
CriticalSection callbackLock;
|
||||
|
||||
HeapBlock<float*> inChans, outChans;
|
||||
int totalNumberOfInputChannels = 0;
|
||||
int totalNumberOfOutputChannels = 0;
|
||||
Array<jack_port_t*> inputPorts, outputPorts;
|
||||
BigInteger activeInputChannels, activeOutputChannels;
|
||||
|
||||
std::atomic<int> xruns { 0 };
|
||||
|
||||
std::function<void()> notifyChannelsChanged;
|
||||
MainThreadDispatcher mainThreadDispatcher { *this };
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class JackAudioIODeviceType;
|
||||
|
||||
class JackAudioIODeviceType final : public AudioIODeviceType
|
||||
{
|
||||
public:
|
||||
JackAudioIODeviceType()
|
||||
: AudioIODeviceType ("JACK")
|
||||
{}
|
||||
|
||||
void scanForDevices()
|
||||
{
|
||||
hasScanned = true;
|
||||
inputNames.clear();
|
||||
outputNames.clear();
|
||||
|
||||
#if (JUCE_LINUX || JUCE_BSD)
|
||||
if (juce_libjackHandle == nullptr) juce_libjackHandle = dlopen ("libjack.so.0", RTLD_LAZY);
|
||||
if (juce_libjackHandle == nullptr) juce_libjackHandle = dlopen ("libjack.so", RTLD_LAZY);
|
||||
#elif JUCE_MAC
|
||||
if (juce_libjackHandle == nullptr) juce_libjackHandle = dlopen ("libjack.dylib", RTLD_LAZY);
|
||||
#elif JUCE_WINDOWS
|
||||
#if JUCE_64BIT
|
||||
if (juce_libjackHandle == nullptr) juce_libjackHandle = LoadLibraryA ("libjack64.dll");
|
||||
#else
|
||||
if (juce_libjackHandle == nullptr) juce_libjackHandle = LoadLibraryA ("libjack.dll");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (juce_libjackHandle == nullptr) return;
|
||||
|
||||
jack_status_t status = {};
|
||||
|
||||
// open a dummy client
|
||||
if (auto* const client = juce::jack_client_open ("JuceJackDummy", JackNoStartServer, &status))
|
||||
{
|
||||
// scan for output devices
|
||||
for (JackPortIterator i (client, false); i.next();)
|
||||
if (i.getClientName() != (JUCE_JACK_CLIENT_NAME) && ! inputNames.contains (i.getClientName()))
|
||||
inputNames.add (i.getClientName());
|
||||
|
||||
// scan for input devices
|
||||
for (JackPortIterator i (client, true); i.next();)
|
||||
if (i.getClientName() != (JUCE_JACK_CLIENT_NAME) && ! outputNames.contains (i.getClientName()))
|
||||
outputNames.add (i.getClientName());
|
||||
|
||||
juce::jack_client_close (client);
|
||||
}
|
||||
else
|
||||
{
|
||||
JUCE_JACK_LOG_STATUS (status);
|
||||
}
|
||||
}
|
||||
|
||||
StringArray getDeviceNames (bool wantInputNames) const
|
||||
{
|
||||
jassert (hasScanned); // need to call scanForDevices() before doing this
|
||||
return wantInputNames ? inputNames : outputNames;
|
||||
}
|
||||
|
||||
int getDefaultDeviceIndex (bool /* forInput */) const
|
||||
{
|
||||
jassert (hasScanned); // need to call scanForDevices() before doing this
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool hasSeparateInputsAndOutputs() const { return true; }
|
||||
|
||||
int getIndexOfDevice (AudioIODevice* device, bool asInput) const
|
||||
{
|
||||
jassert (hasScanned); // need to call scanForDevices() before doing this
|
||||
|
||||
if (JackAudioIODevice* d = dynamic_cast<JackAudioIODevice*> (device))
|
||||
return asInput ? inputNames.indexOf (d->inputName)
|
||||
: outputNames.indexOf (d->outputName);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
AudioIODevice* createDevice (const String& outputDeviceName,
|
||||
const String& inputDeviceName)
|
||||
{
|
||||
jassert (hasScanned); // need to call scanForDevices() before doing this
|
||||
|
||||
const int inputIndex = inputNames.indexOf (inputDeviceName);
|
||||
const int outputIndex = outputNames.indexOf (outputDeviceName);
|
||||
|
||||
if (inputIndex >= 0 || outputIndex >= 0)
|
||||
return new JackAudioIODevice (inputDeviceName, outputDeviceName,
|
||||
[this] { callDeviceChangeListeners(); });
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
StringArray inputNames, outputNames;
|
||||
bool hasScanned = false;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
# We want to ignore this directory, but we need to enable at least a single
|
||||
# check to avoid an error
|
||||
Checks: -*,darwin-dispatch-once-nonstatic
|
||||
@@ -0,0 +1,125 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
# Set the name of the project and store it in PROJECT_NAME. Also set the following variables:
|
||||
# PROJECT_SOURCE_DIR (usually the root directory where Oboe has been cloned e.g.)
|
||||
# PROJECT_BINARY_DIR (usually the containing project's binary directory,
|
||||
# e.g. ${OBOE_HOME}/samples/RhythmGame/.externalNativeBuild/cmake/ndkExtractorDebug/x86/oboe-bin)
|
||||
project(oboe)
|
||||
|
||||
set (oboe_sources
|
||||
src/aaudio/AAudioLoader.cpp
|
||||
src/aaudio/AudioStreamAAudio.cpp
|
||||
src/common/AdpfWrapper.cpp
|
||||
src/common/AudioStream.cpp
|
||||
src/common/AudioStreamBuilder.cpp
|
||||
src/common/FixedBlockAdapter.cpp
|
||||
src/common/FixedBlockReader.cpp
|
||||
src/common/FixedBlockWriter.cpp
|
||||
src/common/LatencyTuner.cpp
|
||||
src/common/OboeExtensions.cpp
|
||||
src/common/Utilities.cpp
|
||||
src/common/QuirksManager.cpp
|
||||
src/fifo/FifoBuffer.cpp
|
||||
src/fifo/FifoController.cpp
|
||||
src/fifo/FifoControllerBase.cpp
|
||||
src/fifo/FifoControllerIndirect.cpp
|
||||
src/opensles/AudioInputStreamOpenSLES.cpp
|
||||
src/opensles/AudioOutputStreamOpenSLES.cpp
|
||||
src/opensles/AudioStreamBuffered.cpp
|
||||
src/opensles/AudioStreamOpenSLES.cpp
|
||||
src/opensles/EngineOpenSLES.cpp
|
||||
src/opensles/OpenSLESUtilities.cpp
|
||||
src/opensles/OutputMixerOpenSLES.cpp
|
||||
src/common/StabilizedCallback.cpp
|
||||
src/common/Trace.cpp
|
||||
src/common/Version.cpp
|
||||
)
|
||||
|
||||
set (data_conversion_sources
|
||||
src/common/AudioSourceCaller.cpp
|
||||
src/common/DataConversionFlowGraph.cpp
|
||||
src/common/FilterAudioStream.cpp
|
||||
src/common/SourceFloatCaller.cpp
|
||||
src/common/SourceI16Caller.cpp
|
||||
src/common/SourceI24Caller.cpp
|
||||
src/common/SourceI32Caller.cpp
|
||||
src/flowgraph/FlowGraphNode.cpp
|
||||
src/flowgraph/ChannelCountConverter.cpp
|
||||
src/flowgraph/ClipToRange.cpp
|
||||
src/flowgraph/Limiter.cpp
|
||||
src/flowgraph/ManyToMultiConverter.cpp
|
||||
src/flowgraph/MonoBlend.cpp
|
||||
src/flowgraph/MonoToMultiConverter.cpp
|
||||
src/flowgraph/MultiToManyConverter.cpp
|
||||
src/flowgraph/MultiToMonoConverter.cpp
|
||||
src/flowgraph/RampLinear.cpp
|
||||
src/flowgraph/SampleRateConverter.cpp
|
||||
src/flowgraph/SinkFloat.cpp
|
||||
src/flowgraph/SinkI16.cpp
|
||||
src/flowgraph/SinkI24.cpp
|
||||
src/flowgraph/SinkI32.cpp
|
||||
src/flowgraph/SinkI8_24.cpp
|
||||
src/flowgraph/SourceFloat.cpp
|
||||
src/flowgraph/SourceI16.cpp
|
||||
src/flowgraph/SourceI24.cpp
|
||||
src/flowgraph/SourceI32.cpp
|
||||
src/flowgraph/SourceI8_24.cpp
|
||||
src/flowgraph/resampler/IntegerRatio.cpp
|
||||
src/flowgraph/resampler/LinearResampler.cpp
|
||||
src/flowgraph/resampler/MultiChannelResampler.cpp
|
||||
src/flowgraph/resampler/PolyphaseResampler.cpp
|
||||
src/flowgraph/resampler/PolyphaseResamplerMono.cpp
|
||||
src/flowgraph/resampler/PolyphaseResamplerStereo.cpp
|
||||
src/flowgraph/resampler/SincResampler.cpp
|
||||
src/flowgraph/resampler/SincResamplerStereo.cpp
|
||||
)
|
||||
|
||||
# Option to disable data conversion features. Default is OFF (i.e., conversion is ON).
|
||||
option(OBOE_DISABLE_CONVERSION "Exclude data conversion source files and features" OFF)
|
||||
|
||||
if(OBOE_DISABLE_CONVERSION)
|
||||
message(STATUS "Oboe: Data conversion is DISABLED.")
|
||||
else()
|
||||
message(STATUS "Oboe: Data conversion is ENABLED.")
|
||||
list(APPEND oboe_sources ${data_conversion_sources})
|
||||
endif()
|
||||
|
||||
add_library(oboe ${oboe_sources})
|
||||
|
||||
# Specify directories which the compiler should look for headers
|
||||
target_include_directories(oboe
|
||||
PRIVATE src
|
||||
PUBLIC include)
|
||||
|
||||
# Compile Flags:
|
||||
# Enable -Werror when building debug config
|
||||
# Enable -Ofast
|
||||
target_compile_options(oboe
|
||||
PRIVATE
|
||||
-std=c++17
|
||||
-Wall
|
||||
-Wextra-semi
|
||||
-Wshadow
|
||||
-Wshadow-field
|
||||
"$<$<CONFIG:RELEASE>:-Ofast>"
|
||||
"$<$<CONFIG:DEBUG>:-O3>"
|
||||
"$<$<CONFIG:DEBUG>:-Werror>")
|
||||
|
||||
target_compile_definitions(oboe PRIVATE $<$<BOOL:${OBOE_DISABLE_CONVERSION}>:DISABLE_CONVERSION=1>)
|
||||
|
||||
# Enable logging of D,V for debug builds
|
||||
target_compile_definitions(oboe PUBLIC $<$<CONFIG:DEBUG>:OBOE_ENABLE_LOGGING=1>)
|
||||
|
||||
option(OBOE_DO_NOT_DEFINE_OPENSL_ES_CONSTANTS "Do not define OpenSLES constants" OFF)
|
||||
target_compile_definitions(oboe PRIVATE $<$<BOOL:${OBOE_DO_NOT_DEFINE_OPENSL_ES_CONSTANTS}>:DO_NOT_DEFINE_OPENSL_ES_CONSTANTS=1>)
|
||||
|
||||
target_link_libraries(oboe PRIVATE log OpenSLES)
|
||||
target_link_options(oboe PRIVATE "-Wl,-z,max-page-size=16384")
|
||||
|
||||
# When installing oboe put the libraries in the lib/<ABI> folder e.g. lib/arm64-v8a
|
||||
install(TARGETS oboe
|
||||
LIBRARY DESTINATION lib/${ANDROID_ABI}
|
||||
ARCHIVE DESTINATION lib/${ANDROID_ABI})
|
||||
|
||||
# Also install the headers
|
||||
install(DIRECTORY include/oboe DESTINATION include)
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,10 @@
|
||||
The files in this directory are reproduced from the official Oboe repository, which can be found at
|
||||
github.com/google/oboe.
|
||||
|
||||
These files are from tag 1.9.0 (03242e9ef9495e418e6ae83954d239dc9193ec5c).
|
||||
|
||||
We've included only those parts of the original repository which are required to build the Oboe
|
||||
library. Documentation, samples, tests, and other non-library items have been omitted.
|
||||
|
||||
Files in this directory and below are licensed under the terms of the license in the LICENSE file
|
||||
which you can find in the same directory as this readme.
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_AUDIO_CLOCK_H
|
||||
#define OBOE_AUDIO_CLOCK_H
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <ctime>
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class AudioClock {
|
||||
public:
|
||||
static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC) {
|
||||
struct timespec time;
|
||||
int result = clock_gettime(clockId, &time);
|
||||
if (result < 0) {
|
||||
return result;
|
||||
}
|
||||
return (time.tv_sec * kNanosPerSecond) + time.tv_nsec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep until the specified time.
|
||||
*
|
||||
* @param nanoTime time to wake up
|
||||
* @param clockId CLOCK_MONOTONIC is default
|
||||
* @return 0 or a negative error, eg. -EINTR
|
||||
*/
|
||||
|
||||
static int sleepUntilNanoTime(int64_t nanoTime, clockid_t clockId = CLOCK_MONOTONIC) {
|
||||
struct timespec time;
|
||||
time.tv_sec = nanoTime / kNanosPerSecond;
|
||||
time.tv_nsec = nanoTime - (time.tv_sec * kNanosPerSecond);
|
||||
return 0 - clock_nanosleep(clockId, TIMER_ABSTIME, &time, NULL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep for the specified number of nanoseconds in real-time.
|
||||
* Return immediately with 0 if a negative nanoseconds is specified.
|
||||
*
|
||||
* @param nanoseconds time to sleep
|
||||
* @param clockId CLOCK_REALTIME is default
|
||||
* @return 0 or a negative error, eg. -EINTR
|
||||
*/
|
||||
|
||||
static int sleepForNanos(int64_t nanoseconds, clockid_t clockId = CLOCK_REALTIME) {
|
||||
if (nanoseconds > 0) {
|
||||
struct timespec time;
|
||||
time.tv_sec = nanoseconds / kNanosPerSecond;
|
||||
time.tv_nsec = nanoseconds - (time.tv_sec * kNanosPerSecond);
|
||||
return 0 - clock_nanosleep(clockId, 0, &time, NULL);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_AUDIO_CLOCK_H
|
||||
+958
@@ -0,0 +1,958 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STREAM_H_
|
||||
#define OBOE_STREAM_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <mutex>
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/ResultWithValue.h"
|
||||
#include "oboe/AudioStreamBuilder.h"
|
||||
#include "oboe/AudioStreamBase.h"
|
||||
#include "oboe/Utilities.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* The default number of nanoseconds to wait for when performing state change operations on the
|
||||
* stream, such as `start` and `stop`.
|
||||
*
|
||||
* @see oboe::AudioStream::start
|
||||
*/
|
||||
constexpr int64_t kDefaultTimeoutNanos = (2000 * kNanosPerMillisecond);
|
||||
|
||||
/**
|
||||
* Base class for Oboe C++ audio stream.
|
||||
*/
|
||||
class AudioStream : public AudioStreamBase {
|
||||
friend class AudioStreamBuilder; // allow access to setWeakThis() and lockWeakThis()
|
||||
public:
|
||||
|
||||
AudioStream() {}
|
||||
|
||||
/**
|
||||
* Construct an `AudioStream` using the given `AudioStreamBuilder`
|
||||
*
|
||||
* @param builder containing all the stream's attributes
|
||||
*/
|
||||
explicit AudioStream(const AudioStreamBuilder &builder);
|
||||
|
||||
virtual ~AudioStream();
|
||||
|
||||
/**
|
||||
* Open a stream based on the current settings.
|
||||
*
|
||||
* Note that we do not recommend re-opening a stream that has been closed.
|
||||
* TODO Should we prevent re-opening?
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
virtual Result open() {
|
||||
return Result::OK; // Called by subclasses. Might do more in the future.
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the audio resources associated with a stream created by AAudioStreamBuilder_openStream().
|
||||
*
|
||||
* AAudioStream_close() should be called at some point after calling this function.
|
||||
*
|
||||
* After this call, the stream will be in AAUDIO_STREAM_STATE_CLOSING
|
||||
*
|
||||
* This function is useful if you want to release the audio resources immediately, but still allow
|
||||
* queries to the stream to occur from other threads. This often happens if you are monitoring
|
||||
* stream progress from a UI thread.
|
||||
*
|
||||
* NOTE: This function is only fully implemented for MMAP streams, which are low latency streams
|
||||
* supported by some devices. On other "Legacy" streams some audio resources will still be in use
|
||||
* and some callbacks may still be in process after this call.
|
||||
*
|
||||
* Available in AAudio since API level 30. Returns Result::ErrorUnimplemented otherwise.
|
||||
*
|
||||
* * @return either Result::OK or an error.
|
||||
*/
|
||||
virtual Result release() {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the stream and deallocate any resources from the open() call.
|
||||
*/
|
||||
virtual Result close();
|
||||
|
||||
/**
|
||||
* Start the stream. This will block until the stream has been started, an error occurs
|
||||
* or `timeoutNanoseconds` has been reached.
|
||||
*/
|
||||
virtual Result start(int64_t timeoutNanoseconds = kDefaultTimeoutNanos);
|
||||
|
||||
/**
|
||||
* Pause the stream. This will block until the stream has been paused, an error occurs
|
||||
* or `timeoutNanoseconds` has been reached.
|
||||
*/
|
||||
virtual Result pause(int64_t timeoutNanoseconds = kDefaultTimeoutNanos);
|
||||
|
||||
/**
|
||||
* Flush the stream. This will block until the stream has been flushed, an error occurs
|
||||
* or `timeoutNanoseconds` has been reached.
|
||||
*/
|
||||
virtual Result flush(int64_t timeoutNanoseconds = kDefaultTimeoutNanos);
|
||||
|
||||
/**
|
||||
* Stop the stream. This will block until the stream has been stopped, an error occurs
|
||||
* or `timeoutNanoseconds` has been reached.
|
||||
*/
|
||||
virtual Result stop(int64_t timeoutNanoseconds = kDefaultTimeoutNanos);
|
||||
|
||||
/* Asynchronous requests.
|
||||
* Use waitForStateChange() if you need to wait for completion.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Start the stream asynchronously. Returns immediately (does not block). Equivalent to calling
|
||||
* `start(0)`.
|
||||
*/
|
||||
virtual Result requestStart() = 0;
|
||||
|
||||
/**
|
||||
* Pause the stream asynchronously. Returns immediately (does not block). Equivalent to calling
|
||||
* `pause(0)`.
|
||||
*/
|
||||
virtual Result requestPause() = 0;
|
||||
|
||||
/**
|
||||
* Flush the stream asynchronously. Returns immediately (does not block). Equivalent to calling
|
||||
* `flush(0)`.
|
||||
*/
|
||||
virtual Result requestFlush() = 0;
|
||||
|
||||
/**
|
||||
* Stop the stream asynchronously. Returns immediately (does not block). Equivalent to calling
|
||||
* `stop(0)`.
|
||||
*/
|
||||
virtual Result requestStop() = 0;
|
||||
|
||||
/**
|
||||
* Query the current state, eg. StreamState::Pausing
|
||||
*
|
||||
* @return state or a negative error.
|
||||
*/
|
||||
virtual StreamState getState() = 0;
|
||||
|
||||
/**
|
||||
* Wait until the stream's current state no longer matches the input state.
|
||||
* The input state is passed to avoid race conditions caused by the state
|
||||
* changing between calls.
|
||||
*
|
||||
* Note that generally applications do not need to call this. It is considered
|
||||
* an advanced technique and is mostly used for testing.
|
||||
*
|
||||
* <pre><code>
|
||||
* int64_t timeoutNanos = 500 * kNanosPerMillisecond; // arbitrary 1/2 second
|
||||
* StreamState currentState = stream->getState();
|
||||
* StreamState nextState = StreamState::Unknown;
|
||||
* while (result == Result::OK && currentState != StreamState::Paused) {
|
||||
* result = stream->waitForStateChange(
|
||||
* currentState, &nextState, timeoutNanos);
|
||||
* currentState = nextState;
|
||||
* }
|
||||
* </code></pre>
|
||||
*
|
||||
* If the state does not change within the timeout period then it will
|
||||
* return ErrorTimeout. This is true even if timeoutNanoseconds is zero.
|
||||
*
|
||||
* @param inputState The state we want to change away from.
|
||||
* @param nextState Pointer to a variable that will be set to the new state.
|
||||
* @param timeoutNanoseconds The maximum time to wait in nanoseconds.
|
||||
* @return Result::OK or a Result::Error.
|
||||
*/
|
||||
virtual Result waitForStateChange(StreamState inputState,
|
||||
StreamState *nextState,
|
||||
int64_t timeoutNanoseconds) = 0;
|
||||
|
||||
/**
|
||||
* This can be used to adjust the latency of the buffer by changing
|
||||
* the threshold where blocking will occur.
|
||||
* By combining this with getXRunCount(), the latency can be tuned
|
||||
* at run-time for each device.
|
||||
*
|
||||
* This cannot be set higher than getBufferCapacity().
|
||||
*
|
||||
* This should only be used with Output streams. It will
|
||||
* be ignored for Input streams because they are generally kept as empty as possible.
|
||||
*
|
||||
* For OpenSL ES, this method only has an effect on output stream that do NOT
|
||||
* use a callback. The blocking writes goes into a buffer in Oboe and the size of that
|
||||
* buffer is controlled by this method.
|
||||
*
|
||||
* @param requestedFrames requested number of frames that can be filled without blocking
|
||||
* @return the resulting buffer size in frames (obtained using value()) or an error (obtained
|
||||
* using error())
|
||||
*/
|
||||
virtual ResultWithValue<int32_t> setBufferSizeInFrames(int32_t /* requestedFrames */) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* An XRun is an Underrun or an Overrun.
|
||||
* During playing, an underrun will occur if the stream is not written in time
|
||||
* and the system runs out of valid data.
|
||||
* During recording, an overrun will occur if the stream is not read in time
|
||||
* and there is no place to put the incoming data so it is discarded.
|
||||
*
|
||||
* An underrun or overrun can cause an audible "pop" or "glitch".
|
||||
*
|
||||
* @return a result which is either Result::OK with the xRun count as the value, or a
|
||||
* Result::Error* code
|
||||
*/
|
||||
virtual ResultWithValue<int32_t> getXRunCount() {
|
||||
return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if XRun counts are supported on the stream
|
||||
*/
|
||||
virtual bool isXRunCountSupported() const = 0;
|
||||
|
||||
/**
|
||||
* Query the number of frames that are read or written by the endpoint at one time.
|
||||
*
|
||||
* @return burst size
|
||||
*/
|
||||
int32_t getFramesPerBurst() const {
|
||||
return mFramesPerBurst;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of bytes in each audio frame. This is calculated using the channel count
|
||||
* and the sample format. For example, a 2 channel floating point stream will have
|
||||
* 2 * 4 = 8 bytes per frame.
|
||||
*
|
||||
* Note for compressed formats, bytes per frames is treated as 1 by convention.
|
||||
*
|
||||
* @return number of bytes in each audio frame.
|
||||
*/
|
||||
int32_t getBytesPerFrame() const {
|
||||
return isCompressedFormat(mFormat) ? 1 : mChannelCount * getBytesPerSample(); }
|
||||
|
||||
/**
|
||||
* Get the number of bytes per sample. This is calculated using the sample format. For example,
|
||||
* a stream using 16-bit integer samples will have 2 bytes per sample.
|
||||
*
|
||||
* Note for compressed formats, they may not have a fixed bytes per sample. In that case,
|
||||
* this method will return 0 for compressed format.
|
||||
*
|
||||
* @return the number of bytes per sample.
|
||||
*/
|
||||
int32_t getBytesPerSample() const;
|
||||
|
||||
/**
|
||||
* The number of audio frames written into the stream.
|
||||
* This monotonic counter will never get reset.
|
||||
*
|
||||
* @return the number of frames written so far
|
||||
*/
|
||||
virtual int64_t getFramesWritten();
|
||||
|
||||
/**
|
||||
* The number of audio frames read from the stream.
|
||||
* This monotonic counter will never get reset.
|
||||
*
|
||||
* @return the number of frames read so far
|
||||
*/
|
||||
virtual int64_t getFramesRead();
|
||||
|
||||
/**
|
||||
* Calculate the latency of a stream based on getTimestamp().
|
||||
*
|
||||
* Output latency is the time it takes for a given frame to travel from the
|
||||
* app to some type of digital-to-analog converter. If the DAC is external, for example
|
||||
* in a USB interface or a TV connected by HDMI, then there may be additional latency
|
||||
* that the Android device is unaware of.
|
||||
*
|
||||
* Input latency is the time it takes to a given frame to travel from an analog-to-digital
|
||||
* converter (ADC) to the app.
|
||||
*
|
||||
* Note that the latency of an OUTPUT stream will increase abruptly when you write data to it
|
||||
* and then decrease slowly over time as the data is consumed.
|
||||
*
|
||||
* The latency of an INPUT stream will decrease abruptly when you read data from it
|
||||
* and then increase slowly over time as more data arrives.
|
||||
*
|
||||
* The latency of an OUTPUT stream is generally higher than the INPUT latency
|
||||
* because an app generally tries to keep the OUTPUT buffer full and the INPUT buffer empty.
|
||||
*
|
||||
* Note that due to issues in Android before R, we recommend NOT calling
|
||||
* this method from a data callback. See this tech note for more details.
|
||||
* https://github.com/google/oboe/wiki/TechNote_ReleaseBuffer
|
||||
*
|
||||
* @return a ResultWithValue which has a result of Result::OK and a value containing the latency
|
||||
* in milliseconds, or a result of Result::Error*.
|
||||
*/
|
||||
virtual ResultWithValue<double> calculateLatencyMillis() {
|
||||
return ResultWithValue<double>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the estimated time that the frame at `framePosition` entered or left the audio processing
|
||||
* pipeline.
|
||||
*
|
||||
* This can be used to coordinate events and interactions with the external environment, and to
|
||||
* estimate the latency of an audio stream. An example of usage can be found in the hello-oboe
|
||||
* sample (search for "calculateCurrentOutputLatencyMillis").
|
||||
*
|
||||
* The time is based on the implementation's best effort, using whatever knowledge is available
|
||||
* to the system, but cannot account for any delay unknown to the implementation.
|
||||
*
|
||||
* Note that due to issues in Android before R, we recommend NOT calling
|
||||
* this method from a data callback. See this tech note for more details.
|
||||
* https://github.com/google/oboe/wiki/TechNote_ReleaseBuffer
|
||||
*
|
||||
* @deprecated since 1.0, use AudioStream::getTimestamp(clockid_t clockId) instead, which
|
||||
* returns ResultWithValue
|
||||
* @param clockId the type of clock to use e.g. CLOCK_MONOTONIC
|
||||
* @param framePosition the frame number to query
|
||||
* @param timeNanoseconds an output parameter which will contain the presentation timestamp
|
||||
*/
|
||||
virtual Result getTimestamp(clockid_t /* clockId */,
|
||||
int64_t* /* framePosition */,
|
||||
int64_t* /* timeNanoseconds */) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the estimated time that the frame at `framePosition` entered or left the audio processing
|
||||
* pipeline.
|
||||
*
|
||||
* This can be used to coordinate events and interactions with the external environment, and to
|
||||
* estimate the latency of an audio stream. An example of usage can be found in the hello-oboe
|
||||
* sample (search for "calculateCurrentOutputLatencyMillis").
|
||||
*
|
||||
* The time is based on the implementation's best effort, using whatever knowledge is available
|
||||
* to the system, but cannot account for any delay unknown to the implementation.
|
||||
*
|
||||
* Note that due to issues in Android before R, we recommend NOT calling
|
||||
* this method from a data callback. See this tech note for more details.
|
||||
* https://github.com/google/oboe/wiki/TechNote_ReleaseBuffer
|
||||
*
|
||||
* See
|
||||
* @param clockId the type of clock to use e.g. CLOCK_MONOTONIC
|
||||
* @return a FrameTimestamp containing the position and time at which a particular audio frame
|
||||
* entered or left the audio processing pipeline, or an error if the operation failed.
|
||||
*/
|
||||
virtual ResultWithValue<FrameTimestamp> getTimestamp(clockid_t /* clockId */);
|
||||
|
||||
// ============== I/O ===========================
|
||||
/**
|
||||
* Write data from the supplied buffer into the stream. This method will block until the write
|
||||
* is complete or it runs out of time.
|
||||
*
|
||||
* If `timeoutNanoseconds` is zero then this call will not wait.
|
||||
*
|
||||
* @param buffer The address of the first sample.
|
||||
* @param numFrames Number of frames to write. Only complete frames will be written.
|
||||
* @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
|
||||
* @return a ResultWithValue which has a result of Result::OK and a value containing the number
|
||||
* of frames actually written, or result of Result::Error*.
|
||||
*/
|
||||
virtual ResultWithValue<int32_t> write(const void* /* buffer */,
|
||||
int32_t /* numFrames */,
|
||||
int64_t /* timeoutNanoseconds */ ) {
|
||||
return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data into the supplied buffer from the stream. This method will block until the read
|
||||
* is complete or it runs out of time.
|
||||
*
|
||||
* If `timeoutNanoseconds` is zero then this call will not wait.
|
||||
*
|
||||
* @param buffer The address of the first sample.
|
||||
* @param numFrames Number of frames to read. Only complete frames will be read.
|
||||
* @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
|
||||
* @return a ResultWithValue which has a result of Result::OK and a value containing the number
|
||||
* of frames actually read, or result of Result::Error*.
|
||||
*/
|
||||
virtual ResultWithValue<int32_t> read(void* /* buffer */,
|
||||
int32_t /* numFrames */,
|
||||
int64_t /* timeoutNanoseconds */) {
|
||||
return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying audio API which the stream uses.
|
||||
*
|
||||
* @return the API that this stream uses.
|
||||
*/
|
||||
virtual AudioApi getAudioApi() const = 0;
|
||||
|
||||
/**
|
||||
* Returns true if the underlying audio API is AAudio.
|
||||
*
|
||||
* @return true if this stream is implemented using the AAudio API.
|
||||
*/
|
||||
bool usesAAudio() const {
|
||||
return getAudioApi() == AudioApi::AAudio;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only for debugging. Do not use in production.
|
||||
* If you need to call this method something is wrong.
|
||||
* If you think you need it for production then please let us know
|
||||
* so we can modify Oboe so that you don't need this.
|
||||
*
|
||||
* @return nullptr or a pointer to a stream from the system API
|
||||
*/
|
||||
virtual void *getUnderlyingStream() const {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update mFramesWritten.
|
||||
* For internal use only.
|
||||
*/
|
||||
virtual void updateFramesWritten() = 0;
|
||||
|
||||
/**
|
||||
* Update mFramesRead.
|
||||
* For internal use only.
|
||||
*/
|
||||
virtual void updateFramesRead() = 0;
|
||||
|
||||
/*
|
||||
* Swap old callback for new callback.
|
||||
* This not atomic.
|
||||
* This should only be used internally.
|
||||
* @param dataCallback
|
||||
* @return previous dataCallback
|
||||
*/
|
||||
AudioStreamDataCallback *swapDataCallback(AudioStreamDataCallback *dataCallback) {
|
||||
AudioStreamDataCallback *previousCallback = mDataCallback;
|
||||
mDataCallback = dataCallback;
|
||||
return previousCallback;
|
||||
}
|
||||
|
||||
/*
|
||||
* Swap old partial data callback for new callback.
|
||||
* This not atomic.
|
||||
* This should only be used internally.
|
||||
* @param dataCallback
|
||||
* @return previous dataCallback
|
||||
*/
|
||||
AudioStreamPartialDataCallback *swapPartialDataCallback(
|
||||
AudioStreamPartialDataCallback *partialDataCallback) {
|
||||
AudioStreamPartialDataCallback *previousPartialCallback = mPartialDataCallback;
|
||||
mPartialDataCallback = partialDataCallback;
|
||||
return previousPartialCallback;
|
||||
}
|
||||
|
||||
/*
|
||||
* Swap old callback for new callback.
|
||||
* This not atomic.
|
||||
* This should only be used internally.
|
||||
* @param errorCallback
|
||||
* @return previous errorCallback
|
||||
*/
|
||||
AudioStreamErrorCallback *swapErrorCallback(AudioStreamErrorCallback *errorCallback) {
|
||||
AudioStreamErrorCallback *previousCallback = mErrorCallback;
|
||||
mErrorCallback = errorCallback;
|
||||
return previousCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of frames of data currently in the buffer
|
||||
*/
|
||||
ResultWithValue<int32_t> getAvailableFrames();
|
||||
|
||||
/**
|
||||
* Wait until the stream has a minimum amount of data available in its buffer.
|
||||
* This can be used with an EXCLUSIVE MMAP input stream to avoid reading data too close to
|
||||
* the DSP write position, which may cause glitches.
|
||||
*
|
||||
* Starting with Oboe 1.7.1, the numFrames will be clipped internally against the
|
||||
* BufferCapacity minus BurstSize. This is to prevent trying to wait for more frames
|
||||
* than could possibly be available. In this case, the return value may be less than numFrames.
|
||||
* Note that there may still be glitching if numFrames is too high.
|
||||
*
|
||||
* @param numFrames requested minimum frames available
|
||||
* @param timeoutNanoseconds
|
||||
* @return number of frames available, ErrorTimeout
|
||||
*/
|
||||
ResultWithValue<int32_t> waitForAvailableFrames(int32_t numFrames,
|
||||
int64_t timeoutNanoseconds);
|
||||
|
||||
/**
|
||||
* @return last result passed from an error callback
|
||||
*/
|
||||
virtual oboe::Result getLastErrorCallbackResult() const {
|
||||
return mErrorCallbackResult;
|
||||
}
|
||||
|
||||
|
||||
int32_t getDelayBeforeCloseMillis() const {
|
||||
return mDelayBeforeCloseMillis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the time to sleep before closing the internal stream.
|
||||
*
|
||||
* Sometimes a callback can occur shortly after a stream has been stopped and
|
||||
* even after a close! If the stream has been closed then the callback
|
||||
* might access memory that has been freed, which could cause a crash.
|
||||
* This seems to be more likely in Android P or earlier.
|
||||
* But it can also occur in later versions. By sleeping, we give time for
|
||||
* the callback threads to finish.
|
||||
*
|
||||
* Note that this only has an effect when OboeGlobals::areWorkaroundsEnabled() is true.
|
||||
*
|
||||
* @param delayBeforeCloseMillis time to sleep before close.
|
||||
*/
|
||||
void setDelayBeforeCloseMillis(int32_t delayBeforeCloseMillis) {
|
||||
mDelayBeforeCloseMillis = delayBeforeCloseMillis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable a device specific CPU performance hint.
|
||||
* Runtime benchmarks such as the callback duration may be used to
|
||||
* speed up the CPU and improve real-time performance.
|
||||
*
|
||||
* Note that this feature is device specific and may not be implemented.
|
||||
* Also the benefits may vary by device.
|
||||
*
|
||||
* The flag will be checked in the Oboe data callback. If it transitions from false to true
|
||||
* then the PerformanceHint feature will be started.
|
||||
* This only needs to be called once for each stream.
|
||||
*
|
||||
* You may want to enable this if you have a dynamically changing workload
|
||||
* and you notice that you are getting under-runs and glitches when your workload increases.
|
||||
* This might happen, for example, if you suddenly go from playing one note to
|
||||
* ten notes on a synthesizer.
|
||||
*
|
||||
* Try the "CPU Load" test in OboeTester if you would like to experiment with this interactively.
|
||||
*
|
||||
* On some devices, this may be implemented using the "ADPF" library.
|
||||
*
|
||||
* @param enabled true if you would like a performance boost, default is false
|
||||
*/
|
||||
void setPerformanceHintEnabled(bool enabled) {
|
||||
mPerformanceHintEnabled = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* This only tells you if the feature has been requested.
|
||||
* It does not tell you if the PerformanceHint feature is implemented or active on the device.
|
||||
*
|
||||
* @return true if set using setPerformanceHintEnabled().
|
||||
*/
|
||||
bool isPerformanceHintEnabled() {
|
||||
return mPerformanceHintEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this to give the performance manager more information about your workload.
|
||||
* You can call this at the beginning of the callback when you figure
|
||||
* out what your workload will be.
|
||||
*
|
||||
* Call this if (1) you have called setPerformanceHintEnabled(true), and
|
||||
* (2) you have a varying workload, and
|
||||
* (3) you hear glitches when your workload suddenly increases.
|
||||
*
|
||||
* This might happen when you go from a single note to a big chord on a synthesizer.
|
||||
*
|
||||
* The workload can be in your own units. If you are synthesizing music
|
||||
* then the workload could be the number of active voices.
|
||||
* If your app is a game then it could be the number of sound effects.
|
||||
* The units are arbitrary. They just have to be proportional to
|
||||
* the estimated computational load. For example, if some of your voices take 20%
|
||||
* more computation than a basic voice then assign 6 units to the complex voice
|
||||
* and 5 units to the basic voice.
|
||||
*
|
||||
* The performance hint code can use this as an advance warning that the callback duration
|
||||
* will probably increase. Rather than wait for the long duration and possibly under-run,
|
||||
* we can boost the CPU immediately before we start doing the calculations.
|
||||
*
|
||||
* @param appWorkload workload in application units, such as number of voices
|
||||
* @return OK or an error such as ErrorInvalidState if the PerformanceHint was not enabled.
|
||||
*/
|
||||
virtual oboe::Result reportWorkload([[maybe_unused]] int32_t appWorkload) {
|
||||
return oboe::Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming increase in the workload of an audio callback
|
||||
* bound to this session. The user can specify whether the increase is expected to be
|
||||
* on the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* rate limiter.
|
||||
*
|
||||
* @param cpu Indicates if the workload increase is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload increase is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorInvalidState if the PerformanceHint was not enabled.
|
||||
* Result::ErrorClosed if AdpfWrapper::open() was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
virtual oboe::Result notifyWorkloadIncrease([[maybe_unused]] bool cpu,
|
||||
[[maybe_unused]] bool gpu,
|
||||
[[maybe_unused]] const char* debugName) {
|
||||
return oboe::Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming reset in the workload of an audio callback
|
||||
* bound to this session, or the imminent start of a new workload. The user can specify
|
||||
* whether the reset is expected to affect the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* this load tracking.
|
||||
*
|
||||
* @param cpu Indicates if the workload reset is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload reset is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorInvalidState if the PerformanceHint was not enabled.
|
||||
* Result::ErrorClosed if AdpfWrapper::open() was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
virtual oboe::Result notifyWorkloadReset([[maybe_unused]] bool cpu,
|
||||
[[maybe_unused]] bool gpu,
|
||||
[[maybe_unused]] const char* debugName) {
|
||||
return oboe::Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming one-off expensive frame for an audio callback
|
||||
* bound to this session. This frame will be treated as not representative of the workload as a
|
||||
* whole, and it will be discarded the purposes of load tracking. The user can specify
|
||||
* whether the workload spike is expected to be on the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* rate limiter.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @param cpu Indicates if the workload spike is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload spike is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorInvalidState if the PerformanceHint was not enabled.
|
||||
* Result::ErrorClosed if AdpfWrapper::open() was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
virtual oboe::Result notifyWorkloadSpike([[maybe_unused]] bool cpu,
|
||||
[[maybe_unused]] bool gpu,
|
||||
[[maybe_unused]] const char* debugName) {
|
||||
return oboe::Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
virtual oboe::Result setOffloadDelayPadding([[maybe_unused]] int32_t delayInFrames,
|
||||
[[maybe_unused]] int32_t paddingInFrames) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
virtual ResultWithValue<int32_t> getOffloadDelay() {
|
||||
return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
virtual ResultWithValue<int32_t> getOffloadPadding() {
|
||||
return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
virtual oboe::Result setOffloadEndOfStream() {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all data from given position. If this operation returns successfully, the following
|
||||
* data will be written from the returned position.
|
||||
*
|
||||
* This method will only available when the performance mode is
|
||||
* PerformanceMode::PowerSavingOffloaded.
|
||||
*
|
||||
* The requested position must not be negative or greater than the written frames. The current
|
||||
* written position can be known by querying getFramesWritten().
|
||||
*
|
||||
* When clients request to flush from a certain position, the audio system will return the
|
||||
* actual flushed position based on the requested position, playback latency, etc. The written
|
||||
* position will be updated as the actual flush position. All data after actual flush position
|
||||
* flushed. The client can provide data from actual flush position at next write operation or
|
||||
* data callback request. When the stream is flushed, the stream end will be reset. The client
|
||||
* must not write any data before this function returns. Otherwise, the data will be corrupted.
|
||||
* When the method returns successfully and the stream is active, the client must write data
|
||||
* immediately if little audio data remains. Otherwise, the stream will underrun.
|
||||
*
|
||||
* This was introduced in Android API Level 37.
|
||||
*
|
||||
* @param accuracy the accuracy requirement when flushing. The value must be one of the valid
|
||||
* FlushFromAccuracy value.
|
||||
* @param position the start point in frames to flush the stream.
|
||||
* @return a result which the error code indicates if the stream is successfully flush or not
|
||||
* and value as the successfully flushed position or suggested flushed position.
|
||||
* Result::OK if the stream is successfully flushed. The value is the actual flushed
|
||||
* position.
|
||||
* Result::ErrorUnimplemented if it is not supported by the device. The value is the
|
||||
* requested position.
|
||||
* Result::ErrorIllegalArgument if the stream is not an output offload stream or the
|
||||
* accuracy is not one of valid FlushFromAccuracy values. The value is the requested
|
||||
* position.
|
||||
* Result::ErrorOutOfRange if the provided position is negative or is greater than the
|
||||
* frames written or the stream cannot flush from the requested position and
|
||||
* FlushFromAccuracy::Accurate is requested. The value is suggested flushed position.
|
||||
* Result::ErrorDisconnected if the stream is disconnected. The value is the requested
|
||||
* position.
|
||||
* Result::ErrorClosed if the stream is closed. The value is the requested position.
|
||||
*/
|
||||
virtual ResultWithValue<int64_t> flushFromFrame(
|
||||
FlushFromAccuracy accuracy, int64_t positionInFrames) {
|
||||
return ResultWithValue<int64_t>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set playback parameters for the given stream.
|
||||
*
|
||||
* This was introduced in Android API Level 37.
|
||||
*
|
||||
* @param parameters a pointer of PlaybackParameters where current playback parameters
|
||||
* will be written to on success.
|
||||
* @return Result::OK if the playback parameters are set successfully.
|
||||
* Result::ErrorIllegalArgument if the given stream is not an output stream or
|
||||
* the requested parameters are invalid.
|
||||
* Result::ErrorUnimplemented if the device or the stream doesn't support setting
|
||||
* playback parameters.
|
||||
* Result::ErrorInvalidState if the stream is not initialized successfully.
|
||||
*/
|
||||
virtual oboe::Result setPlaybackParameters(const PlaybackParameters& parameters) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current playback parameters for the given stream.
|
||||
*
|
||||
* This was introduced in Android API Level 37.
|
||||
*
|
||||
* @return a ResultWithValue which has a result of Result::OK and a value containing the
|
||||
* playback parameters, or a result of Result::Error*.
|
||||
*/
|
||||
virtual ResultWithValue<PlaybackParameters> getPlaybackParameters() {
|
||||
return ResultWithValue<PlaybackParameters>(Result::ErrorUnimplemented);
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
/**
|
||||
* This is used to detect more than one error callback from a stream.
|
||||
* These were bugs in some versions of Android that caused multiple error callbacks.
|
||||
* Internal bug b/63087953
|
||||
*
|
||||
* Calling this sets an atomic<bool> true and returns the previous value.
|
||||
*
|
||||
* @return false on first call, true on subsequent calls
|
||||
*/
|
||||
bool wasErrorCallbackCalled() {
|
||||
return mErrorCallbackCalled.exchange(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a transition from one state to another.
|
||||
* @return OK if the endingState was observed, or ErrorUnexpectedState
|
||||
* if any state that was not the startingState or endingState was observed
|
||||
* or ErrorTimeout.
|
||||
*/
|
||||
virtual Result waitForStateTransition(StreamState startingState,
|
||||
StreamState endingState,
|
||||
int64_t timeoutNanoseconds);
|
||||
|
||||
/**
|
||||
* Override this to provide a default for when the application did not specify a callback.
|
||||
*
|
||||
* @param audioData
|
||||
* @param numFrames
|
||||
* @return result
|
||||
*/
|
||||
virtual DataCallbackResult onDefaultCallback(void* /* audioData */, int /* numFrames */) {
|
||||
return DataCallbackResult::Stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override this to provide your own behaviour for the audio callback
|
||||
*
|
||||
* @param audioData container array which audio frames will be written into or read from
|
||||
* @param numFrames number of frames which were read/written
|
||||
* @return the result of the callback: stop or continue
|
||||
*
|
||||
*/
|
||||
virtual DataCallbackResult fireDataCallback(void *audioData, int numFrames);
|
||||
|
||||
/**
|
||||
* Override this to provide your own behaviour for the parital audio callback
|
||||
*
|
||||
* @param audioData container array which audio frames will be written into or read from
|
||||
* @param numFrames number of frames which were read/written
|
||||
* @return the actual processed frames
|
||||
*/
|
||||
virtual int32_t firePartialDataCallback(void* audioData, int numFrames);
|
||||
|
||||
/**
|
||||
* @return true if callbacks may be called
|
||||
*/
|
||||
bool isDataCallbackEnabled() {
|
||||
return mDataCallbackEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* This can be set false internally to prevent callbacks
|
||||
* after DataCallbackResult::Stop has been returned.
|
||||
*/
|
||||
void setDataCallbackEnabled(bool enabled) {
|
||||
mDataCallbackEnabled = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* This should only be called as a stream is being opened.
|
||||
* Otherwise we might override setDelayBeforeCloseMillis().
|
||||
*/
|
||||
void calculateDefaultDelayBeforeCloseMillis();
|
||||
|
||||
/**
|
||||
* Try to avoid a race condition when closing.
|
||||
*/
|
||||
void sleepBeforeClose() {
|
||||
if (mDelayBeforeCloseMillis > 0) {
|
||||
usleep(mDelayBeforeCloseMillis * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This may be called internally at the beginning of a callback.
|
||||
*/
|
||||
virtual void beginPerformanceHintInCallback() {}
|
||||
|
||||
/**
|
||||
* This may be called internally at the end of a callback.
|
||||
* @param numFrames passed to the callback
|
||||
*/
|
||||
virtual void endPerformanceHintInCallback(int32_t /*numFrames*/) {}
|
||||
|
||||
/**
|
||||
* This will be called when the stream is closed just in case performance hints were enabled.
|
||||
*/
|
||||
virtual void closePerformanceHint() {}
|
||||
|
||||
/*
|
||||
* Set a weak_ptr to this stream from the shared_ptr so that we can
|
||||
* later use a shared_ptr in the error callback.
|
||||
*/
|
||||
void setWeakThis(std::shared_ptr<oboe::AudioStream> &sharedStream) {
|
||||
mWeakThis = sharedStream;
|
||||
}
|
||||
|
||||
/*
|
||||
* Make a shared_ptr that will prevent this stream from being deleted.
|
||||
*/
|
||||
std::shared_ptr<oboe::AudioStream> lockWeakThis() {
|
||||
return mWeakThis.lock();
|
||||
}
|
||||
|
||||
std::weak_ptr<AudioStream> mWeakThis; // weak pointer to this object
|
||||
|
||||
/**
|
||||
* Number of frames which have been written into the stream
|
||||
*
|
||||
* This is signed integer to match the counters in AAudio.
|
||||
* At audio rates, the counter will overflow in about six million years.
|
||||
*/
|
||||
std::atomic<int64_t> mFramesWritten{};
|
||||
|
||||
/**
|
||||
* Number of frames which have been read from the stream.
|
||||
*
|
||||
* This is signed integer to match the counters in AAudio.
|
||||
* At audio rates, the counter will overflow in about six million years.
|
||||
*/
|
||||
std::atomic<int64_t> mFramesRead{};
|
||||
|
||||
std::mutex mLock; // for synchronizing start/stop/close
|
||||
|
||||
oboe::Result mErrorCallbackResult = oboe::Result::OK;
|
||||
|
||||
/**
|
||||
* Number of frames which will be copied to/from the audio device in a single read/write
|
||||
* operation
|
||||
*/
|
||||
int32_t mFramesPerBurst = kUnspecified;
|
||||
|
||||
// Time to sleep in order to prevent a race condition with a callback after a close().
|
||||
// Two milliseconds may be enough but 10 msec is even safer.
|
||||
static constexpr int kMinDelayBeforeCloseMillis = 10;
|
||||
static constexpr int kMaxDelayBeforeCloseMillis = 100;
|
||||
int32_t mDelayBeforeCloseMillis = kMinDelayBeforeCloseMillis;
|
||||
|
||||
private:
|
||||
|
||||
// Log the scheduler if it changes.
|
||||
void checkScheduler();
|
||||
int mPreviousScheduler = -1;
|
||||
|
||||
std::atomic<bool> mDataCallbackEnabled{false};
|
||||
std::atomic<bool> mErrorCallbackCalled{false};
|
||||
|
||||
std::atomic<bool> mPerformanceHintEnabled{false}; // set only by app
|
||||
};
|
||||
|
||||
/**
|
||||
* This struct is a stateless functor which closes an AudioStream prior to its deletion.
|
||||
* This means it can be used to safely delete a smart pointer referring to an open stream.
|
||||
*/
|
||||
struct StreamDeleterFunctor {
|
||||
void operator()(AudioStream *audioStream) {
|
||||
if (audioStream) {
|
||||
audioStream->close();
|
||||
}
|
||||
delete audioStream;
|
||||
}
|
||||
};
|
||||
} // namespace oboe
|
||||
|
||||
#endif /* OBOE_STREAM_H_ */
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
/*
|
||||
* Copyright 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STREAM_BASE_H_
|
||||
#define OBOE_STREAM_BASE_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "oboe/AudioStreamCallback.h"
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* Base class containing parameters for audio streams and builders.
|
||||
**/
|
||||
class AudioStreamBase {
|
||||
|
||||
public:
|
||||
|
||||
AudioStreamBase() {}
|
||||
|
||||
virtual ~AudioStreamBase() = default;
|
||||
|
||||
// This class only contains primitives so we can use default constructor and copy methods.
|
||||
|
||||
/**
|
||||
* Default copy constructor
|
||||
*/
|
||||
AudioStreamBase(const AudioStreamBase&) = default;
|
||||
|
||||
/**
|
||||
* Default assignment operator
|
||||
*/
|
||||
AudioStreamBase& operator=(const AudioStreamBase&) = default;
|
||||
|
||||
/**
|
||||
* @return number of channels, for example 2 for stereo, or kUnspecified
|
||||
*/
|
||||
int32_t getChannelCount() const { return mChannelCount; }
|
||||
|
||||
/**
|
||||
* @return Direction::Input or Direction::Output
|
||||
*/
|
||||
Direction getDirection() const { return mDirection; }
|
||||
|
||||
/**
|
||||
* @return sample rate for the stream or kUnspecified
|
||||
*/
|
||||
int32_t getSampleRate() const { return mSampleRate; }
|
||||
|
||||
/**
|
||||
* @deprecated use `getFramesPerDataCallback` instead.
|
||||
*/
|
||||
int32_t getFramesPerCallback() const { return getFramesPerDataCallback(); }
|
||||
|
||||
/**
|
||||
* @return the number of frames in each data callback or kUnspecified.
|
||||
*/
|
||||
int32_t getFramesPerDataCallback() const { return mFramesPerCallback; }
|
||||
|
||||
/**
|
||||
* @return the audio sample format (e.g. Float or I16)
|
||||
*/
|
||||
AudioFormat getFormat() const { return mFormat; }
|
||||
|
||||
/**
|
||||
* Query the maximum number of frames that can be filled without blocking.
|
||||
* If the stream has been closed the last known value will be returned.
|
||||
*
|
||||
* @return buffer size
|
||||
*/
|
||||
virtual int32_t getBufferSizeInFrames() { return mBufferSizeInFrames; }
|
||||
|
||||
/**
|
||||
* @return capacityInFrames or kUnspecified
|
||||
*/
|
||||
virtual int32_t getBufferCapacityInFrames() const { return mBufferCapacityInFrames; }
|
||||
|
||||
/**
|
||||
* @return the sharing mode of the stream.
|
||||
*/
|
||||
SharingMode getSharingMode() const { return mSharingMode; }
|
||||
|
||||
/**
|
||||
* @return the performance mode of the stream.
|
||||
*/
|
||||
PerformanceMode getPerformanceMode() const { return mPerformanceMode; }
|
||||
|
||||
/**
|
||||
* @return the device ID of the stream.
|
||||
*/
|
||||
int32_t getDeviceId() const {
|
||||
return mDeviceIds.empty() ? kUnspecified : mDeviceIds[0];
|
||||
}
|
||||
|
||||
std::vector<int32_t> getDeviceIds() const {
|
||||
return mDeviceIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* For internal use only.
|
||||
* @return the data callback object for this stream, if set.
|
||||
*/
|
||||
AudioStreamDataCallback *getDataCallback() const {
|
||||
return mDataCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* For internal use only.
|
||||
* @return the partial data callback object for this stream, if set.
|
||||
*/
|
||||
AudioStreamPartialDataCallback* getPartialDataCallback() const {
|
||||
return mPartialDataCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* For internal use only.
|
||||
* @return the error callback object for this stream, if set.
|
||||
*/
|
||||
AudioStreamErrorCallback *getErrorCallback() const {
|
||||
return mErrorCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* For internal use only.
|
||||
* @return the presentation callback object for this stream, if set.
|
||||
*/
|
||||
std::shared_ptr<AudioStreamPresentationCallback> getPresentationCallback() const {
|
||||
return mSharedPresentationCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a data callback was set for this stream
|
||||
*/
|
||||
bool isDataCallbackSpecified() const {
|
||||
return mDataCallback != nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a partial data callback was set for this stream
|
||||
*/
|
||||
bool isPartialDataCallbackSpecified() const {
|
||||
return mPartialDataCallback != nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a data callback or a partial data callback was set for this stream
|
||||
*/
|
||||
bool anyDataCallbackSpecified() const {
|
||||
return isDataCallbackSpecified() || isPartialDataCallbackSpecified();
|
||||
}
|
||||
|
||||
/**
|
||||
* Note that if the app does not set an error callback then a
|
||||
* default one may be provided.
|
||||
* @return true if an error callback was set for this stream
|
||||
*/
|
||||
bool isErrorCallbackSpecified() const {
|
||||
return mErrorCallback != nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a presentation callback was set for this stream
|
||||
*/
|
||||
bool isPresentationCallbackSpecified() const {
|
||||
return mSharedPresentationCallback != nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the usage for this stream.
|
||||
*/
|
||||
Usage getUsage() const { return mUsage; }
|
||||
|
||||
/**
|
||||
* @return the stream's content type.
|
||||
*/
|
||||
ContentType getContentType() const { return mContentType; }
|
||||
|
||||
/**
|
||||
* @return the stream's input preset.
|
||||
*/
|
||||
InputPreset getInputPreset() const { return mInputPreset; }
|
||||
|
||||
/**
|
||||
* @return the stream's session ID allocation strategy (None or Allocate).
|
||||
*/
|
||||
SessionId getSessionId() const { return mSessionId; }
|
||||
|
||||
/**
|
||||
* @return whether the content of the stream is spatialized.
|
||||
*/
|
||||
bool isContentSpatialized() const { return mIsContentSpatialized; }
|
||||
|
||||
/**
|
||||
* @return the spatialization behavior for the stream.
|
||||
*/
|
||||
SpatializationBehavior getSpatializationBehavior() const { return mSpatializationBehavior; }
|
||||
|
||||
/**
|
||||
* Return the policy that determines whether the audio may or may not be captured
|
||||
* by other apps or the system.
|
||||
*
|
||||
* See AudioStreamBuilder_setAllowedCapturePolicy().
|
||||
*
|
||||
* Added in API level 29 to AAudio.
|
||||
*
|
||||
* @return the allowed capture policy, for example AllowedCapturePolicy::All
|
||||
*/
|
||||
AllowedCapturePolicy getAllowedCapturePolicy() const { return mAllowedCapturePolicy; }
|
||||
|
||||
/**
|
||||
* Return whether this input stream is marked as privacy sensitive.
|
||||
*
|
||||
* See AudioStreamBuilder_setPrivacySensitiveMode().
|
||||
*
|
||||
* Added in API level 30 to AAudio.
|
||||
*
|
||||
* @return PrivacySensitiveMode::Enabled if privacy sensitive,
|
||||
* PrivacySensitiveMode::Disabled if not privacy sensitive, and
|
||||
* PrivacySensitiveMode::Unspecified if API is not supported.
|
||||
*/
|
||||
PrivacySensitiveMode getPrivacySensitiveMode() const { return mPrivacySensitiveMode; }
|
||||
|
||||
/**
|
||||
* Return the stream's package name
|
||||
*
|
||||
* See AudioStreamBuilder_setPackageName().
|
||||
*
|
||||
* Added in API level 31 to AAudio.
|
||||
*
|
||||
* @return packageName
|
||||
*/
|
||||
std::string getPackageName() const { return mPackageName; }
|
||||
|
||||
/**
|
||||
* Return the stream's attribution tag
|
||||
*
|
||||
* See AudioStreamBuilder_setAttributionTag().
|
||||
*
|
||||
* Added in API level 31 to AAudio.
|
||||
*
|
||||
* @return attributionTag
|
||||
*/
|
||||
std::string getAttributionTag() const { return mAttributionTag; }
|
||||
|
||||
/**
|
||||
* @return true if Oboe can convert channel counts to achieve optimal results.
|
||||
*/
|
||||
bool isChannelConversionAllowed() const {
|
||||
return mChannelConversionAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if Oboe can convert data formats to achieve optimal results.
|
||||
*/
|
||||
bool isFormatConversionAllowed() const {
|
||||
return mFormatConversionAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether and how Oboe can convert sample rates to achieve optimal results.
|
||||
*/
|
||||
SampleRateConversionQuality getSampleRateConversionQuality() const {
|
||||
return mSampleRateConversionQuality;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the stream's channel mask.
|
||||
*/
|
||||
ChannelMask getChannelMask() const {
|
||||
return mChannelMask;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of channels for the hardware, for example 2 for stereo, or kUnspecified.
|
||||
*/
|
||||
int32_t getHardwareChannelCount() const { return mHardwareChannelCount; }
|
||||
|
||||
/**
|
||||
* @return hardware sample rate for the stream or kUnspecified
|
||||
*/
|
||||
int32_t getHardwareSampleRate() const { return mHardwareSampleRate; }
|
||||
|
||||
/**
|
||||
* @return the audio sample format of the hardware (e.g. Float or I16)
|
||||
*/
|
||||
AudioFormat getHardwareFormat() const { return mHardwareFormat; }
|
||||
|
||||
protected:
|
||||
/** The callback which will be fired when new data is ready to be read/written. **/
|
||||
AudioStreamDataCallback *mDataCallback = nullptr;
|
||||
std::shared_ptr<AudioStreamDataCallback> mSharedDataCallback;
|
||||
|
||||
/** The partial data callback which will be fired when new data is ready to be read/written. **/
|
||||
AudioStreamPartialDataCallback *mPartialDataCallback = nullptr;
|
||||
std::shared_ptr<AudioStreamPartialDataCallback> mSharedPartialDataCallback;
|
||||
|
||||
/** The callback which will be fired when an error or a disconnect occurs. **/
|
||||
AudioStreamErrorCallback *mErrorCallback = nullptr;
|
||||
std::shared_ptr<AudioStreamErrorCallback> mSharedErrorCallback;
|
||||
|
||||
std::shared_ptr<AudioStreamPresentationCallback> mSharedPresentationCallback;
|
||||
|
||||
/** Number of audio frames which will be requested in each callback */
|
||||
int32_t mFramesPerCallback = kUnspecified;
|
||||
/** Stream channel count */
|
||||
int32_t mChannelCount = kUnspecified;
|
||||
/** Stream sample rate */
|
||||
int32_t mSampleRate = kUnspecified;
|
||||
/** Stream buffer capacity specified as a number of audio frames */
|
||||
int32_t mBufferCapacityInFrames = kUnspecified;
|
||||
/** Stream buffer size specified as a number of audio frames */
|
||||
int32_t mBufferSizeInFrames = kUnspecified;
|
||||
/** Stream channel mask. Only active on Android 32+ */
|
||||
ChannelMask mChannelMask = ChannelMask::Unspecified;
|
||||
|
||||
/** Stream sharing mode */
|
||||
SharingMode mSharingMode = SharingMode::Shared;
|
||||
/** Format of audio frames */
|
||||
AudioFormat mFormat = AudioFormat::Unspecified;
|
||||
/** Stream direction */
|
||||
Direction mDirection = Direction::Output;
|
||||
/** Stream performance mode */
|
||||
PerformanceMode mPerformanceMode = PerformanceMode::None;
|
||||
|
||||
/** Stream usage. Only active on Android 28+ */
|
||||
Usage mUsage = Usage::Media;
|
||||
/** Stream content type. Only active on Android 28+ */
|
||||
ContentType mContentType = ContentType::Music;
|
||||
/** Stream input preset. Only active on Android 28+
|
||||
* TODO InputPreset::Unspecified should be considered as a possible default alternative.
|
||||
*/
|
||||
InputPreset mInputPreset = InputPreset::VoiceRecognition;
|
||||
/** Stream session ID allocation strategy. Only active on Android 28+ */
|
||||
SessionId mSessionId = SessionId::None;
|
||||
|
||||
/** Allowed Capture Policy. Only active on Android 29+ */
|
||||
AllowedCapturePolicy mAllowedCapturePolicy = AllowedCapturePolicy::Unspecified;
|
||||
|
||||
/** Privacy Sensitive Mode. Only active on Android 30+ */
|
||||
PrivacySensitiveMode mPrivacySensitiveMode = PrivacySensitiveMode::Unspecified;
|
||||
|
||||
/** Control the name of the package creating the stream. Only active on Android 31+ */
|
||||
std::string mPackageName;
|
||||
/** Control the attribution tag of the context creating the stream. Only active on Android 31+ */
|
||||
std::string mAttributionTag;
|
||||
|
||||
/** Whether the content is already spatialized. Only used on Android 32+ */
|
||||
bool mIsContentSpatialized = false;
|
||||
/** Spatialization Behavior. Only active on Android 32+ */
|
||||
SpatializationBehavior mSpatializationBehavior = SpatializationBehavior::Unspecified;
|
||||
|
||||
/** Hardware channel count. Only specified on Android 34+ AAudio streams */
|
||||
int32_t mHardwareChannelCount = kUnspecified;
|
||||
/** Hardware sample rate. Only specified on Android 34+ AAudio streams */
|
||||
int32_t mHardwareSampleRate = kUnspecified;
|
||||
/** Hardware format. Only specified on Android 34+ AAudio streams */
|
||||
AudioFormat mHardwareFormat = AudioFormat::Unspecified;
|
||||
|
||||
// Control whether Oboe can convert channel counts to achieve optimal results.
|
||||
bool mChannelConversionAllowed = false;
|
||||
// Control whether Oboe can convert data formats to achieve optimal results.
|
||||
bool mFormatConversionAllowed = false;
|
||||
// Control whether and how Oboe can convert sample rates to achieve optimal results.
|
||||
SampleRateConversionQuality mSampleRateConversionQuality = SampleRateConversionQuality::Medium;
|
||||
|
||||
std::vector<int32_t> mDeviceIds;
|
||||
|
||||
/** Validate stream parameters that might not be checked in lower layers */
|
||||
virtual Result isValidConfig() {
|
||||
switch (mFormat) {
|
||||
case AudioFormat::Unspecified:
|
||||
case AudioFormat::I16:
|
||||
case AudioFormat::Float:
|
||||
case AudioFormat::I24:
|
||||
case AudioFormat::I32:
|
||||
case AudioFormat::IEC61937:
|
||||
case AudioFormat::MP3:
|
||||
case AudioFormat::AAC_LC:
|
||||
case AudioFormat::AAC_HE_V1:
|
||||
case AudioFormat::AAC_HE_V2:
|
||||
case AudioFormat::AAC_ELD:
|
||||
case AudioFormat::AAC_XHE:
|
||||
case AudioFormat::OPUS:
|
||||
break;
|
||||
|
||||
default:
|
||||
return Result::ErrorInvalidFormat;
|
||||
}
|
||||
|
||||
switch (mSampleRateConversionQuality) {
|
||||
case SampleRateConversionQuality::None:
|
||||
case SampleRateConversionQuality::Fastest:
|
||||
case SampleRateConversionQuality::Low:
|
||||
case SampleRateConversionQuality::Medium:
|
||||
case SampleRateConversionQuality::High:
|
||||
case SampleRateConversionQuality::Best:
|
||||
return Result::OK;
|
||||
default:
|
||||
return Result::ErrorIllegalArgument;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif /* OBOE_STREAM_BASE_H_ */
|
||||
+782
@@ -0,0 +1,782 @@
|
||||
/*
|
||||
* Copyright 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STREAM_BUILDER_H_
|
||||
#define OBOE_STREAM_BUILDER_H_
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/AudioStreamBase.h"
|
||||
#include "oboe/Utilities.h"
|
||||
#include "ResultWithValue.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
// This depends on AudioStream, so we use forward declaration, it will close and delete the stream
|
||||
struct StreamDeleterFunctor;
|
||||
using ManagedStream = std::unique_ptr<AudioStream, StreamDeleterFunctor>;
|
||||
|
||||
/**
|
||||
* Factory class for an audio Stream.
|
||||
*/
|
||||
class AudioStreamBuilder : public AudioStreamBase {
|
||||
public:
|
||||
|
||||
AudioStreamBuilder() : AudioStreamBase() {}
|
||||
|
||||
AudioStreamBuilder(const AudioStreamBase &audioStreamBase): AudioStreamBase(audioStreamBase) {}
|
||||
|
||||
/**
|
||||
* Request a specific number of channels.
|
||||
*
|
||||
* Default is kUnspecified. If the value is unspecified then
|
||||
* the application should query for the actual value after the stream is opened.
|
||||
*
|
||||
* As the channel count here may be different from the corresponding channel count of
|
||||
* provided channel mask used in setChannelMask(). The last called will be respected
|
||||
* if this function and setChannelMask() are called.
|
||||
*/
|
||||
AudioStreamBuilder *setChannelCount(int channelCount) {
|
||||
mChannelCount = channelCount;
|
||||
mChannelMask = ChannelMask::Unspecified;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a specific channel mask.
|
||||
*
|
||||
* Default is kUnspecified. If the value is unspecified then the application
|
||||
* should query for the actual value after the stream is opened.
|
||||
*
|
||||
* As the corresponding channel count of provided channel mask here may be different
|
||||
* from the channel count used in setChannelCount(). The last called will be respected
|
||||
* if this function and setChannelCount() are called.
|
||||
*
|
||||
* As the setChannelMask API is available on Android 32+, this call will only take effects
|
||||
* on Android 32+.
|
||||
*/
|
||||
AudioStreamBuilder *setChannelMask(ChannelMask channelMask) {
|
||||
mChannelMask = channelMask;
|
||||
mChannelCount = getChannelCountFromChannelMask(channelMask);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request the direction for a stream. The default is Direction::Output.
|
||||
*
|
||||
* @param direction Direction::Output or Direction::Input
|
||||
*/
|
||||
AudioStreamBuilder *setDirection(Direction direction) {
|
||||
mDirection = direction;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a specific sample rate in Hz.
|
||||
*
|
||||
* Default is kUnspecified. If the value is unspecified then
|
||||
* the application should query for the actual value after the stream is opened.
|
||||
*
|
||||
* Technically, this should be called the "frame rate" or "frames per second",
|
||||
* because it refers to the number of complete frames transferred per second.
|
||||
* But it is traditionally called "sample rate". Se we use that term.
|
||||
*
|
||||
*/
|
||||
AudioStreamBuilder *setSampleRate(int32_t sampleRate) {
|
||||
mSampleRate = sampleRate;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use `setFramesPerDataCallback` instead.
|
||||
*/
|
||||
AudioStreamBuilder *setFramesPerCallback(int framesPerCallback) {
|
||||
return setFramesPerDataCallback(framesPerCallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a specific number of frames for the data callback.
|
||||
*
|
||||
* Default is kUnspecified. If the value is unspecified then
|
||||
* the actual number may vary from callback to callback.
|
||||
*
|
||||
* If an application can handle a varying number of frames then we recommend
|
||||
* leaving this unspecified. This allow the underlying API to optimize
|
||||
* the callbacks. But if your application is, for example, doing FFTs or other block
|
||||
* oriented operations, then call this function to get the sizes you need.
|
||||
*
|
||||
* Calling setFramesPerDataCallback() does not guarantee anything about timing.
|
||||
* This just collects the data into a the number of frames that your app requires.
|
||||
* We encourage leaving this unspecified in most cases.
|
||||
*
|
||||
* If this number is larger than the burst size, some bursts will not receive a callback.
|
||||
* If this number is smaller than the burst size, there may be multiple callbacks in a single
|
||||
* burst.
|
||||
*
|
||||
* @param framesPerCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setFramesPerDataCallback(int framesPerCallback) {
|
||||
mFramesPerCallback = framesPerCallback;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a sample data format, for example Format::Float.
|
||||
*
|
||||
* Default is Format::Unspecified. If the value is unspecified then
|
||||
* the application should query for the actual value after the stream is opened.
|
||||
*/
|
||||
AudioStreamBuilder *setFormat(AudioFormat format) {
|
||||
mFormat = format;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the requested buffer capacity in frames.
|
||||
* BufferCapacityInFrames is the maximum possible BufferSizeInFrames.
|
||||
*
|
||||
* The final stream capacity may differ. For AAudio it should be at least this big.
|
||||
* For OpenSL ES, it could be smaller.
|
||||
*
|
||||
* Default is kUnspecified.
|
||||
*
|
||||
* @param bufferCapacityInFrames the desired buffer capacity in frames or kUnspecified
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setBufferCapacityInFrames(int32_t bufferCapacityInFrames) {
|
||||
mBufferCapacityInFrames = bufferCapacityInFrames;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the audio API which will be requested when opening the stream. No guarantees that this is
|
||||
* the API which will actually be used. Query the stream itself to find out the API which is
|
||||
* being used.
|
||||
*
|
||||
* If you do not specify the API, then AAudio will be used if isAAudioRecommended()
|
||||
* returns true. Otherwise OpenSL ES will be used.
|
||||
*
|
||||
* @return the requested audio API
|
||||
*/
|
||||
AudioApi getAudioApi() const { return mAudioApi; }
|
||||
|
||||
/**
|
||||
* If you leave this unspecified then Oboe will choose the best API
|
||||
* for the device and SDK version at runtime.
|
||||
*
|
||||
* This should almost always be left unspecified, except for debugging purposes.
|
||||
* Specifying AAudio will force Oboe to use AAudio on 8.0, which is extremely risky.
|
||||
* Specifying OpenSLES should mainly be used to test legacy performance/functionality.
|
||||
*
|
||||
* If the caller requests AAudio and it is supported then AAudio will be used.
|
||||
*
|
||||
* @param audioApi Must be AudioApi::Unspecified, AudioApi::OpenSLES or AudioApi::AAudio.
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setAudioApi(AudioApi audioApi) {
|
||||
mAudioApi = audioApi;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the AAudio API supported on this device?
|
||||
*
|
||||
* AAudio was introduced in the Oreo 8.0 release.
|
||||
*
|
||||
* @return true if supported
|
||||
*/
|
||||
static bool isAAudioSupported();
|
||||
|
||||
/**
|
||||
* Is the AAudio API recommended this device?
|
||||
*
|
||||
* AAudio may be supported but not recommended because of version specific issues.
|
||||
* AAudio is not recommended for Android 8.0 or earlier versions.
|
||||
*
|
||||
* @return true if recommended
|
||||
*/
|
||||
static bool isAAudioRecommended();
|
||||
|
||||
/**
|
||||
* Request a mode for sharing the device.
|
||||
* The requested sharing mode may not be available.
|
||||
* So the application should query for the actual mode after the stream is opened.
|
||||
*
|
||||
* @param sharingMode SharingMode::Shared or SharingMode::Exclusive
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setSharingMode(SharingMode sharingMode) {
|
||||
mSharingMode = sharingMode;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a performance level for the stream.
|
||||
* This will determine the latency, the power consumption, and the level of
|
||||
* protection from glitches.
|
||||
*
|
||||
* @param performanceMode for example, PerformanceMode::LowLatency
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setPerformanceMode(PerformanceMode performanceMode) {
|
||||
mPerformanceMode = performanceMode;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Set the intended use case for an output stream.
|
||||
*
|
||||
* The system will use this information to optimize the behavior of the stream.
|
||||
* This could, for example, affect how volume and focus is handled for the stream.
|
||||
* The usage is ignored for input streams.
|
||||
*
|
||||
* The default, if you do not call this function, is Usage::Media.
|
||||
*
|
||||
* Added in API level 28.
|
||||
*
|
||||
* @param usage the desired usage, eg. Usage::Game
|
||||
*/
|
||||
AudioStreamBuilder *setUsage(Usage usage) {
|
||||
mUsage = usage;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the type of audio data that an output stream will carry.
|
||||
*
|
||||
* The system will use this information to optimize the behavior of the stream.
|
||||
* This could, for example, affect whether a stream is paused when a notification occurs.
|
||||
* The contentType is ignored for input streams.
|
||||
*
|
||||
* The default, if you do not call this function, is ContentType::Music.
|
||||
*
|
||||
* Added in API level 28.
|
||||
*
|
||||
* @param contentType the type of audio data, eg. ContentType::Speech
|
||||
*/
|
||||
AudioStreamBuilder *setContentType(ContentType contentType) {
|
||||
mContentType = contentType;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the input (capture) preset for the stream.
|
||||
*
|
||||
* The system will use this information to optimize the behavior of the stream.
|
||||
* This could, for example, affect which microphones are used and how the
|
||||
* recorded data is processed.
|
||||
*
|
||||
* The default, if you do not call this function, is InputPreset::VoiceRecognition.
|
||||
* That is because VoiceRecognition is the preset with the lowest latency
|
||||
* on many platforms.
|
||||
*
|
||||
* Added in API level 28.
|
||||
*
|
||||
* @param inputPreset the desired configuration for recording
|
||||
*/
|
||||
AudioStreamBuilder *setInputPreset(InputPreset inputPreset) {
|
||||
mInputPreset = inputPreset;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Set the requested session ID.
|
||||
*
|
||||
* The session ID can be used to associate a stream with effects processors.
|
||||
* The effects are controlled using the Android AudioEffect Java API.
|
||||
*
|
||||
* The default, if you do not call this function, is SessionId::None.
|
||||
*
|
||||
* If set to SessionId::Allocate then a session ID will be allocated
|
||||
* when the stream is opened.
|
||||
*
|
||||
* The allocated session ID can be obtained by calling AudioStream::getSessionId()
|
||||
* and then used with this function when opening another stream.
|
||||
* This allows effects to be shared between streams.
|
||||
*
|
||||
* Session IDs from Oboe can be used the Android Java APIs and vice versa.
|
||||
* So a session ID from an Oboe stream can be passed to Java
|
||||
* and effects applied using the Java AudioEffect API.
|
||||
*
|
||||
* Allocated session IDs will always be positive and nonzero.
|
||||
*
|
||||
* Added in API level 28.
|
||||
*
|
||||
* @param sessionId an allocated sessionID or SessionId::Allocate
|
||||
*/
|
||||
AudioStreamBuilder *setSessionId(SessionId sessionId) {
|
||||
mSessionId = sessionId;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a stream to a specific audio input/output device given an audio device ID.
|
||||
*
|
||||
* In most cases, the primary device will be the appropriate device to use, and the
|
||||
* deviceId can be left kUnspecified.
|
||||
*
|
||||
* The ID could be obtained from the Java AudioManager.
|
||||
* AudioManager.getDevices() returns an array of AudioDeviceInfo,
|
||||
* which contains a getId() method. That ID can be passed to this function.
|
||||
*
|
||||
* It is possible that you may not get the device that you requested.
|
||||
* So if it is important to you, you should call
|
||||
* stream->getDeviceId() after the stream is opened to
|
||||
* verify the actual ID.
|
||||
*
|
||||
* Note that when using OpenSL ES, this will be ignored and the created
|
||||
* stream will have deviceId kUnspecified.
|
||||
*
|
||||
* @param deviceId device identifier or kUnspecified
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setDeviceId(int32_t deviceId) {
|
||||
mDeviceIds.clear();
|
||||
if (deviceId != kUnspecified) {
|
||||
mDeviceIds.push_back(deviceId);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify whether this stream audio may or may not be captured by other apps or the system.
|
||||
*
|
||||
* The default is AllowedCapturePolicy::Unspecified which maps to AAUDIO_ALLOW_CAPTURE_BY_ALL.
|
||||
*
|
||||
* Note that an application can also set its global policy, in which case the most restrictive
|
||||
* policy is always applied. See android.media.AudioAttributes.setAllowedCapturePolicy.
|
||||
*
|
||||
* Added in API level 29 to AAudio.
|
||||
*
|
||||
* @param inputPreset the desired level of opt-out from being captured.
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setAllowedCapturePolicy(AllowedCapturePolicy allowedCapturePolicy) {
|
||||
mAllowedCapturePolicy = allowedCapturePolicy;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Indicates whether this input stream must be marked as privacy sensitive or not.
|
||||
*
|
||||
* When PrivacySensitiveMode::Enabled, this input stream is privacy sensitive and any
|
||||
* concurrent capture is not permitted.
|
||||
*
|
||||
* This is off (PrivacySensitiveMode::Disabled) by default except when the input preset is
|
||||
* InputPreset::VoiceRecognition or InputPreset::Camcorder
|
||||
*
|
||||
* Always takes precedence over default from input preset when set explicitly.
|
||||
*
|
||||
* Only relevant if the stream direction is Direction::Input and AAudio is used.
|
||||
*
|
||||
* Added in API level 30 to AAudio.
|
||||
*
|
||||
* @param privacySensitive PrivacySensitiveMode::Enabled if capture from this stream must be
|
||||
* marked as privacy sensitive, PrivacySensitiveMode::Disabled if stream should be marked as
|
||||
* not sensitive.
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setPrivacySensitiveMode(PrivacySensitiveMode privacySensitiveMode) {
|
||||
mPrivacySensitiveMode = privacySensitiveMode;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies whether the audio data of this output stream has already been processed for spatialization.
|
||||
*
|
||||
* If the stream has been processed for spatialization, setting this to true will prevent issues such as
|
||||
* double-processing on platforms that will spatialize audio data.
|
||||
*
|
||||
* This is false by default.
|
||||
*
|
||||
* Available since API level 32.
|
||||
*
|
||||
* @param isContentSpatialized whether the content is already spatialized
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setIsContentSpatialized(bool isContentSpatialized) {
|
||||
mIsContentSpatialized = isContentSpatialized;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the behavior affecting whether spatialization will be used.
|
||||
*
|
||||
* The AAudio system will use this information to select whether the stream will go through a
|
||||
* spatializer effect or not when the effect is supported and enabled.
|
||||
*
|
||||
* This is SpatializationBehavior::Never by default.
|
||||
*
|
||||
* Available since API level 32.
|
||||
*
|
||||
* @param spatializationBehavior the desired spatialization behavior
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setSpatializationBehavior(SpatializationBehavior spatializationBehavior) {
|
||||
mSpatializationBehavior = spatializationBehavior;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies an object to handle data related callbacks from the underlying API.
|
||||
*
|
||||
* <strong>Important: See AudioStreamCallback for restrictions on what may be called
|
||||
* from the callback methods.</strong>
|
||||
*
|
||||
* We pass a shared_ptr so that the sharedDataCallback object cannot be deleted
|
||||
* before the stream is deleted.
|
||||
*
|
||||
* If both this method and setPartialDataCallback(std::shared_ptr<AudioStreamPartialDataCallback>)
|
||||
* are called, the data callback from the last called method will be used.
|
||||
*
|
||||
* Note that if the stream is offloaded or compress formats, it is suggested to use
|
||||
* setPartialDataCallback(std::shared_ptr<AudioStreamPartialDataCallback>) when it is available.
|
||||
* The reason is that AudioStreamDataCallback will require apps to process all the provided
|
||||
* data or none of the provided data. This is not suitable for compressed audio data, for
|
||||
* gapless audio playback, or to drain audio to a fixed arbitrary stop point in frames.
|
||||
*
|
||||
* @param sharedDataCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setDataCallback(
|
||||
std::shared_ptr<AudioStreamDataCallback> sharedDataCallback) {
|
||||
// Use this raw pointer in the rest of the code to retain backwards compatibility.
|
||||
mDataCallback = sharedDataCallback.get();
|
||||
// Hold a shared_ptr to protect the raw pointer for the lifetime of the stream.
|
||||
mSharedDataCallback = sharedDataCallback;
|
||||
mSharedPartialDataCallback.reset();
|
||||
mPartialDataCallback = nullptr;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pass a raw pointer to a data callback. This is not recommended because the dataCallback
|
||||
* object might get deleted by the app while it is being used.
|
||||
*
|
||||
* If both this method and setPartialDataCallback(std::shared_ptr<AudioStreamPartialDataCallback>)
|
||||
* are called, the data callback from the last called method will be used.
|
||||
*
|
||||
* Note that if the stream is offloaded or compress formats, it is suggested to use
|
||||
* setPartialDataCallback(std::shared_ptr<AudioStreamPartialDataCallback>) when it is available.
|
||||
* The reason is that AudioStreamDataCallback will require apps to process all the provided
|
||||
* data or none of the provided data. This is not suitable for compressed audio data, for
|
||||
* gapless audio playback, or to drain audio to a fixed arbitrary stop point in frames.
|
||||
*
|
||||
* @deprecated Call setDataCallback(std::shared_ptr<AudioStreamDataCallback>) instead.
|
||||
* @param dataCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setDataCallback(AudioStreamDataCallback *dataCallback) {
|
||||
mDataCallback = dataCallback;
|
||||
mSharedDataCallback = nullptr;
|
||||
mPartialDataCallback = nullptr;
|
||||
mSharedPartialDataCallback.reset();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies an object to handle data related callbacks from the underlying API.
|
||||
*
|
||||
* <strong>Important: See AudioStreamPartialDataCallback for restrictions on what may be called
|
||||
* from the callback methods.</strong>
|
||||
*
|
||||
* We pass a shared_ptr and cache it so that the partial data callback object cannot be deleted
|
||||
* before the stream is deleted.
|
||||
*
|
||||
* If both this method and setDataCallback(AudioStreamDataCallback*) or
|
||||
* setDataCallback(std::shared_ptr<AudioStreamDataCallback>) are called,
|
||||
* the data callback from the last called method will be used.
|
||||
*
|
||||
* Note that partial data callback from aaudio API at API level 37. In that case, when partial
|
||||
* data callback is set on the Android device that is not supporting partial data callback API,
|
||||
* the stream will fail to open.
|
||||
*
|
||||
* Also note that partial data callback is only supported by aaudio API. OpenSLES has been
|
||||
* deprecated for years. When setting parital data callback and using openSLES will result in
|
||||
* failing to open.
|
||||
*
|
||||
* When the stream is in low latency mode, the data buffer is pretty small. In that case, it
|
||||
* may be easier to use AudioStreamDataCallback instead of AudioStreamPartialDataCallback. For
|
||||
* other use cases that use a big buffer, such as offload playback, deep buffer playback, it
|
||||
* will make more sense to use partial data callback. When the stream is offloaded, no data
|
||||
* conversion is allowed. When the stream is a deep buffer stream, the data conversion will be
|
||||
* provided by the Android framework. In that case, partial data callback is currently only
|
||||
* supported without using data conversion from oboe.
|
||||
*
|
||||
* Call OboeExtensions::isPartialDataCallbackSupported() to check if partial data
|
||||
* callback is supported by the device or not.
|
||||
*
|
||||
* @param partialDataCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setPartialDataCallback(
|
||||
const std::shared_ptr<AudioStreamPartialDataCallback>& partialDataCallback) {
|
||||
mSharedDataCallback.reset();
|
||||
mDataCallback = nullptr;
|
||||
mSharedPartialDataCallback = partialDataCallback;
|
||||
mPartialDataCallback = mSharedPartialDataCallback.get();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies an object to handle error related callbacks from the underlying API.
|
||||
* This can occur when a stream is disconnected because a headset is plugged in or unplugged.
|
||||
* It can also occur if the audio service fails or if an exclusive stream is stolen by
|
||||
* another stream.
|
||||
*
|
||||
* Note that error callbacks will only be called when a data callback has been specified
|
||||
* and the stream is started. If you are not using a data callback then the read(), write()
|
||||
* and requestStart() methods will return errors if the stream is disconnected.
|
||||
*
|
||||
* <strong>Important: See AudioStreamCallback for restrictions on what may be called
|
||||
* from the callback methods.</strong>
|
||||
*
|
||||
* <strong>When an error callback occurs, the associated stream must be stopped and closed
|
||||
* in a separate thread.</strong>
|
||||
*
|
||||
* We pass a shared_ptr so that the errorCallback object cannot be deleted before the stream is deleted.
|
||||
* If the stream was created using a shared_ptr then the stream cannot be deleted before the
|
||||
* error callback has finished running.
|
||||
*
|
||||
* @param sharedErrorCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setErrorCallback(std::shared_ptr<AudioStreamErrorCallback> sharedErrorCallback) {
|
||||
// Use this raw pointer in the rest of the code to retain backwards compatibility.
|
||||
mErrorCallback = sharedErrorCallback.get();
|
||||
// Hold a shared_ptr to protect the raw pointer for the lifetime of the stream.
|
||||
mSharedErrorCallback = sharedErrorCallback;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pass a raw pointer to an error callback. This is not recommended because the errorCallback
|
||||
* object might get deleted by the app while it is being used.
|
||||
*
|
||||
* @deprecated Call setErrorCallback(std::shared_ptr<AudioStreamErrorCallback>) instead.
|
||||
* @param errorCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setErrorCallback(AudioStreamErrorCallback *errorCallback) {
|
||||
mErrorCallback = errorCallback;
|
||||
mSharedErrorCallback = nullptr;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies an object to handle data presentation related callbacks from the underlying API.
|
||||
* This can occur when all data queued in the audio system for an offload stream has been
|
||||
* played.
|
||||
*
|
||||
* Note that presentation callbacks will only be called when a data callback has been specified
|
||||
* and the stream is started.
|
||||
*
|
||||
* <strong>Important: See AudioStreamCallback for restrictions on what may be called
|
||||
* from the callback methods.</strong>
|
||||
*
|
||||
* We pass a shared_ptr so that the presentationCallback object cannot be deleted before the
|
||||
* stream is deleted. If the stream was created using a shared_ptr then the stream cannot be
|
||||
* deleted before the presentation callback has finished running.
|
||||
*
|
||||
* @param sharedPresentationCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setPresentationCallback(
|
||||
std::shared_ptr<AudioStreamPresentationCallback> sharedPresentationCallback) {
|
||||
mSharedPresentationCallback = sharedPresentationCallback;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies an object to handle data or error related callbacks from the underlying API.
|
||||
*
|
||||
* This is the equivalent of calling both setDataCallback() and setErrorCallback().
|
||||
*
|
||||
* <strong>Important: See AudioStreamCallback for restrictions on what may be called
|
||||
* from the callback methods.</strong>
|
||||
*
|
||||
* Note that when this is called, partial data callback will be reset.
|
||||
*
|
||||
* @deprecated Call setDataCallback(std::shared_ptr<AudioStreamDataCallback>) and
|
||||
* setErrorCallback(std::shared_ptr<AudioStreamErrorCallback>) instead.
|
||||
* @param streamCallback
|
||||
* @return pointer to the builder so calls can be chained
|
||||
*/
|
||||
AudioStreamBuilder *setCallback(AudioStreamCallback *streamCallback) {
|
||||
// Use the same callback object for both, dual inheritance.
|
||||
mDataCallback = streamCallback;
|
||||
mErrorCallback = streamCallback;
|
||||
mSharedPartialDataCallback.reset();
|
||||
mPartialDataCallback = nullptr;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* If true then Oboe might convert channel counts to achieve optimal results.
|
||||
* On some versions of Android for example, stereo streams could not use a FAST track.
|
||||
* So a mono stream might be used instead and duplicated to two channels.
|
||||
* On some devices, mono streams might be broken, so a stereo stream might be opened
|
||||
* and converted to mono.
|
||||
*
|
||||
* Default is false.
|
||||
*/
|
||||
AudioStreamBuilder *setChannelConversionAllowed(bool allowed) {
|
||||
mChannelConversionAllowed = allowed;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* If true then Oboe might convert data formats to achieve optimal results.
|
||||
* On some versions of Android, for example, a float stream could not get a
|
||||
* low latency data path. So an I16 stream might be opened and converted to float.
|
||||
*
|
||||
* Default is false.
|
||||
*/
|
||||
AudioStreamBuilder *setFormatConversionAllowed(bool allowed) {
|
||||
mFormatConversionAllowed = allowed;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the quality of the sample rate converter in Oboe.
|
||||
*
|
||||
* If set to None then Oboe will not do sample rate conversion. But the underlying APIs might
|
||||
* still do sample rate conversion if you specify a sample rate.
|
||||
* That can prevent you from getting a low latency stream.
|
||||
*
|
||||
* If you do the conversion in Oboe then you might still get a low latency stream.
|
||||
*
|
||||
* Default is SampleRateConversionQuality::Medium
|
||||
*/
|
||||
AudioStreamBuilder *setSampleRateConversionQuality(SampleRateConversionQuality quality) {
|
||||
mSampleRateConversionQuality = quality;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare the name of the package creating the stream.
|
||||
*
|
||||
* This is usually {@code Context#getPackageName()}.
|
||||
*
|
||||
* The default, if you do not call this function, is a random package in the calling uid.
|
||||
* The vast majority of apps have only one package per calling UID.
|
||||
* If an invalid package name is set, input streams may not be given permission to
|
||||
* record when started.
|
||||
*
|
||||
* Please declare this as some input streams will fail permission checks otherwise.
|
||||
*
|
||||
* The package name is usually the applicationId in your app's build.gradle file.
|
||||
*
|
||||
* Available since API level 31.
|
||||
*
|
||||
* @param packageName packageName of the calling app.
|
||||
*/
|
||||
AudioStreamBuilder *setPackageName(std::string packageName) {
|
||||
mPackageName = packageName;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare the attribution tag of the context creating the stream.
|
||||
*
|
||||
* This is usually {@code Context#getAttributionTag()}.
|
||||
*
|
||||
* The default, if you do not call this function, is null.
|
||||
*
|
||||
* Available since API level 31.
|
||||
*
|
||||
* @param attributionTag attributionTag of the calling context.
|
||||
*/
|
||||
AudioStreamBuilder *setAttributionTag(std::string attributionTag) {
|
||||
mAttributionTag = attributionTag;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if AAudio will be used based on the current settings.
|
||||
*/
|
||||
bool willUseAAudio() const {
|
||||
return (mAudioApi == AudioApi::AAudio && isAAudioSupported())
|
||||
|| (mAudioApi == AudioApi::Unspecified && isAAudioRecommended());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and open a stream object based on the current settings.
|
||||
*
|
||||
* The caller owns the pointer to the AudioStream object
|
||||
* and must delete it when finished.
|
||||
*
|
||||
* @deprecated Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.
|
||||
* @param stream pointer to a variable to receive the stream address
|
||||
* @return OBOE_OK if successful or a negative error code
|
||||
*/
|
||||
Result openStream(AudioStream **stream);
|
||||
|
||||
/**
|
||||
* Create and open a stream object based on the current settings.
|
||||
*
|
||||
* The caller shares the pointer to the AudioStream object.
|
||||
* The shared_ptr is used internally by Oboe to prevent the stream from being
|
||||
* deleted while it is being used by callbacks.
|
||||
*
|
||||
* @param stream reference to a shared_ptr to receive the stream address
|
||||
* @return OBOE_OK if successful or a negative error code
|
||||
*/
|
||||
Result openStream(std::shared_ptr<oboe::AudioStream> &stream);
|
||||
|
||||
/**
|
||||
* Create and open a ManagedStream object based on the current builder state.
|
||||
*
|
||||
* The caller must create a unique ptr, and pass by reference so it can be
|
||||
* modified to point to an opened stream. The caller owns the unique ptr,
|
||||
* and it will be automatically closed and deleted when going out of scope.
|
||||
*
|
||||
* @deprecated Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.
|
||||
* @param stream Reference to the ManagedStream (uniqueptr) used to keep track of stream
|
||||
* @return OBOE_OK if successful or a negative error code.
|
||||
*/
|
||||
Result openManagedStream(ManagedStream &stream);
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Use this internally to implement opening with a shared_ptr.
|
||||
*
|
||||
* @param stream pointer to a variable to receive the stream address
|
||||
* @return OBOE_OK if successful or a negative error code.
|
||||
*/
|
||||
Result openStreamInternal(AudioStream **streamPP);
|
||||
|
||||
/**
|
||||
* @param other
|
||||
* @return true if channels, format and sample rate match
|
||||
*/
|
||||
bool isCompatible(AudioStreamBase &other);
|
||||
|
||||
/**
|
||||
* Create an AudioStream object. The AudioStream must be opened before use.
|
||||
*
|
||||
* The caller owns the pointer.
|
||||
*
|
||||
* @return pointer to an AudioStream object or nullptr.
|
||||
*/
|
||||
oboe::AudioStream *build();
|
||||
|
||||
AudioApi mAudioApi = AudioApi::Unspecified;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif /* OBOE_STREAM_BUILDER_H_ */
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STREAM_CALLBACK_H
|
||||
#define OBOE_STREAM_CALLBACK_H
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class AudioStream;
|
||||
|
||||
/**
|
||||
* AudioStreamDataCallback defines a callback interface for
|
||||
* moving data to/from an audio stream using `onAudioReady`
|
||||
* 2) being alerted when a stream has an error using `onError*` methods
|
||||
*
|
||||
* It is used with AudioStreamBuilder::setDataCallback().
|
||||
*/
|
||||
|
||||
class AudioStreamDataCallback {
|
||||
public:
|
||||
virtual ~AudioStreamDataCallback() = default;
|
||||
|
||||
/**
|
||||
* A buffer is ready for processing.
|
||||
*
|
||||
* For an output stream, this function should render and write numFrames of data
|
||||
* in the stream's current data format to the audioData buffer.
|
||||
*
|
||||
* For an input stream, this function should read and process numFrames of data
|
||||
* from the audioData buffer.
|
||||
*
|
||||
* The audio data is passed through the buffer. So do NOT call read() or
|
||||
* write() on the stream that is making the callback.
|
||||
*
|
||||
* Note that numFrames can vary unless AudioStreamBuilder::setFramesPerCallback()
|
||||
* is called. If AudioStreamBuilder::setFramesPerCallback() is NOT called then
|
||||
* numFrames should always be <= AudioStream::getFramesPerBurst().
|
||||
*
|
||||
* Also note that this callback function should be considered a "real-time" function.
|
||||
* It must not do anything that could cause an unbounded delay because that can cause the
|
||||
* audio to glitch or pop.
|
||||
*
|
||||
* These are things the function should NOT do:
|
||||
* <ul>
|
||||
* <li>allocate memory using, for example, malloc() or new</li>
|
||||
* <li>any file operations such as opening, closing, reading or writing</li>
|
||||
* <li>any network operations such as streaming</li>
|
||||
* <li>use any mutexes or other synchronization primitives</li>
|
||||
* <li>sleep</li>
|
||||
* <li>oboeStream->stop(), pause(), flush() or close()</li>
|
||||
* <li>oboeStream->read()</li>
|
||||
* <li>oboeStream->write()</li>
|
||||
* </ul>
|
||||
*
|
||||
* The following are OK to call from the data callback:
|
||||
* <ul>
|
||||
* <li>oboeStream->get*()</li>
|
||||
* <li>oboe::convertToText()</li>
|
||||
* <li>oboeStream->setBufferSizeInFrames()</li>
|
||||
* </ul>
|
||||
*
|
||||
* If you need to move data, eg. MIDI commands, in or out of the callback function then
|
||||
* we recommend the use of non-blocking techniques such as an atomic FIFO.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param audioData buffer containing input data or a place to put output data
|
||||
* @param numFrames number of frames to be processed
|
||||
* @return DataCallbackResult::Continue or DataCallbackResult::Stop
|
||||
*/
|
||||
virtual DataCallbackResult onAudioReady(
|
||||
AudioStream *audioStream,
|
||||
void *audioData,
|
||||
int32_t numFrames) = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* AudioStreamErrorCallback defines a callback interface for
|
||||
* being alerted when a stream has an error or is disconnected
|
||||
* using `onError*` methods.
|
||||
*
|
||||
* Note: This callback is only fired when an AudioStreamCallback is set.
|
||||
* If you use AudioStream::write() you have to evaluate the return codes of
|
||||
* AudioStream::write() to notice errors in the stream.
|
||||
*
|
||||
* It is used with AudioStreamBuilder::setErrorCallback().
|
||||
*/
|
||||
class AudioStreamErrorCallback {
|
||||
public:
|
||||
virtual ~AudioStreamErrorCallback() = default;
|
||||
|
||||
/**
|
||||
* This will be called before other `onError` methods when an error occurs on a stream,
|
||||
* such as when the stream is disconnected.
|
||||
*
|
||||
* It can be used to override and customize the normal error processing.
|
||||
* Use of this method is considered an advanced technique.
|
||||
* It might, for example, be used if an app want to use a high level lock when
|
||||
* closing and reopening a stream.
|
||||
* Or it might be used when an app want to signal a management thread that handles
|
||||
* all of the stream state.
|
||||
*
|
||||
* If this method returns false it indicates that the stream has *not been stopped and closed
|
||||
* by the application. In this case it will be stopped by Oboe in the following way:
|
||||
* onErrorBeforeClose() will be called, then the stream will be closed and onErrorAfterClose()
|
||||
* will be closed.
|
||||
*
|
||||
* If this method returns true it indicates that the stream *has* been stopped and closed
|
||||
* by the application and Oboe will not do this.
|
||||
* In that case, the app MUST stop() and close() the stream.
|
||||
*
|
||||
* This method will be called on a thread created by Oboe.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param error
|
||||
* @return true if the stream has been stopped and closed, false if not
|
||||
*/
|
||||
virtual bool onError(AudioStream* /* audioStream */, Result /* error */) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This will be called when an error occurs on a stream,
|
||||
* such as when the stream is disconnected,
|
||||
* and if onError() returns false (indicating that the error has not already been handled).
|
||||
*
|
||||
* Note that this will be called on a thread created by Oboe.
|
||||
*
|
||||
* The underlying stream will already be stopped by Oboe but not yet closed.
|
||||
* So the stream can be queried.
|
||||
*
|
||||
* Do not close or delete the stream in this method because it will be
|
||||
* closed after this method returns.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param error
|
||||
*/
|
||||
virtual void onErrorBeforeClose(AudioStream* /* audioStream */, Result /* error */) {}
|
||||
|
||||
/**
|
||||
* This will be called when an error occurs on a stream,
|
||||
* such as when the stream is disconnected,
|
||||
* and if onError() returns false (indicating that the error has not already been handled).
|
||||
*
|
||||
* The underlying AAudio or OpenSL ES stream will already be stopped AND closed by Oboe.
|
||||
* So the underlying stream cannot be referenced.
|
||||
* But you can still query most parameters.
|
||||
*
|
||||
* This callback could be used to reopen a new stream on another device.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param error
|
||||
*/
|
||||
virtual void onErrorAfterClose(AudioStream* /* audioStream */, Result /* error */) {}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* AudioStreamPresentationCallback defines a callback interface for
|
||||
* being notified when a data presentation event is filed.
|
||||
*
|
||||
* It is used with AudioStreamBuilder::setPresentationCallback().
|
||||
*/
|
||||
class AudioStreamPresentationCallback {
|
||||
public:
|
||||
virtual ~AudioStreamPresentationCallback() = default;
|
||||
|
||||
/**
|
||||
* This will be called when all the buffers of an offloaded
|
||||
* stream that were queued in the audio system (e.g. the
|
||||
* combination of the Android audio framework and the device's
|
||||
* audio hardware) have been played.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
*/
|
||||
virtual void onPresentationEnded(AudioStream* /* audioStream */) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* AudioStreamPartialDataCallback defines a callback interface for
|
||||
* moving data to/from an audio stream using `onAudioReady`
|
||||
*
|
||||
* It is used with AudioStreamBuilder::setPartialDataCallback(). The only difference
|
||||
* between AudioStreamPartialDataCallback and AudioStreamDataCallback is that the
|
||||
* AudioStreamPartialDataCallback allows apps to only process part of the requested
|
||||
* data.
|
||||
*
|
||||
* Note that Android only support partial data callback from aaudio API at
|
||||
* API level 37. In that case, when partial data callback is set on the Android
|
||||
* device that is not supporting partial data callback API, apps must process all
|
||||
* the requested data to avoid data lost.
|
||||
*
|
||||
* Call OboeExtensions::isPartialDataCallbackSupported() to check if partial data callback
|
||||
* is supported by the device or not.
|
||||
*/
|
||||
class AudioStreamPartialDataCallback {
|
||||
public:
|
||||
virtual ~AudioStreamPartialDataCallback() = default;
|
||||
|
||||
/**
|
||||
* A buffer is ready for processing. If the client cannot process all the provided/requested
|
||||
* data, returns a number to indicate the actual processed frames.
|
||||
*
|
||||
* For an output stream, this function should render and write at most numFrames of data
|
||||
* in the stream's current data format to the audioData buffer.
|
||||
*
|
||||
* For an input stream, this function should read and process at most numFrames of data
|
||||
* from the audioData buffer.
|
||||
*
|
||||
* The audio data is passed through the buffer. So do NOT call read() or
|
||||
* write() on the stream that is making the callback.
|
||||
*
|
||||
* Note that numFrames can vary unless AudioStreamBuilder::setFramesPerCallback()
|
||||
* is called. If AudioStreamBuilder::setFramesPerCallback() is NOT called then
|
||||
* numFrames should always be <= AudioStream::getFramesPerBurst().
|
||||
*
|
||||
* Also note that this callback function should be considered a "real-time" function.
|
||||
* It must not do anything that could cause an unbounded delay because that can cause the
|
||||
* audio to glitch or pop.
|
||||
*
|
||||
* These are things the function should NOT do:
|
||||
* <ul>
|
||||
* <li>allocate memory using, for example, malloc() or new</li>
|
||||
* <li>any file operations such as opening, closing, reading or writing</li>
|
||||
* <li>any network operations such as streaming</li>
|
||||
* <li>use any mutexes or other synchronization primitives</li>
|
||||
* <li>sleep</li>
|
||||
* <li>oboeStream->stop(), pause(), flush() or close()</li>
|
||||
* <li>oboeStream->read()</li>
|
||||
* <li>oboeStream->write()</li>
|
||||
* </ul>
|
||||
*
|
||||
* The following are OK to call from the data callback:
|
||||
* <ul>
|
||||
* <li>oboeStream->get*()</li>
|
||||
* <li>oboe::convertToText()</li>
|
||||
* <li>oboeStream->setBufferSizeInFrames()</li>
|
||||
* </ul>
|
||||
*
|
||||
* If you need to move data, eg. MIDI commands, in or out of the callback function then
|
||||
* we recommend the use of non-blocking techniques such as an atomic FIFO.
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param audioData buffer containing input data or a place to put output data
|
||||
* @param numFrames number of frames to be processed
|
||||
* @return the actual processed data frames, must be within range of [0, numFrames].
|
||||
* Returning a negative number will stop the stream.
|
||||
*/
|
||||
virtual int32_t onPartialAudioReady(
|
||||
AudioStream *audioStream,
|
||||
void *audioData,
|
||||
int32_t numFrames) = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* AudioStreamCallback defines a callback interface for:
|
||||
*
|
||||
* 1) moving data to/from an audio stream using `onAudioReady`
|
||||
* 2) being alerted when a stream has an error using `onError*` methods
|
||||
*
|
||||
* It is used with AudioStreamBuilder::setCallback().
|
||||
*
|
||||
* It combines the interfaces defined by AudioStreamDataCallback and AudioStreamErrorCallback.
|
||||
* This was the original callback object. We now recommend using the individual interfaces
|
||||
* and using setDataCallback() and setErrorCallback().
|
||||
*
|
||||
* @deprecated Use `AudioStreamDataCallback` and `AudioStreamErrorCallback` instead
|
||||
*/
|
||||
class AudioStreamCallback : public AudioStreamDataCallback,
|
||||
public AudioStreamErrorCallback {
|
||||
public:
|
||||
virtual ~AudioStreamCallback() = default;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_STREAM_CALLBACK_H
|
||||
+1217
File diff suppressed because it is too large
Load Diff
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_FIFOPROCESSOR_H
|
||||
#define OBOE_FIFOPROCESSOR_H
|
||||
|
||||
#include <memory>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
#include "oboe/FifoControllerBase.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class FifoBuffer {
|
||||
public:
|
||||
/**
|
||||
* Construct a `FifoBuffer`.
|
||||
*
|
||||
* @param bytesPerFrame amount of bytes for one frame
|
||||
* @param capacityInFrames the capacity of frames in fifo
|
||||
*/
|
||||
FifoBuffer(uint32_t bytesPerFrame, uint32_t capacityInFrames);
|
||||
|
||||
/**
|
||||
* Construct a `FifoBuffer`.
|
||||
* To be used if the storage allocation is done outside of FifoBuffer.
|
||||
*
|
||||
* @param bytesPerFrame amount of bytes for one frame
|
||||
* @param capacityInFrames capacity of frames in fifo
|
||||
* @param readCounterAddress address of read counter
|
||||
* @param writeCounterAddress address of write counter
|
||||
* @param dataStorageAddress address of storage
|
||||
*/
|
||||
FifoBuffer(uint32_t bytesPerFrame,
|
||||
uint32_t capacityInFrames,
|
||||
std::atomic<uint64_t> *readCounterAddress,
|
||||
std::atomic<uint64_t> *writeCounterAddress,
|
||||
uint8_t *dataStorageAddress);
|
||||
|
||||
~FifoBuffer();
|
||||
|
||||
/**
|
||||
* Convert a number of frames in bytes.
|
||||
*
|
||||
* @return number of bytes
|
||||
*/
|
||||
int32_t convertFramesToBytes(int32_t frames);
|
||||
|
||||
/**
|
||||
* Read framesToRead or, if not enough, then read as many as are available.
|
||||
*
|
||||
* @param destination
|
||||
* @param framesToRead number of frames requested
|
||||
* @return number of frames actually read
|
||||
*/
|
||||
int32_t read(void *destination, int32_t framesToRead);
|
||||
|
||||
/**
|
||||
* Write framesToWrite or, if too enough, then write as many as the fifo are not empty.
|
||||
*
|
||||
* @param destination
|
||||
* @param framesToWrite number of frames requested
|
||||
* @return number of frames actually write
|
||||
*/
|
||||
int32_t write(const void *source, int32_t framesToWrite);
|
||||
|
||||
/**
|
||||
* Get the buffer capacity in frames.
|
||||
*
|
||||
* @return number of frames
|
||||
*/
|
||||
uint32_t getBufferCapacityInFrames() const;
|
||||
|
||||
/**
|
||||
* Calls read(). If all of the frames cannot be read then the remainder of the buffer
|
||||
* is set to zero.
|
||||
*
|
||||
* @param destination
|
||||
* @param framesToRead number of frames requested
|
||||
* @return number of frames actually read
|
||||
*/
|
||||
int32_t readNow(void *destination, int32_t numFrames);
|
||||
|
||||
/**
|
||||
* Get the number of frames in the fifo.
|
||||
*
|
||||
* @return number of frames actually in the buffer
|
||||
*/
|
||||
uint32_t getFullFramesAvailable() {
|
||||
return mFifo->getFullFramesAvailable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the amount of bytes per frame.
|
||||
*
|
||||
* @return number of bytes per frame
|
||||
*/
|
||||
uint32_t getBytesPerFrame() const {
|
||||
return mBytesPerFrame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the position of read counter.
|
||||
*
|
||||
* @return position of read counter
|
||||
*/
|
||||
uint64_t getReadCounter() const {
|
||||
return mFifo->getReadCounter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the position of read counter.
|
||||
*
|
||||
* @param n position of read counter
|
||||
*/
|
||||
void setReadCounter(uint64_t n) {
|
||||
mFifo->setReadCounter(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the position of write counter.
|
||||
*
|
||||
* @return position of write counter
|
||||
*/
|
||||
uint64_t getWriteCounter() {
|
||||
return mFifo->getWriteCounter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the position of write counter.
|
||||
*
|
||||
* @param n position of write counter
|
||||
*/
|
||||
void setWriteCounter(uint64_t n) {
|
||||
mFifo->setWriteCounter(n);
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t mBytesPerFrame;
|
||||
uint8_t* mStorage;
|
||||
bool mStorageOwned; // did this object allocate the storage?
|
||||
std::unique_ptr<FifoControllerBase> mFifo;
|
||||
uint64_t mFramesReadCount;
|
||||
uint64_t mFramesUnderrunCount;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_FIFOPROCESSOR_H
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef NATIVEOBOE_FIFOCONTROLLERBASE_H
|
||||
#define NATIVEOBOE_FIFOCONTROLLERBASE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* Manage the read/write indices of a circular buffer.
|
||||
*
|
||||
* The caller is responsible for reading and writing the actual data.
|
||||
* Note that the span of available frames may not be contiguous. They
|
||||
* may wrap around from the end to the beginning of the buffer. In that
|
||||
* case the data must be read or written in at least two blocks of frames.
|
||||
*
|
||||
*/
|
||||
|
||||
class FifoControllerBase {
|
||||
|
||||
public:
|
||||
/**
|
||||
* Construct a `FifoControllerBase`.
|
||||
*
|
||||
* @param totalFrames capacity of the circular buffer in frames
|
||||
*/
|
||||
FifoControllerBase(uint32_t totalFrames);
|
||||
|
||||
virtual ~FifoControllerBase() = default;
|
||||
|
||||
/**
|
||||
* The frames available to read will be calculated from the read and write counters.
|
||||
* The result will be clipped to the capacity of the buffer.
|
||||
* If the buffer has underflowed then this will return zero.
|
||||
*
|
||||
* @return number of valid frames available to read.
|
||||
*/
|
||||
uint32_t getFullFramesAvailable() const;
|
||||
|
||||
/**
|
||||
* The index in a circular buffer of the next frame to read.
|
||||
*
|
||||
* @return read index position
|
||||
*/
|
||||
uint32_t getReadIndex() const;
|
||||
|
||||
/**
|
||||
* Advance read index from a number of frames.
|
||||
* Equivalent of incrementReadCounter(numFrames).
|
||||
*
|
||||
* @param numFrames number of frames to advance the read index
|
||||
*/
|
||||
void advanceReadIndex(uint32_t numFrames);
|
||||
|
||||
/**
|
||||
* Get the number of frame that are not written yet.
|
||||
*
|
||||
* @return maximum number of frames that can be written without exceeding the threshold
|
||||
*/
|
||||
uint32_t getEmptyFramesAvailable() const;
|
||||
|
||||
/**
|
||||
* The index in a circular buffer of the next frame to write.
|
||||
*
|
||||
* @return index of the next frame to write
|
||||
*/
|
||||
uint32_t getWriteIndex() const;
|
||||
|
||||
/**
|
||||
* Advance write index from a number of frames.
|
||||
* Equivalent of incrementWriteCounter(numFrames).
|
||||
*
|
||||
* @param numFrames number of frames to advance the write index
|
||||
*/
|
||||
void advanceWriteIndex(uint32_t numFrames);
|
||||
|
||||
/**
|
||||
* Get the frame capacity of the fifo.
|
||||
*
|
||||
* @return frame capacity
|
||||
*/
|
||||
uint32_t getFrameCapacity() const { return mTotalFrames; }
|
||||
|
||||
virtual uint64_t getReadCounter() const = 0;
|
||||
virtual void setReadCounter(uint64_t n) = 0;
|
||||
virtual void incrementReadCounter(uint64_t n) = 0;
|
||||
virtual uint64_t getWriteCounter() const = 0;
|
||||
virtual void setWriteCounter(uint64_t n) = 0;
|
||||
virtual void incrementWriteCounter(uint64_t n) = 0;
|
||||
|
||||
private:
|
||||
uint32_t mTotalFrames;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //NATIVEOBOE_FIFOCONTROLLERBASE_H
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
/*
|
||||
* Copyright 2023 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_FULL_DUPLEX_STREAM_
|
||||
#define OBOE_FULL_DUPLEX_STREAM_
|
||||
|
||||
#include <cstdint>
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
#include "oboe/AudioStreamCallback.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* FullDuplexStream can be used to synchronize an input and output stream.
|
||||
*
|
||||
* For the builder of the output stream, call setDataCallback() with this object.
|
||||
*
|
||||
* When both streams are ready, onAudioReady() of the output stream will call onBothStreamsReady().
|
||||
* Callers must override onBothStreamsReady().
|
||||
*
|
||||
* To ensure best results, open an output stream before the input stream.
|
||||
* Call inputBuilder.setBufferCapacityInFrames(mOutputStream->getBufferCapacityInFrames() * 2).
|
||||
* Also, call inputBuilder.setSampleRate(mOutputStream->getSampleRate()).
|
||||
*
|
||||
* Callers must call setInputStream() and setOutputStream().
|
||||
* Call start() to start both streams and stop() to stop both streams.
|
||||
* Caller is responsible for closing both streams.
|
||||
*
|
||||
* Callers should handle error callbacks with setErrorCallback() for the output stream.
|
||||
* When an error callback occurs for the output stream, Oboe will stop and close the output stream.
|
||||
* The caller is responsible for stopping and closing the input stream.
|
||||
* The caller should also reopen and restart both streams when the error callback is ErrorDisconnected.
|
||||
* See the LiveEffect sample as an example of this.
|
||||
*
|
||||
*/
|
||||
class FullDuplexStream : public AudioStreamDataCallback {
|
||||
public:
|
||||
FullDuplexStream() {}
|
||||
virtual ~FullDuplexStream() = default;
|
||||
|
||||
/**
|
||||
* Sets the input stream.
|
||||
*
|
||||
* @deprecated Call setSharedInputStream(std::shared_ptr<AudioStream> &stream) instead.
|
||||
* @param stream the output stream
|
||||
*/
|
||||
void setInputStream(AudioStream *stream) {
|
||||
mRawInputStream = stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the input stream. Calling this is mandatory.
|
||||
*
|
||||
* @param stream the output stream
|
||||
*/
|
||||
void setSharedInputStream(std::shared_ptr<AudioStream> &stream) {
|
||||
mSharedInputStream = stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current input stream. This function tries to return the shared input stream if it
|
||||
* is set before the raw input stream.
|
||||
*
|
||||
* @return pointer to an output stream or nullptr.
|
||||
*/
|
||||
AudioStream *getInputStream() {
|
||||
if (mSharedInputStream) {
|
||||
return mSharedInputStream.get();
|
||||
} else {
|
||||
return mRawInputStream;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the output stream.
|
||||
*
|
||||
* @deprecated Call setSharedOutputStream(std::shared_ptr<AudioStream> &stream) instead.
|
||||
* @param stream the output stream
|
||||
*/
|
||||
void setOutputStream(AudioStream *stream) {
|
||||
mRawOutputStream = stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the output stream. Calling this is mandatory.
|
||||
*
|
||||
* @param stream the output stream
|
||||
*/
|
||||
void setSharedOutputStream(std::shared_ptr<AudioStream> &stream) {
|
||||
mSharedOutputStream = stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current output stream. This function tries to return the shared output stream if it
|
||||
* is set before the raw output stream.
|
||||
*
|
||||
* @return pointer to an output stream or nullptr.
|
||||
*/
|
||||
AudioStream *getOutputStream() {
|
||||
if (mSharedOutputStream) {
|
||||
return mSharedOutputStream.get();
|
||||
} else {
|
||||
return mRawOutputStream;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to start both streams. Please call setInputStream() and setOutputStream() before
|
||||
* calling this function.
|
||||
*
|
||||
* @return result of the operation
|
||||
*/
|
||||
virtual Result start() {
|
||||
mCountCallbacksToDrain = kNumCallbacksToDrain;
|
||||
mCountInputBurstsCushion = mNumInputBurstsCushion;
|
||||
mCountCallbacksToDiscard = kNumCallbacksToDiscard;
|
||||
|
||||
// Determine maximum size that could possibly be called.
|
||||
int32_t bufferSize = getOutputStream()->getBufferCapacityInFrames()
|
||||
* getOutputStream()->getChannelCount();
|
||||
if (bufferSize > mBufferSize) {
|
||||
mInputBuffer = std::make_unique<float[]>(bufferSize);
|
||||
mBufferSize = bufferSize;
|
||||
}
|
||||
|
||||
oboe::Result result = getInputStream()->requestStart();
|
||||
if (result != oboe::Result::OK) {
|
||||
return result;
|
||||
}
|
||||
return getOutputStream()->requestStart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops both streams. Returns Result::OK if neither stream had an error during close.
|
||||
*
|
||||
* @return result of the operation
|
||||
*/
|
||||
virtual Result stop() {
|
||||
Result outputResult = Result::OK;
|
||||
Result inputResult = Result::OK;
|
||||
if (getOutputStream()) {
|
||||
outputResult = getOutputStream()->requestStop();
|
||||
}
|
||||
if (getInputStream()) {
|
||||
inputResult = getInputStream()->requestStop();
|
||||
}
|
||||
if (outputResult != Result::OK) {
|
||||
return outputResult;
|
||||
} else {
|
||||
return inputResult;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads input from the input stream. Callers should not call this directly as this is called
|
||||
* in onAudioReady().
|
||||
*
|
||||
* @param numFrames
|
||||
* @return result of the operation
|
||||
*/
|
||||
virtual ResultWithValue<int32_t> readInput(int32_t numFrames) {
|
||||
return getInputStream()->read(mInputBuffer.get(), numFrames, 0 /* timeout */);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when data is available on both streams.
|
||||
* Caller should override this method.
|
||||
* numInputFrames and numOutputFrames may be zero.
|
||||
*
|
||||
* @param inputData buffer containing input data
|
||||
* @param numInputFrames number of input frames
|
||||
* @param outputData a place to put output data
|
||||
* @param numOutputFrames number of output frames
|
||||
* @return DataCallbackResult::Continue or DataCallbackResult::Stop
|
||||
*/
|
||||
virtual DataCallbackResult onBothStreamsReady(
|
||||
const void *inputData,
|
||||
int numInputFrames,
|
||||
void *outputData,
|
||||
int numOutputFrames
|
||||
) = 0;
|
||||
|
||||
/**
|
||||
* Called when the output stream is ready to process audio.
|
||||
* This in return calls onBothStreamsReady() when data is available on both streams.
|
||||
* Callers should call this function when the output stream is ready.
|
||||
* Callers must override onBothStreamsReady().
|
||||
*
|
||||
* @param audioStream pointer to the associated stream
|
||||
* @param audioData a place to put output data
|
||||
* @param numFrames number of frames to be processed
|
||||
* @return DataCallbackResult::Continue or DataCallbackResult::Stop
|
||||
*
|
||||
*/
|
||||
DataCallbackResult onAudioReady(
|
||||
AudioStream * /*audioStream*/,
|
||||
void *audioData,
|
||||
int numFrames) {
|
||||
DataCallbackResult callbackResult = DataCallbackResult::Continue;
|
||||
int32_t actualFramesRead = 0;
|
||||
|
||||
// Silence the output.
|
||||
int32_t numBytes = numFrames * getOutputStream()->getBytesPerFrame();
|
||||
memset(audioData, 0 /* value */, numBytes);
|
||||
|
||||
if (mCountCallbacksToDrain > 0) {
|
||||
// Drain the input.
|
||||
int32_t totalFramesRead = 0;
|
||||
do {
|
||||
ResultWithValue<int32_t> result = readInput(numFrames);
|
||||
if (!result) {
|
||||
// Ignore errors because input stream may not be started yet.
|
||||
break;
|
||||
}
|
||||
actualFramesRead = result.value();
|
||||
totalFramesRead += actualFramesRead;
|
||||
} while (actualFramesRead > 0);
|
||||
// Only counts if we actually got some data.
|
||||
if (totalFramesRead > 0) {
|
||||
mCountCallbacksToDrain--;
|
||||
}
|
||||
|
||||
} else if (mCountInputBurstsCushion > 0) {
|
||||
// Let the input fill up a bit so we are not so close to the write pointer.
|
||||
mCountInputBurstsCushion--;
|
||||
|
||||
} else if (mCountCallbacksToDiscard > 0) {
|
||||
mCountCallbacksToDiscard--;
|
||||
// Ignore. Allow the input to reach to equilibrium with the output.
|
||||
ResultWithValue<int32_t> resultAvailable = getInputStream()->getAvailableFrames();
|
||||
if (!resultAvailable) {
|
||||
callbackResult = DataCallbackResult::Stop;
|
||||
} else {
|
||||
int32_t framesAvailable = resultAvailable.value();
|
||||
if (framesAvailable >= mMinimumFramesBeforeRead) {
|
||||
ResultWithValue<int32_t> resultRead = readInput(numFrames);
|
||||
if (!resultRead) {
|
||||
callbackResult = DataCallbackResult::Stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int32_t framesRead = 0;
|
||||
ResultWithValue<int32_t> resultAvailable = getInputStream()->getAvailableFrames();
|
||||
if (!resultAvailable) {
|
||||
callbackResult = DataCallbackResult::Stop;
|
||||
} else {
|
||||
int32_t framesAvailable = resultAvailable.value();
|
||||
if (framesAvailable >= mMinimumFramesBeforeRead) {
|
||||
// Read data into input buffer.
|
||||
ResultWithValue<int32_t> resultRead = readInput(numFrames);
|
||||
if (!resultRead) {
|
||||
callbackResult = DataCallbackResult::Stop;
|
||||
} else {
|
||||
framesRead = resultRead.value();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (callbackResult == DataCallbackResult::Continue) {
|
||||
callbackResult = onBothStreamsReady(mInputBuffer.get(), framesRead,
|
||||
audioData, numFrames);
|
||||
}
|
||||
}
|
||||
|
||||
if (callbackResult == DataCallbackResult::Stop) {
|
||||
getInputStream()->requestStop();
|
||||
}
|
||||
|
||||
return callbackResult;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* This is a cushion between the DSP and the application processor cursors to prevent collisions.
|
||||
* Typically 0 for latency measurements or 1 for glitch tests.
|
||||
*
|
||||
* @param numBursts number of bursts to leave in the input buffer as a cushion
|
||||
*/
|
||||
void setNumInputBurstsCushion(int32_t numBursts) {
|
||||
mNumInputBurstsCushion = numBursts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of bursts left in the input buffer as a cushion.
|
||||
*
|
||||
* @return number of bursts in the input buffer as a cushion
|
||||
*/
|
||||
int32_t getNumInputBurstsCushion() const {
|
||||
return mNumInputBurstsCushion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum number of frames in the input stream buffer before calling readInput().
|
||||
*
|
||||
* @param numFrames number of bursts in the input buffer as a cushion
|
||||
*/
|
||||
void setMinimumFramesBeforeRead(int32_t numFrames) {
|
||||
mMinimumFramesBeforeRead = numFrames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the minimum number of frames in the input stream buffer before calling readInput().
|
||||
*
|
||||
* @return minimum number of frames before reading
|
||||
*/
|
||||
int32_t getMinimumFramesBeforeRead() const {
|
||||
return mMinimumFramesBeforeRead;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// TODO add getters and setters
|
||||
static constexpr int32_t kNumCallbacksToDrain = 20;
|
||||
static constexpr int32_t kNumCallbacksToDiscard = 30;
|
||||
|
||||
// let input fill back up, usually 0 or 1
|
||||
int32_t mNumInputBurstsCushion = 0;
|
||||
int32_t mMinimumFramesBeforeRead = 0;
|
||||
|
||||
// We want to reach a state where the input buffer is empty and
|
||||
// the output buffer is full.
|
||||
// These are used in order.
|
||||
// Drain several callback so that input is empty.
|
||||
int32_t mCountCallbacksToDrain = kNumCallbacksToDrain;
|
||||
// Let the input fill back up slightly so we don't run dry.
|
||||
int32_t mCountInputBurstsCushion = mNumInputBurstsCushion;
|
||||
// Discard some callbacks so the input and output reach equilibrium.
|
||||
int32_t mCountCallbacksToDiscard = kNumCallbacksToDiscard;
|
||||
|
||||
AudioStream *mRawInputStream = nullptr;
|
||||
AudioStream *mRawOutputStream = nullptr;
|
||||
std::shared_ptr<AudioStream> mSharedInputStream;
|
||||
std::shared_ptr<AudioStream> mSharedOutputStream;
|
||||
|
||||
int32_t mBufferSize = 0;
|
||||
std::unique_ptr<float[]> mInputBuffer;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_FULL_DUPLEX_STREAM_
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Copyright 2017 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_LATENCY_TUNER_
|
||||
#define OBOE_LATENCY_TUNER_
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* LatencyTuner can be used to dynamically tune the latency of an output stream.
|
||||
* It adjusts the stream's bufferSize by monitoring the number of underruns.
|
||||
*
|
||||
* This only affects the latency associated with the first level of buffering that is closest
|
||||
* to the application. It does not affect low latency in the HAL, or touch latency in the UI.
|
||||
*
|
||||
* Call tune() right before returning from your data callback function if using callbacks.
|
||||
* Call tune() right before calling write() if using blocking writes.
|
||||
*
|
||||
* If you want to see the ongoing results of this tuning process then call
|
||||
* stream->getBufferSize() periodically.
|
||||
*
|
||||
*/
|
||||
class LatencyTuner {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Construct a new LatencyTuner object which will act on the given audio stream
|
||||
*
|
||||
* @param stream the stream who's latency will be tuned
|
||||
*/
|
||||
explicit LatencyTuner(AudioStream &stream);
|
||||
|
||||
/**
|
||||
* Construct a new LatencyTuner object which will act on the given audio stream.
|
||||
*
|
||||
* @param stream the stream who's latency will be tuned
|
||||
* @param the maximum buffer size which the tune() operation will set the buffer size to
|
||||
*/
|
||||
explicit LatencyTuner(AudioStream &stream, int32_t maximumBufferSize);
|
||||
|
||||
/**
|
||||
* Adjust the bufferSizeInFrames to optimize latency.
|
||||
* It will start with a low latency and then raise it if an underrun occurs.
|
||||
*
|
||||
* Latency tuning is only supported for AAudio.
|
||||
*
|
||||
* @return OK or negative error, ErrorUnimplemented for OpenSL ES
|
||||
*/
|
||||
Result tune();
|
||||
|
||||
/**
|
||||
* This may be called from another thread. Then tune() will call reset(),
|
||||
* which will lower the latency to the minimum and then allow it to rise back up
|
||||
* if there are glitches.
|
||||
*
|
||||
* This is typically called in response to a user decision to minimize latency. In other words,
|
||||
* call this from a button handler.
|
||||
*/
|
||||
void requestReset();
|
||||
|
||||
/**
|
||||
* @return true if the audio stream's buffer size is at the maximum value. If no maximum value
|
||||
* was specified when constructing the LatencyTuner then the value of
|
||||
* stream->getBufferCapacityInFrames is used
|
||||
*/
|
||||
bool isAtMaximumBufferSize();
|
||||
|
||||
/**
|
||||
* Set the minimum bufferSize in frames that is used when the tuner is reset.
|
||||
* You may wish to call requestReset() after calling this.
|
||||
* @param bufferSize
|
||||
*/
|
||||
void setMinimumBufferSize(int32_t bufferSize) {
|
||||
mMinimumBufferSize = bufferSize;
|
||||
}
|
||||
|
||||
int32_t getMinimumBufferSize() const {
|
||||
return mMinimumBufferSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the amount the bufferSize will be incremented while tuning.
|
||||
* By default, this will be one burst.
|
||||
*
|
||||
* Note that AAudio will quantize the buffer size to a multiple of the burstSize.
|
||||
* So the final buffer sizes may not be a multiple of this increment.
|
||||
*
|
||||
* @param sizeIncrement
|
||||
*/
|
||||
void setBufferSizeIncrement(int32_t sizeIncrement) {
|
||||
mBufferSizeIncrement = sizeIncrement;
|
||||
}
|
||||
|
||||
int32_t getBufferSizeIncrement() const {
|
||||
return mBufferSizeIncrement;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Drop the latency down to the minimum and then let it rise back up.
|
||||
* This is useful if a glitch caused the latency to increase and it hasn't gone back down.
|
||||
*
|
||||
* This should only be called in the same thread as tune().
|
||||
*/
|
||||
void reset();
|
||||
|
||||
enum class State {
|
||||
Idle,
|
||||
Active,
|
||||
AtMax,
|
||||
Unsupported
|
||||
} ;
|
||||
|
||||
// arbitrary number of calls to wait before bumping up the latency
|
||||
static constexpr int32_t kIdleCount = 8;
|
||||
static constexpr int32_t kDefaultNumBursts = 2;
|
||||
|
||||
AudioStream &mStream;
|
||||
State mState = State::Idle;
|
||||
int32_t mMaxBufferSize = 0;
|
||||
int32_t mPreviousXRuns = 0;
|
||||
int32_t mIdleCountDown = 0;
|
||||
int32_t mMinimumBufferSize;
|
||||
int32_t mBufferSizeIncrement;
|
||||
std::atomic<int32_t> mLatencyTriggerRequests{0}; // TODO user atomic requester from AAudio
|
||||
std::atomic<int32_t> mLatencyTriggerResponses{0};
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif // OBOE_LATENCY_TUNER_
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_OBOE_H
|
||||
#define OBOE_OBOE_H
|
||||
|
||||
/**
|
||||
* \mainpage API reference
|
||||
*
|
||||
* See our <a href="https://github.com/google/oboe/blob/main/docs/FullGuide.md">guide</a> on Github
|
||||
* for a guide on Oboe.
|
||||
*
|
||||
* Click the classes tab to see the reference for various Oboe functions.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/ResultWithValue.h"
|
||||
#include "oboe/LatencyTuner.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
#include "oboe/AudioStreamBase.h"
|
||||
#include "oboe/AudioStreamBuilder.h"
|
||||
#include "oboe/Utilities.h"
|
||||
#include "oboe/Version.h"
|
||||
#include "oboe/StabilizedCallback.h"
|
||||
#include "oboe/FifoBuffer.h"
|
||||
#include "oboe/OboeExtensions.h"
|
||||
#include "oboe/FullDuplexStream.h"
|
||||
#include "oboe/AudioClock.h"
|
||||
|
||||
#endif //OBOE_OBOE_H
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_EXTENSIONS_
|
||||
#define OBOE_EXTENSIONS_
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* The definitions below are only for testing.
|
||||
* They are not recommended for use in an application.
|
||||
* They may change or be removed at any time.
|
||||
*/
|
||||
class OboeExtensions {
|
||||
public:
|
||||
|
||||
/**
|
||||
* @returns true if the device supports AAudio MMAP
|
||||
*/
|
||||
static bool isMMapSupported();
|
||||
|
||||
/**
|
||||
* @returns true if the AAudio MMAP data path can be selected
|
||||
*/
|
||||
static bool isMMapEnabled();
|
||||
|
||||
/**
|
||||
* Controls whether the AAudio MMAP data path can be selected when opening a stream.
|
||||
* It has no effect after the stream has been opened.
|
||||
* It only affects the application that calls it. Other apps are not affected.
|
||||
*
|
||||
* @param enabled
|
||||
* @return 0 or a negative error code
|
||||
*/
|
||||
static int32_t setMMapEnabled(bool enabled);
|
||||
|
||||
/**
|
||||
* @param oboeStream
|
||||
* @return true if the AAudio MMAP data path is used on the stream
|
||||
*/
|
||||
static bool isMMapUsed(oboe::AudioStream *oboeStream);
|
||||
|
||||
/**
|
||||
* @returns true if partial data callback is supported.
|
||||
*/
|
||||
static bool isPartialDataCallbackSupported();
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif // OBOE_LATENCY_TUNER_
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_RESULT_WITH_VALUE_H
|
||||
#define OBOE_RESULT_WITH_VALUE_H
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* A ResultWithValue can store both the result of an operation (either OK or an error) and a value.
|
||||
*
|
||||
* It has been designed for cases where the caller needs to know whether an operation succeeded and,
|
||||
* if it did, a value which was obtained during the operation.
|
||||
*
|
||||
* For example, when reading from a stream the caller needs to know the result of the read operation
|
||||
* and, if it was successful, how many frames were read. Note that ResultWithValue can be evaluated
|
||||
* as a boolean so it's simple to check whether the result is OK.
|
||||
*
|
||||
* <code>
|
||||
* ResultWithValue<int32_t> resultOfRead = myStream.read(&buffer, numFrames, timeoutNanoseconds);
|
||||
*
|
||||
* if (resultOfRead) {
|
||||
* LOGD("Frames read: %d", resultOfRead.value());
|
||||
* } else {
|
||||
* LOGD("Error reading from stream: %s", resultOfRead.error());
|
||||
* }
|
||||
* </code>
|
||||
*/
|
||||
template <typename T>
|
||||
class ResultWithValue {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Construct a ResultWithValue containing an error result.
|
||||
*
|
||||
* @param error The error
|
||||
*/
|
||||
ResultWithValue(oboe::Result error)
|
||||
: mValue{}
|
||||
, mError(error) {}
|
||||
|
||||
/**
|
||||
* Construct a ResultWithValue containing an OK result and a value.
|
||||
*
|
||||
* @param value the value to store
|
||||
*/
|
||||
explicit ResultWithValue(T value)
|
||||
: mValue(value)
|
||||
, mError(oboe::Result::OK) {}
|
||||
|
||||
ResultWithValue(T value, oboe::Result error)
|
||||
: mValue(value)
|
||||
, mError(error) {}
|
||||
|
||||
/**
|
||||
* Get the result.
|
||||
*
|
||||
* @return the result
|
||||
*/
|
||||
oboe::Result error() const {
|
||||
return mError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value
|
||||
* @return
|
||||
*/
|
||||
T value() const {
|
||||
return mValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if OK
|
||||
*/
|
||||
explicit operator bool() const { return mError == oboe::Result::OK; }
|
||||
|
||||
/**
|
||||
* Quick way to check for an error.
|
||||
*
|
||||
* The caller could write something like this:
|
||||
* <code>
|
||||
* if (!result) { printf("Got error %s\n", convertToText(result.error())); }
|
||||
* </code>
|
||||
*
|
||||
* @return true if an error occurred
|
||||
*/
|
||||
bool operator !() const { return mError != oboe::Result::OK; }
|
||||
|
||||
/**
|
||||
* Implicitly convert to a Result. This enables easy comparison with Result values. Example:
|
||||
*
|
||||
* <code>
|
||||
* ResultWithValue result = openStream();
|
||||
* if (result == Result::ErrorNoMemory){ // tell user they're out of memory }
|
||||
* </code>
|
||||
*/
|
||||
operator Result() const {
|
||||
return mError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ResultWithValue from a number. If the number is positive the ResultWithValue will
|
||||
* have a result of Result::OK and the value will contain the number. If the number is negative
|
||||
* the result will be obtained from the negative number (numeric error codes can be found in
|
||||
* AAudio.h) and the value will be null.
|
||||
*
|
||||
*/
|
||||
static ResultWithValue<T> createBasedOnSign(T numericResult){
|
||||
|
||||
// Ensure that the type is either an integer or float
|
||||
static_assert(std::is_arithmetic<T>::value,
|
||||
"createBasedOnSign can only be called for numeric types (int or float)");
|
||||
|
||||
if (numericResult >= 0){
|
||||
return ResultWithValue<T>(numericResult);
|
||||
} else {
|
||||
return ResultWithValue<T>(static_cast<Result>(numericResult));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
const T mValue;
|
||||
const oboe::Result mError;
|
||||
};
|
||||
|
||||
/**
|
||||
* If the result is `OK` then return the value, otherwise return a human-readable error message.
|
||||
*/
|
||||
template <typename T>
|
||||
std::ostream& operator<<(std::ostream &strm, const ResultWithValue<T> &result) {
|
||||
if (!result) {
|
||||
strm << convertToText(result.error());
|
||||
} else {
|
||||
strm << result.value();
|
||||
}
|
||||
return strm;
|
||||
}
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
|
||||
#endif //OBOE_RESULT_WITH_VALUE_H
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STABILIZEDCALLBACK_H
|
||||
#define OBOE_STABILIZEDCALLBACK_H
|
||||
|
||||
#include <cstdint>
|
||||
#include "oboe/AudioStream.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class StabilizedCallback : public AudioStreamCallback {
|
||||
|
||||
public:
|
||||
explicit StabilizedCallback(AudioStreamCallback *callback);
|
||||
|
||||
DataCallbackResult
|
||||
onAudioReady(AudioStream *oboeStream, void *audioData, int32_t numFrames) override;
|
||||
|
||||
void onErrorBeforeClose(AudioStream *oboeStream, Result error) override {
|
||||
return mCallback->onErrorBeforeClose(oboeStream, error);
|
||||
}
|
||||
|
||||
void onErrorAfterClose(AudioStream *oboeStream, Result error) override {
|
||||
|
||||
// Reset all fields now that the stream has been closed
|
||||
mFrameCount = 0;
|
||||
mEpochTimeNanos = 0;
|
||||
mOpsPerNano = 1;
|
||||
return mCallback->onErrorAfterClose(oboeStream, error);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
AudioStreamCallback *mCallback = nullptr;
|
||||
int64_t mFrameCount = 0;
|
||||
int64_t mEpochTimeNanos = 0;
|
||||
double mOpsPerNano = 1;
|
||||
|
||||
void generateLoad(int64_t durationNanos);
|
||||
};
|
||||
|
||||
/**
|
||||
* cpu_relax is an architecture specific method of telling the CPU that you don't want it to
|
||||
* do much work. asm volatile keeps the compiler from optimising these instructions out.
|
||||
*/
|
||||
#if defined(__i386__) || defined(__x86_64__)
|
||||
#define cpu_relax() asm volatile("rep; nop" ::: "memory");
|
||||
|
||||
#elif defined(__arm__) || defined(__mips__) || defined(__riscv)
|
||||
#define cpu_relax() asm volatile("":::"memory")
|
||||
|
||||
#elif defined(__aarch64__)
|
||||
#define cpu_relax() asm volatile("yield" ::: "memory")
|
||||
|
||||
#else
|
||||
#error "cpu_relax is not defined for this architecture"
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
#endif //OBOE_STABILIZEDCALLBACK_H
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_UTILITIES_H
|
||||
#define OBOE_UTILITIES_H
|
||||
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <string>
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* Convert an array of floats to an array of 16-bit integers.
|
||||
*
|
||||
* @param source the input array.
|
||||
* @param destination the output array.
|
||||
* @param numSamples the number of values to convert.
|
||||
*/
|
||||
void convertFloatToPcm16(const float *source, int16_t *destination, int32_t numSamples);
|
||||
|
||||
/**
|
||||
* Convert an array of 16-bit integers to an array of floats.
|
||||
*
|
||||
* @param source the input array.
|
||||
* @param destination the output array.
|
||||
* @param numSamples the number of values to convert.
|
||||
*/
|
||||
void convertPcm16ToFloat(const int16_t *source, float *destination, int32_t numSamples);
|
||||
|
||||
/**
|
||||
* @return the size of a sample of the given format in bytes or 0 if format is invalid
|
||||
*/
|
||||
int32_t convertFormatToSizeInBytes(AudioFormat format);
|
||||
|
||||
/**
|
||||
* The text is the ASCII symbol corresponding to the supplied Oboe enum value,
|
||||
* or an English message saying the value is unrecognized.
|
||||
* This is intended for developers to use when debugging.
|
||||
* It is not for displaying to users.
|
||||
*
|
||||
* @param input object to convert from. @see common/Utilities.cpp for concrete implementations
|
||||
* @return text representation of an Oboe enum value. There is no need to call free on this.
|
||||
*/
|
||||
template <typename FromType>
|
||||
const char * convertToText(FromType input);
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @return the value of a named system property in a string or empty string
|
||||
*/
|
||||
std::string getPropertyString(const char * name);
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @param defaultValue
|
||||
* @return integer value associated with a property or the default value
|
||||
*/
|
||||
int getPropertyInteger(const char * name, int defaultValue);
|
||||
|
||||
/**
|
||||
* Return the version of the SDK that is currently running.
|
||||
*
|
||||
* For example, on Android, this would return 27 for Oreo 8.1.
|
||||
* If the version number cannot be determined then this will return -1.
|
||||
*
|
||||
* @return version number or -1
|
||||
*/
|
||||
int getSdkVersion();
|
||||
|
||||
/**
|
||||
* Returns whether a device is on a pre-release SDK that is at least the specified codename
|
||||
* version.
|
||||
*
|
||||
* @param codename the code name to verify.
|
||||
* @return boolean of whether the device is on a pre-release SDK and is at least the specified
|
||||
* codename
|
||||
*/
|
||||
bool isAtLeastPreReleaseCodename(const std::string& codename);
|
||||
|
||||
int getChannelCountFromChannelMask(ChannelMask channelMask);
|
||||
|
||||
bool isCompressedFormat(AudioFormat format);
|
||||
|
||||
std::string toString(const PlaybackParameters& parameters);
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_UTILITIES_H
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2017 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_VERSIONINFO_H
|
||||
#define OBOE_VERSIONINFO_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
/**
|
||||
* A note on use of preprocessor defines:
|
||||
*
|
||||
* This is one of the few times when it's suitable to use preprocessor defines rather than constexpr
|
||||
* Why? Because C++11 requires a lot of boilerplate code to convert integers into compile-time
|
||||
* string literals. The preprocessor, despite it's lack of type checking, is more suited to the task
|
||||
*
|
||||
* See: https://stackoverflow.com/questions/6713420/c-convert-integer-to-string-at-compile-time/26824971#26824971
|
||||
*
|
||||
*/
|
||||
|
||||
// Type: 8-bit unsigned int. Min value: 0 Max value: 255. See below for description.
|
||||
#define OBOE_VERSION_MAJOR 1
|
||||
|
||||
// Type: 8-bit unsigned int. Min value: 0 Max value: 255. See below for description.
|
||||
#define OBOE_VERSION_MINOR 10
|
||||
|
||||
// Type: 16-bit unsigned int. Min value: 0 Max value: 65535. See below for description.
|
||||
#define OBOE_VERSION_PATCH 0
|
||||
|
||||
#define OBOE_STRINGIFY(x) #x
|
||||
#define OBOE_TOSTRING(x) OBOE_STRINGIFY(x)
|
||||
|
||||
// Type: String literal. See below for description.
|
||||
#define OBOE_VERSION_TEXT \
|
||||
OBOE_TOSTRING(OBOE_VERSION_MAJOR) "." \
|
||||
OBOE_TOSTRING(OBOE_VERSION_MINOR) "." \
|
||||
OBOE_TOSTRING(OBOE_VERSION_PATCH)
|
||||
|
||||
// Type: 32-bit unsigned int. See below for description.
|
||||
#define OBOE_VERSION_NUMBER ((OBOE_VERSION_MAJOR << 24) | (OBOE_VERSION_MINOR << 16) | OBOE_VERSION_PATCH)
|
||||
|
||||
namespace oboe {
|
||||
|
||||
const char * getVersionText();
|
||||
|
||||
/**
|
||||
* Oboe versioning object
|
||||
*/
|
||||
struct Version {
|
||||
/**
|
||||
* This is incremented when we make breaking API changes. Based loosely on https://semver.org/.
|
||||
*/
|
||||
static constexpr uint8_t Major = OBOE_VERSION_MAJOR;
|
||||
|
||||
/**
|
||||
* This is incremented when we add backwards compatible functionality. Or set to zero when MAJOR is
|
||||
* incremented.
|
||||
*/
|
||||
static constexpr uint8_t Minor = OBOE_VERSION_MINOR;
|
||||
|
||||
/**
|
||||
* This is incremented when we make backwards compatible bug fixes. Or set to zero when MINOR is
|
||||
* incremented.
|
||||
*/
|
||||
static constexpr uint16_t Patch = OBOE_VERSION_PATCH;
|
||||
|
||||
/**
|
||||
* Version string in the form MAJOR.MINOR.PATCH.
|
||||
*/
|
||||
static constexpr const char * Text = OBOE_VERSION_TEXT;
|
||||
|
||||
/**
|
||||
* Integer representation of the current Oboe library version. This will always increase when the
|
||||
* version number changes so can be compared using integer comparison.
|
||||
*/
|
||||
static constexpr uint32_t Number = OBOE_VERSION_NUMBER;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
#endif //OBOE_VERSIONINFO_H
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
* Copyright 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_AAUDIO_EXTENSIONS_H
|
||||
#define OBOE_AAUDIO_EXTENSIONS_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <dlfcn.h>
|
||||
#include <set>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <sys/system_properties.h>
|
||||
|
||||
#include "common/OboeDebug.h"
|
||||
#include "oboe/Oboe.h"
|
||||
#include "AAudioLoader.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
#define LIB_AAUDIO_NAME "libaaudio.so"
|
||||
#define FUNCTION_IS_MMAP "AAudioStream_isMMapUsed"
|
||||
#define FUNCTION_SET_MMAP_POLICY "AAudio_setMMapPolicy"
|
||||
#define FUNCTION_GET_MMAP_POLICY "AAudio_getMMapPolicy"
|
||||
|
||||
#define AAUDIO_ERROR_UNAVAILABLE static_cast<aaudio_result_t>(Result::ErrorUnavailable)
|
||||
|
||||
typedef struct AAudioStreamStruct AAudioStream;
|
||||
|
||||
// The output device type collection must be updated if there is any new added output device type
|
||||
const static std::set<DeviceType> ALL_OUTPUT_DEVICE_TYPES = {
|
||||
DeviceType::BuiltinEarpiece,
|
||||
DeviceType::BuiltinSpeaker,
|
||||
DeviceType::WiredHeadset,
|
||||
DeviceType::WiredHeadphones,
|
||||
DeviceType::LineAnalog,
|
||||
DeviceType::LineDigital,
|
||||
DeviceType::BluetoothSco,
|
||||
DeviceType::BluetoothA2dp,
|
||||
DeviceType::Hdmi,
|
||||
DeviceType::HdmiArc,
|
||||
DeviceType::HdmiEarc,
|
||||
DeviceType::UsbDevice,
|
||||
DeviceType::UsbHeadset,
|
||||
DeviceType::UsbAccessory,
|
||||
DeviceType::Dock,
|
||||
DeviceType::DockAnalog,
|
||||
DeviceType::FM,
|
||||
DeviceType::Telephony,
|
||||
DeviceType::AuxLine,
|
||||
DeviceType::IP,
|
||||
DeviceType::Bus,
|
||||
DeviceType::HearingAid,
|
||||
DeviceType::BuiltinSpeakerSafe,
|
||||
DeviceType::RemoteSubmix,
|
||||
DeviceType::BleHeadset,
|
||||
DeviceType::BleSpeaker,
|
||||
DeviceType::BleBroadcast,
|
||||
};
|
||||
|
||||
// The input device type collection must be updated if there is any new added input device type
|
||||
const static std::set<DeviceType> ALL_INPUT_DEVICE_TYPES = {
|
||||
DeviceType::BuiltinMic,
|
||||
DeviceType::BluetoothSco,
|
||||
DeviceType::WiredHeadset,
|
||||
DeviceType::Hdmi,
|
||||
DeviceType::Telephony,
|
||||
DeviceType::Dock,
|
||||
DeviceType::DockAnalog,
|
||||
DeviceType::UsbAccessory,
|
||||
DeviceType::UsbDevice,
|
||||
DeviceType::UsbHeadset,
|
||||
DeviceType::FMTuner,
|
||||
DeviceType::TVTuner,
|
||||
DeviceType::LineAnalog,
|
||||
DeviceType::LineDigital,
|
||||
DeviceType::BluetoothA2dp,
|
||||
DeviceType::IP,
|
||||
DeviceType::Bus,
|
||||
DeviceType::RemoteSubmix,
|
||||
DeviceType::BleHeadset,
|
||||
DeviceType::HdmiArc,
|
||||
DeviceType::HdmiEarc,
|
||||
};
|
||||
|
||||
/**
|
||||
* Call some AAudio test routines that are not part of the normal API.
|
||||
*/
|
||||
class AAudioExtensions {
|
||||
private: // Because it is a singleton. Call getInstance() instead.
|
||||
AAudioExtensions() {
|
||||
mLibLoader = AAudioLoader::getInstance();
|
||||
if (!initMMapPolicy()) {
|
||||
int32_t policy = getIntegerProperty("aaudio.mmap_policy", 0);
|
||||
mMMapSupported = isPolicyEnabled(policy);
|
||||
|
||||
policy = getIntegerProperty("aaudio.mmap_exclusive_policy", 0);
|
||||
mMMapExclusiveSupported = isPolicyEnabled(policy);
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
static bool isPolicyEnabled(int32_t policy) {
|
||||
const MMapPolicy mmapPolicy = static_cast<MMapPolicy>(policy);
|
||||
return (mmapPolicy == MMapPolicy::Auto || mmapPolicy == MMapPolicy::Always);
|
||||
}
|
||||
|
||||
static AAudioExtensions &getInstance() {
|
||||
static AAudioExtensions instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
bool isMMapUsed(oboe::AudioStream *oboeStream) {
|
||||
AAudioStream *aaudioStream = (AAudioStream *) oboeStream->getUnderlyingStream();
|
||||
return isMMapUsed(aaudioStream);
|
||||
}
|
||||
|
||||
bool isMMapUsed(AAudioStream *aaudioStream) {
|
||||
if (mLibLoader != nullptr && mLibLoader->stream_isMMapUsed != nullptr) {
|
||||
return mLibLoader->stream_isMMapUsed(aaudioStream);
|
||||
}
|
||||
if (loadSymbols()) return false;
|
||||
if (mAAudioStream_isMMap == nullptr) return false;
|
||||
return mAAudioStream_isMMap(aaudioStream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls whether the MMAP data path can be selected when opening a stream.
|
||||
* It has no effect after the stream has been opened.
|
||||
* It only affects the application that calls it. Other apps are not affected.
|
||||
*
|
||||
* @param enabled
|
||||
* @return 0 or a negative error code
|
||||
*/
|
||||
int32_t setMMapEnabled(bool enabled) {
|
||||
// The API for setting mmap policy is public after API level 36.
|
||||
if (mLibLoader != nullptr && mLibLoader->aaudio_setMMapPolicy != nullptr) {
|
||||
return mLibLoader->aaudio_setMMapPolicy(
|
||||
static_cast<aaudio_policy_t>(enabled ? MMapPolicy::Auto : MMapPolicy::Never));
|
||||
}
|
||||
// When there is no public API, fallback to loading the symbol from hidden API.
|
||||
if (loadSymbols()) return AAUDIO_ERROR_UNAVAILABLE;
|
||||
if (mAAudio_setMMapPolicy == nullptr) return false;
|
||||
return mAAudio_setMMapPolicy(
|
||||
static_cast<int32_t>(enabled ? MMapPolicy::Auto : MMapPolicy::Never));
|
||||
}
|
||||
|
||||
bool isMMapEnabled() {
|
||||
// The API for getting mmap policy is public after API level 36.
|
||||
// Use it when it is available.
|
||||
if (mLibLoader != nullptr && mLibLoader->aaudio_getMMapPolicy != nullptr) {
|
||||
MMapPolicy policy = static_cast<MMapPolicy>(mLibLoader->aaudio_getMMapPolicy());
|
||||
return policy == MMapPolicy::Unspecified
|
||||
? mMMapSupported : isPolicyEnabled(static_cast<int32_t>(policy));
|
||||
}
|
||||
// When there is no public API, fallback to loading the symbol from hidden API.
|
||||
if (loadSymbols()) return false;
|
||||
if (mAAudio_getMMapPolicy == nullptr) return false;
|
||||
int32_t policy = mAAudio_getMMapPolicy();
|
||||
return (policy == Unspecified) ? mMMapSupported : isPolicyEnabled(policy);
|
||||
}
|
||||
|
||||
bool isMMapSupported() {
|
||||
return mMMapSupported;
|
||||
}
|
||||
|
||||
bool isMMapExclusiveSupported() {
|
||||
return mMMapExclusiveSupported;
|
||||
}
|
||||
|
||||
MMapPolicy getMMapPolicy(DeviceType deviceType, Direction direction) {
|
||||
if (mLibLoader == nullptr ||
|
||||
mLibLoader->aaudio_getPlatformMMapPolicy == nullptr) {
|
||||
return MMapPolicy::Unspecified;
|
||||
}
|
||||
return static_cast<MMapPolicy>(mLibLoader->aaudio_getPlatformMMapPolicy(
|
||||
static_cast<AAudio_DeviceType>(deviceType),
|
||||
static_cast<aaudio_direction_t>(direction)));
|
||||
}
|
||||
|
||||
MMapPolicy getMMapExclusivePolicy(DeviceType deviceType, Direction direction) {
|
||||
if (mLibLoader == nullptr ||
|
||||
mLibLoader->aaudio_getPlatformMMapExclusivePolicy == nullptr) {
|
||||
return MMapPolicy::Unspecified;
|
||||
}
|
||||
return static_cast<MMapPolicy>(mLibLoader->aaudio_getPlatformMMapExclusivePolicy(
|
||||
static_cast<AAudio_DeviceType>(deviceType),
|
||||
static_cast<aaudio_direction_t>(direction)));
|
||||
}
|
||||
|
||||
bool isPartialDataCallbackSupported() {
|
||||
return mLibLoader != nullptr && mLibLoader->builder_setPartialDataCallback != nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
bool initMMapPolicy() {
|
||||
if (mLibLoader == nullptr || mLibLoader->open() != 0) {
|
||||
return false;
|
||||
}
|
||||
if (mLibLoader->aaudio_getPlatformMMapPolicy == nullptr ||
|
||||
mLibLoader->aaudio_getPlatformMMapExclusivePolicy == nullptr) {
|
||||
return false;
|
||||
}
|
||||
mMMapSupported =
|
||||
std::any_of(ALL_INPUT_DEVICE_TYPES.begin(), ALL_INPUT_DEVICE_TYPES.end(),
|
||||
[this](DeviceType deviceType) {
|
||||
return isPolicyEnabled(static_cast<int32_t>(
|
||||
getMMapPolicy(deviceType, Direction::Input)));
|
||||
}) ||
|
||||
std::any_of(ALL_OUTPUT_DEVICE_TYPES.begin(), ALL_OUTPUT_DEVICE_TYPES.end(),
|
||||
[this](DeviceType deviceType) {
|
||||
return isPolicyEnabled(static_cast<int32_t>(
|
||||
getMMapPolicy(deviceType, Direction::Output)));
|
||||
});
|
||||
mMMapExclusiveSupported =
|
||||
std::any_of(ALL_INPUT_DEVICE_TYPES.begin(), ALL_INPUT_DEVICE_TYPES.end(),
|
||||
[this](DeviceType deviceType) {
|
||||
return isPolicyEnabled(static_cast<int32_t>(
|
||||
getMMapExclusivePolicy(deviceType, Direction::Input)));
|
||||
}) ||
|
||||
std::any_of(ALL_OUTPUT_DEVICE_TYPES.begin(), ALL_OUTPUT_DEVICE_TYPES.end(),
|
||||
[this](DeviceType deviceType) {
|
||||
return isPolicyEnabled(static_cast<int32_t>(
|
||||
getMMapExclusivePolicy(deviceType, Direction::Output)));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
int getIntegerProperty(const char *name, int defaultValue) {
|
||||
int result = defaultValue;
|
||||
char valueText[PROP_VALUE_MAX] = {0};
|
||||
if (__system_property_get(name, valueText) != 0) {
|
||||
result = atoi(valueText);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the function pointers.
|
||||
* This can be called multiple times.
|
||||
* It should only be called from one thread.
|
||||
*
|
||||
* @return 0 if successful or negative error.
|
||||
*/
|
||||
aaudio_result_t loadSymbols() {
|
||||
if (mAAudio_getMMapPolicy != nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (mLibLoader == nullptr || mLibLoader->open() != 0) {
|
||||
LOGD("%s() could not open " LIB_AAUDIO_NAME, __func__);
|
||||
return AAUDIO_ERROR_UNAVAILABLE;
|
||||
}
|
||||
|
||||
void *libHandle = mLibLoader->getLibHandle();
|
||||
if (libHandle == nullptr) {
|
||||
LOGE("%s() could not find " LIB_AAUDIO_NAME, __func__);
|
||||
return AAUDIO_ERROR_UNAVAILABLE;
|
||||
}
|
||||
|
||||
mAAudioStream_isMMap = (bool (*)(AAudioStream *stream))
|
||||
dlsym(libHandle, FUNCTION_IS_MMAP);
|
||||
if (mAAudioStream_isMMap == nullptr) {
|
||||
LOGI("%s() could not find " FUNCTION_IS_MMAP, __func__);
|
||||
return AAUDIO_ERROR_UNAVAILABLE;
|
||||
}
|
||||
|
||||
mAAudio_setMMapPolicy = (int32_t (*)(aaudio_policy_t policy))
|
||||
dlsym(libHandle, FUNCTION_SET_MMAP_POLICY);
|
||||
if (mAAudio_setMMapPolicy == nullptr) {
|
||||
LOGI("%s() could not find " FUNCTION_SET_MMAP_POLICY, __func__);
|
||||
return AAUDIO_ERROR_UNAVAILABLE;
|
||||
}
|
||||
|
||||
mAAudio_getMMapPolicy = (aaudio_policy_t (*)())
|
||||
dlsym(libHandle, FUNCTION_GET_MMAP_POLICY);
|
||||
if (mAAudio_getMMapPolicy == nullptr) {
|
||||
LOGI("%s() could not find " FUNCTION_GET_MMAP_POLICY, __func__);
|
||||
return AAUDIO_ERROR_UNAVAILABLE;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool mMMapSupported = false;
|
||||
bool mMMapExclusiveSupported = false;
|
||||
|
||||
bool (*mAAudioStream_isMMap)(AAudioStream *stream) = nullptr;
|
||||
int32_t (*mAAudio_setMMapPolicy)(aaudio_policy_t policy) = nullptr;
|
||||
aaudio_policy_t (*mAAudio_getMMapPolicy)() = nullptr;
|
||||
|
||||
AAudioLoader *mLibLoader;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_AAUDIO_EXTENSIONS_H
|
||||
+634
@@ -0,0 +1,634 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <oboe/Utilities.h>
|
||||
#include "common/OboeDebug.h"
|
||||
#include "AAudioLoader.h"
|
||||
|
||||
#define LIB_AAUDIO_NAME "libaaudio.so"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
AAudioLoader::~AAudioLoader() {
|
||||
// Issue 360: thread_local variables with non-trivial destructors
|
||||
// will cause segfaults if the containing library is dlclose()ed on
|
||||
// devices running M or newer, or devices before M when using a static STL.
|
||||
// The simple workaround is to not call dlclose.
|
||||
// https://github.com/android/ndk/wiki/Changelog-r22#known-issues
|
||||
//
|
||||
// The libaaudio and libaaudioclient do not use thread_local.
|
||||
// But, to be safe, we should avoid dlclose() if possible.
|
||||
// Because AAudioLoader is a static Singleton, we can safely skip
|
||||
// calling dlclose() without causing a resource leak.
|
||||
LOGI("%s() dlclose(%s) not called, OK", __func__, LIB_AAUDIO_NAME);
|
||||
}
|
||||
|
||||
AAudioLoader* AAudioLoader::getInstance() {
|
||||
static AAudioLoader instance;
|
||||
return &instance;
|
||||
}
|
||||
|
||||
int AAudioLoader::open() {
|
||||
if (mLibHandle != nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Use RTLD_NOW to avoid the unpredictable behavior that RTLD_LAZY can cause.
|
||||
// Also resolving all the links now will prevent a run-time penalty later.
|
||||
mLibHandle = dlopen(LIB_AAUDIO_NAME, RTLD_NOW);
|
||||
if (mLibHandle == nullptr) {
|
||||
LOGI("AAudioLoader::open() could not find " LIB_AAUDIO_NAME);
|
||||
return -1; // TODO review return code
|
||||
} else {
|
||||
LOGD("AAudioLoader(): dlopen(%s) returned %p", LIB_AAUDIO_NAME, mLibHandle);
|
||||
}
|
||||
|
||||
// Load all the function pointers.
|
||||
createStreamBuilder = load_I_PPB("AAudio_createStreamBuilder");
|
||||
builder_openStream = load_I_PBPPS("AAudioStreamBuilder_openStream");
|
||||
|
||||
builder_setChannelCount = load_V_PBI("AAudioStreamBuilder_setChannelCount");
|
||||
if (builder_setChannelCount == nullptr) {
|
||||
// Use old deprecated alias if needed.
|
||||
builder_setChannelCount = load_V_PBI("AAudioStreamBuilder_setSamplesPerFrame");
|
||||
}
|
||||
|
||||
builder_setBufferCapacityInFrames = load_V_PBI("AAudioStreamBuilder_setBufferCapacityInFrames");
|
||||
builder_setDeviceId = load_V_PBI("AAudioStreamBuilder_setDeviceId");
|
||||
builder_setDirection = load_V_PBI("AAudioStreamBuilder_setDirection");
|
||||
builder_setFormat = load_V_PBI("AAudioStreamBuilder_setFormat");
|
||||
builder_setFramesPerDataCallback = load_V_PBI("AAudioStreamBuilder_setFramesPerDataCallback");
|
||||
builder_setSharingMode = load_V_PBI("AAudioStreamBuilder_setSharingMode");
|
||||
builder_setPerformanceMode = load_V_PBI("AAudioStreamBuilder_setPerformanceMode");
|
||||
builder_setSampleRate = load_V_PBI("AAudioStreamBuilder_setSampleRate");
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_P__){
|
||||
builder_setUsage = load_V_PBI("AAudioStreamBuilder_setUsage");
|
||||
builder_setContentType = load_V_PBI("AAudioStreamBuilder_setContentType");
|
||||
builder_setInputPreset = load_V_PBI("AAudioStreamBuilder_setInputPreset");
|
||||
builder_setSessionId = load_V_PBI("AAudioStreamBuilder_setSessionId");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_Q__){
|
||||
builder_setAllowedCapturePolicy = load_V_PBI("AAudioStreamBuilder_setAllowedCapturePolicy");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_R__){
|
||||
builder_setPrivacySensitive = load_V_PBO("AAudioStreamBuilder_setPrivacySensitive");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_S__){
|
||||
builder_setPackageName = load_V_PBCPH("AAudioStreamBuilder_setPackageName");
|
||||
builder_setAttributionTag = load_V_PBCPH("AAudioStreamBuilder_setAttributionTag");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_S_V2__) {
|
||||
builder_setChannelMask = load_V_PBU("AAudioStreamBuilder_setChannelMask");
|
||||
builder_setIsContentSpatialized = load_V_PBO("AAudioStreamBuilder_setIsContentSpatialized");
|
||||
builder_setSpatializationBehavior = load_V_PBI("AAudioStreamBuilder_setSpatializationBehavior");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_B__) {
|
||||
builder_setPresentationEndCallback = load_V_PBPRPV("AAudioStreamBuilder_setPresentationEndCallback");
|
||||
}
|
||||
|
||||
builder_delete = load_I_PB("AAudioStreamBuilder_delete");
|
||||
|
||||
|
||||
builder_setDataCallback = load_V_PBPDPV("AAudioStreamBuilder_setDataCallback");
|
||||
builder_setErrorCallback = load_V_PBPEPV("AAudioStreamBuilder_setErrorCallback");
|
||||
|
||||
stream_read = load_I_PSPVIL("AAudioStream_read");
|
||||
|
||||
stream_write = load_I_PSCPVIL("AAudioStream_write");
|
||||
|
||||
stream_waitForStateChange = load_I_PSTPTL("AAudioStream_waitForStateChange");
|
||||
|
||||
stream_getTimestamp = load_I_PSKPLPL("AAudioStream_getTimestamp");
|
||||
|
||||
stream_getChannelCount = load_I_PS("AAudioStream_getChannelCount");
|
||||
if (stream_getChannelCount == nullptr) {
|
||||
// Use old alias if needed.
|
||||
stream_getChannelCount = load_I_PS("AAudioStream_getSamplesPerFrame");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_R__) {
|
||||
stream_release = load_I_PS("AAudioStream_release");
|
||||
}
|
||||
|
||||
stream_close = load_I_PS("AAudioStream_close");
|
||||
|
||||
stream_getBufferSize = load_I_PS("AAudioStream_getBufferSizeInFrames");
|
||||
stream_getDeviceId = load_I_PS("AAudioStream_getDeviceId");
|
||||
stream_getBufferCapacity = load_I_PS("AAudioStream_getBufferCapacityInFrames");
|
||||
stream_getFormat = load_F_PS("AAudioStream_getFormat");
|
||||
stream_getFramesPerBurst = load_I_PS("AAudioStream_getFramesPerBurst");
|
||||
stream_getFramesRead = load_L_PS("AAudioStream_getFramesRead");
|
||||
stream_getFramesWritten = load_L_PS("AAudioStream_getFramesWritten");
|
||||
stream_getPerformanceMode = load_I_PS("AAudioStream_getPerformanceMode");
|
||||
stream_getSampleRate = load_I_PS("AAudioStream_getSampleRate");
|
||||
stream_getSharingMode = load_I_PS("AAudioStream_getSharingMode");
|
||||
stream_getState = load_I_PS("AAudioStream_getState");
|
||||
stream_getXRunCount = load_I_PS("AAudioStream_getXRunCount");
|
||||
|
||||
stream_requestStart = load_I_PS("AAudioStream_requestStart");
|
||||
stream_requestPause = load_I_PS("AAudioStream_requestPause");
|
||||
stream_requestFlush = load_I_PS("AAudioStream_requestFlush");
|
||||
stream_requestStop = load_I_PS("AAudioStream_requestStop");
|
||||
|
||||
stream_setBufferSize = load_I_PSI("AAudioStream_setBufferSizeInFrames");
|
||||
|
||||
convertResultToText = load_CPH_I("AAudio_convertResultToText");
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_P__){
|
||||
stream_getUsage = load_I_PS("AAudioStream_getUsage");
|
||||
stream_getContentType = load_I_PS("AAudioStream_getContentType");
|
||||
stream_getInputPreset = load_I_PS("AAudioStream_getInputPreset");
|
||||
stream_getSessionId = load_I_PS("AAudioStream_getSessionId");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_Q__){
|
||||
stream_getAllowedCapturePolicy = load_I_PS("AAudioStream_getAllowedCapturePolicy");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_R__){
|
||||
stream_isPrivacySensitive = load_O_PS("AAudioStream_isPrivacySensitive");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_S_V2__) {
|
||||
stream_getChannelMask = load_U_PS("AAudioStream_getChannelMask");
|
||||
stream_isContentSpatialized = load_O_PS("AAudioStream_isContentSpatialized");
|
||||
stream_getSpatializationBehavior = load_I_PS("AAudioStream_getSpatializationBehavior");
|
||||
}
|
||||
|
||||
if (getSdkVersion() >= __ANDROID_API_U__) {
|
||||
stream_getHardwareChannelCount = load_I_PS("AAudioStream_getHardwareChannelCount");
|
||||
stream_getHardwareSampleRate = load_I_PS("AAudioStream_getHardwareSampleRate");
|
||||
stream_getHardwareFormat = load_F_PS("AAudioStream_getHardwareFormat");
|
||||
}
|
||||
|
||||
// TODO: Remove pre-release check after Android B release
|
||||
if (getSdkVersion() >= __ANDROID_API_B__ || isAtLeastPreReleaseCodename("Baklava")) {
|
||||
aaudio_getPlatformMMapPolicy = load_I_II("AAudio_getPlatformMMapPolicy");
|
||||
aaudio_getPlatformMMapExclusivePolicy = load_I_II("AAudio_getPlatformMMapExclusivePolicy");
|
||||
aaudio_setMMapPolicy = load_I_I("AAudio_setMMapPolicy");
|
||||
aaudio_getMMapPolicy = load_I("AAudio_getMMapPolicy");
|
||||
stream_isMMapUsed = load_O_PS("AAudioStream_isMMapUsed");
|
||||
|
||||
stream_setOffloadDelayPadding = load_I_PSII("AAudioStream_setOffloadDelayPadding");
|
||||
stream_getOffloadDelay = load_I_PS("AAudioStream_getOffloadDelay");
|
||||
stream_getOffloadPadding = load_I_PS("AAudioStream_getOffloadPadding");
|
||||
stream_setOffloadEndOfStream = load_I_PS("AAudioStream_setOffloadEndOfStream");
|
||||
|
||||
stream_getDeviceIds = load_I_PSPIPI("AAudioStream_getDeviceIds");
|
||||
|
||||
// TODO: Use 25Q4 version code and name when it is defined.
|
||||
stream_flushFromFrame = load_I_PSIPL("AAudioStream_flushFromFrame");
|
||||
stream_getPlaybackParameters =
|
||||
load_I_PSPM("AAudioStream_getPlaybackParameters");
|
||||
stream_setPlaybackParameters =
|
||||
load_I_PSCPM("AAudioStream_setPlaybackParameters");
|
||||
|
||||
builder_setPartialDataCallback =
|
||||
load_V_PBPDPV("AAudioStreamBuilder_setPartialDataCallback");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void AAudioLoader_check(void *proc, const char *functionName) {
|
||||
if (proc == nullptr) {
|
||||
LOGW("AAudioLoader could not find %s", functionName);
|
||||
}
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PPB AAudioLoader::load_I_PPB(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PPB>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_CPH_I AAudioLoader::load_CPH_I(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_CPH_I>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBI AAudioLoader::load_V_PBI(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBI>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBCPH AAudioLoader::load_V_PBCPH(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBCPH>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBPDPV AAudioLoader::load_V_PBPDPV(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBPDPV>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBPEPV AAudioLoader::load_V_PBPEPV(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBPEPV>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSI AAudioLoader::load_I_PSI(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSI>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PS AAudioLoader::load_I_PS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_L_PS AAudioLoader::load_L_PS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_L_PS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_F_PS AAudioLoader::load_F_PS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_F_PS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_O_PS AAudioLoader::load_O_PS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_O_PS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PB AAudioLoader::load_I_PB(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PB>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PBPPS AAudioLoader::load_I_PBPPS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PBPPS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSCPVIL AAudioLoader::load_I_PSCPVIL(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSCPVIL>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSPVIL AAudioLoader::load_I_PSPVIL(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSPVIL>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSTPTL AAudioLoader::load_I_PSTPTL(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSTPTL>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSKPLPL AAudioLoader::load_I_PSKPLPL(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSKPLPL>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBU AAudioLoader::load_V_PBU(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBU>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_U_PS AAudioLoader::load_U_PS(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_U_PS>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBO AAudioLoader::load_V_PBO(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBO>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_II AAudioLoader::load_I_II(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_II>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_I AAudioLoader::load_I_I(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_I>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I AAudioLoader::load_I(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_V_PBPRPV AAudioLoader::load_V_PBPRPV(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_V_PBPRPV>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSII AAudioLoader::load_I_PSII(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSII>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSPIPI AAudioLoader::load_I_PSPIPI(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSPIPI>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSIPL AAudioLoader::load_I_PSIPL(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSIPL>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSPM AAudioLoader::load_I_PSPM(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSPM>(proc);
|
||||
}
|
||||
|
||||
AAudioLoader::signature_I_PSCPM AAudioLoader::load_I_PSCPM(const char *functionName) {
|
||||
void *proc = dlsym(mLibHandle, functionName);
|
||||
AAudioLoader_check(proc, functionName);
|
||||
return reinterpret_cast<signature_I_PSCPM>(proc);
|
||||
}
|
||||
|
||||
// Ensure that all AAudio primitive data types are int32_t
|
||||
#define ASSERT_INT32(type) static_assert(std::is_same<int32_t, type>::value, \
|
||||
#type" must be int32_t")
|
||||
|
||||
// Ensure that all AAudio primitive data types are uint32_t
|
||||
#define ASSERT_UINT32(type) static_assert(std::is_same<uint32_t, type>::value, \
|
||||
#type" must be uint32_t")
|
||||
|
||||
#define ERRMSG "Oboe constants must match AAudio constants."
|
||||
|
||||
// These asserts help verify that the Oboe definitions match the equivalent AAudio definitions.
|
||||
// This code is in this .cpp file so it only gets tested once.
|
||||
#ifdef AAUDIO_AAUDIO_H
|
||||
|
||||
ASSERT_INT32(aaudio_stream_state_t);
|
||||
ASSERT_INT32(aaudio_direction_t);
|
||||
ASSERT_INT32(aaudio_format_t);
|
||||
ASSERT_INT32(aaudio_data_callback_result_t);
|
||||
ASSERT_INT32(aaudio_result_t);
|
||||
ASSERT_INT32(aaudio_sharing_mode_t);
|
||||
ASSERT_INT32(aaudio_performance_mode_t);
|
||||
|
||||
static_assert((int32_t)StreamState::Uninitialized == AAUDIO_STREAM_STATE_UNINITIALIZED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Unknown == AAUDIO_STREAM_STATE_UNKNOWN, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Open == AAUDIO_STREAM_STATE_OPEN, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Starting == AAUDIO_STREAM_STATE_STARTING, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Started == AAUDIO_STREAM_STATE_STARTED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Pausing == AAUDIO_STREAM_STATE_PAUSING, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Paused == AAUDIO_STREAM_STATE_PAUSED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Flushing == AAUDIO_STREAM_STATE_FLUSHING, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Flushed == AAUDIO_STREAM_STATE_FLUSHED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Stopping == AAUDIO_STREAM_STATE_STOPPING, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Stopped == AAUDIO_STREAM_STATE_STOPPED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Closing == AAUDIO_STREAM_STATE_CLOSING, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Closed == AAUDIO_STREAM_STATE_CLOSED, ERRMSG);
|
||||
static_assert((int32_t)StreamState::Disconnected == AAUDIO_STREAM_STATE_DISCONNECTED, ERRMSG);
|
||||
|
||||
static_assert((int32_t)Direction::Output == AAUDIO_DIRECTION_OUTPUT, ERRMSG);
|
||||
static_assert((int32_t)Direction::Input == AAUDIO_DIRECTION_INPUT, ERRMSG);
|
||||
|
||||
static_assert((int32_t)AudioFormat::Invalid == AAUDIO_FORMAT_INVALID, ERRMSG);
|
||||
static_assert((int32_t)AudioFormat::Unspecified == AAUDIO_FORMAT_UNSPECIFIED, ERRMSG);
|
||||
static_assert((int32_t)AudioFormat::I16 == AAUDIO_FORMAT_PCM_I16, ERRMSG);
|
||||
static_assert((int32_t)AudioFormat::Float == AAUDIO_FORMAT_PCM_FLOAT, ERRMSG);
|
||||
|
||||
static_assert((int32_t)DataCallbackResult::Continue == AAUDIO_CALLBACK_RESULT_CONTINUE, ERRMSG);
|
||||
static_assert((int32_t)DataCallbackResult::Stop == AAUDIO_CALLBACK_RESULT_STOP, ERRMSG);
|
||||
|
||||
static_assert((int32_t)Result::OK == AAUDIO_OK, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorBase == AAUDIO_ERROR_BASE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorDisconnected == AAUDIO_ERROR_DISCONNECTED, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorIllegalArgument == AAUDIO_ERROR_ILLEGAL_ARGUMENT, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorInternal == AAUDIO_ERROR_INTERNAL, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorInvalidState == AAUDIO_ERROR_INVALID_STATE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorInvalidHandle == AAUDIO_ERROR_INVALID_HANDLE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorUnimplemented == AAUDIO_ERROR_UNIMPLEMENTED, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorUnavailable == AAUDIO_ERROR_UNAVAILABLE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorNoFreeHandles == AAUDIO_ERROR_NO_FREE_HANDLES, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorNoMemory == AAUDIO_ERROR_NO_MEMORY, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorNull == AAUDIO_ERROR_NULL, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorTimeout == AAUDIO_ERROR_TIMEOUT, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorWouldBlock == AAUDIO_ERROR_WOULD_BLOCK, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorInvalidFormat == AAUDIO_ERROR_INVALID_FORMAT, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorOutOfRange == AAUDIO_ERROR_OUT_OF_RANGE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorNoService == AAUDIO_ERROR_NO_SERVICE, ERRMSG);
|
||||
static_assert((int32_t)Result::ErrorInvalidRate == AAUDIO_ERROR_INVALID_RATE, ERRMSG);
|
||||
|
||||
static_assert((int32_t)SharingMode::Exclusive == AAUDIO_SHARING_MODE_EXCLUSIVE, ERRMSG);
|
||||
static_assert((int32_t)SharingMode::Shared == AAUDIO_SHARING_MODE_SHARED, ERRMSG);
|
||||
|
||||
static_assert((int32_t)PerformanceMode::None == AAUDIO_PERFORMANCE_MODE_NONE, ERRMSG);
|
||||
static_assert((int32_t)PerformanceMode::PowerSaving
|
||||
== AAUDIO_PERFORMANCE_MODE_POWER_SAVING, ERRMSG);
|
||||
static_assert((int32_t)PerformanceMode::LowLatency
|
||||
== AAUDIO_PERFORMANCE_MODE_LOW_LATENCY, ERRMSG);
|
||||
|
||||
// The aaudio_ usage, content and input_preset types were added in NDK 17,
|
||||
// which is the first version to support Android Pie (API 28).
|
||||
#if __NDK_MAJOR__ >= 17
|
||||
|
||||
ASSERT_INT32(aaudio_usage_t);
|
||||
ASSERT_INT32(aaudio_content_type_t);
|
||||
ASSERT_INT32(aaudio_input_preset_t);
|
||||
|
||||
static_assert((int32_t)Usage::Media == AAUDIO_USAGE_MEDIA, ERRMSG);
|
||||
static_assert((int32_t)Usage::VoiceCommunication == AAUDIO_USAGE_VOICE_COMMUNICATION, ERRMSG);
|
||||
static_assert((int32_t)Usage::VoiceCommunicationSignalling
|
||||
== AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING, ERRMSG);
|
||||
static_assert((int32_t)Usage::Alarm == AAUDIO_USAGE_ALARM, ERRMSG);
|
||||
static_assert((int32_t)Usage::Notification == AAUDIO_USAGE_NOTIFICATION, ERRMSG);
|
||||
static_assert((int32_t)Usage::NotificationRingtone == AAUDIO_USAGE_NOTIFICATION_RINGTONE, ERRMSG);
|
||||
static_assert((int32_t)Usage::NotificationEvent == AAUDIO_USAGE_NOTIFICATION_EVENT, ERRMSG);
|
||||
static_assert((int32_t)Usage::AssistanceAccessibility == AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY, ERRMSG);
|
||||
static_assert((int32_t)Usage::AssistanceNavigationGuidance
|
||||
== AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, ERRMSG);
|
||||
static_assert((int32_t)Usage::AssistanceSonification == AAUDIO_USAGE_ASSISTANCE_SONIFICATION, ERRMSG);
|
||||
static_assert((int32_t)Usage::Game == AAUDIO_USAGE_GAME, ERRMSG);
|
||||
static_assert((int32_t)Usage::Assistant == AAUDIO_USAGE_ASSISTANT, ERRMSG);
|
||||
|
||||
static_assert((int32_t)ContentType::Speech == AAUDIO_CONTENT_TYPE_SPEECH, ERRMSG);
|
||||
static_assert((int32_t)ContentType::Music == AAUDIO_CONTENT_TYPE_MUSIC, ERRMSG);
|
||||
static_assert((int32_t)ContentType::Movie == AAUDIO_CONTENT_TYPE_MOVIE, ERRMSG);
|
||||
static_assert((int32_t)ContentType::Sonification == AAUDIO_CONTENT_TYPE_SONIFICATION, ERRMSG);
|
||||
|
||||
static_assert((int32_t)InputPreset::Generic == AAUDIO_INPUT_PRESET_GENERIC, ERRMSG);
|
||||
static_assert((int32_t)InputPreset::Camcorder == AAUDIO_INPUT_PRESET_CAMCORDER, ERRMSG);
|
||||
static_assert((int32_t)InputPreset::VoiceRecognition == AAUDIO_INPUT_PRESET_VOICE_RECOGNITION, ERRMSG);
|
||||
static_assert((int32_t)InputPreset::VoiceCommunication
|
||||
== AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION, ERRMSG);
|
||||
static_assert((int32_t)InputPreset::Unprocessed == AAUDIO_INPUT_PRESET_UNPROCESSED, ERRMSG);
|
||||
|
||||
static_assert((int32_t)SessionId::None == AAUDIO_SESSION_ID_NONE, ERRMSG);
|
||||
static_assert((int32_t)SessionId::Allocate == AAUDIO_SESSION_ID_ALLOCATE, ERRMSG);
|
||||
|
||||
#endif // __NDK_MAJOR__ >= 17
|
||||
|
||||
// aaudio_allowed_capture_policy_t was added in NDK 20,
|
||||
// which is the first version to support Android Q (API 29).
|
||||
#if __NDK_MAJOR__ >= 20
|
||||
|
||||
ASSERT_INT32(aaudio_allowed_capture_policy_t);
|
||||
|
||||
static_assert((int32_t)AllowedCapturePolicy::Unspecified == AAUDIO_UNSPECIFIED, ERRMSG);
|
||||
static_assert((int32_t)AllowedCapturePolicy::All == AAUDIO_ALLOW_CAPTURE_BY_ALL, ERRMSG);
|
||||
static_assert((int32_t)AllowedCapturePolicy::System == AAUDIO_ALLOW_CAPTURE_BY_SYSTEM, ERRMSG);
|
||||
static_assert((int32_t)AllowedCapturePolicy::None == AAUDIO_ALLOW_CAPTURE_BY_NONE, ERRMSG);
|
||||
|
||||
#endif // __NDK_MAJOR__ >= 20
|
||||
|
||||
// The aaudio channel masks and spatialization behavior were added in NDK 24,
|
||||
// which is the first version to support Android SC_V2 (API 32).
|
||||
#if __NDK_MAJOR__ >= 24
|
||||
|
||||
ASSERT_UINT32(aaudio_channel_mask_t);
|
||||
|
||||
static_assert((uint32_t)ChannelMask::FrontLeft == AAUDIO_CHANNEL_FRONT_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontRight == AAUDIO_CHANNEL_FRONT_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontCenter == AAUDIO_CHANNEL_FRONT_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::LowFrequency == AAUDIO_CHANNEL_LOW_FREQUENCY, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BackLeft == AAUDIO_CHANNEL_BACK_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BackRight == AAUDIO_CHANNEL_BACK_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontLeftOfCenter == AAUDIO_CHANNEL_FRONT_LEFT_OF_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontRightOfCenter == AAUDIO_CHANNEL_FRONT_RIGHT_OF_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BackCenter == AAUDIO_CHANNEL_BACK_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::SideLeft == AAUDIO_CHANNEL_SIDE_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::SideRight == AAUDIO_CHANNEL_SIDE_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopCenter == AAUDIO_CHANNEL_TOP_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopFrontLeft == AAUDIO_CHANNEL_TOP_FRONT_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopFrontCenter == AAUDIO_CHANNEL_TOP_FRONT_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopFrontRight == AAUDIO_CHANNEL_TOP_FRONT_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopBackLeft == AAUDIO_CHANNEL_TOP_BACK_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopBackCenter == AAUDIO_CHANNEL_TOP_BACK_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopBackRight == AAUDIO_CHANNEL_TOP_BACK_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopSideLeft == AAUDIO_CHANNEL_TOP_SIDE_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TopSideRight == AAUDIO_CHANNEL_TOP_SIDE_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BottomFrontLeft == AAUDIO_CHANNEL_BOTTOM_FRONT_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BottomFrontCenter == AAUDIO_CHANNEL_BOTTOM_FRONT_CENTER, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::BottomFrontRight == AAUDIO_CHANNEL_BOTTOM_FRONT_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::LowFrequency2 == AAUDIO_CHANNEL_LOW_FREQUENCY_2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontWideLeft == AAUDIO_CHANNEL_FRONT_WIDE_LEFT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontWideRight == AAUDIO_CHANNEL_FRONT_WIDE_RIGHT, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Mono == AAUDIO_CHANNEL_MONO, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Stereo == AAUDIO_CHANNEL_STEREO, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM2Point1 == AAUDIO_CHANNEL_2POINT1, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Tri == AAUDIO_CHANNEL_TRI, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::TriBack == AAUDIO_CHANNEL_TRI_BACK, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM3Point1 == AAUDIO_CHANNEL_3POINT1, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM2Point0Point2 == AAUDIO_CHANNEL_2POINT0POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM2Point1Point2 == AAUDIO_CHANNEL_2POINT1POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM3Point0Point2 == AAUDIO_CHANNEL_3POINT0POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM3Point1Point2 == AAUDIO_CHANNEL_3POINT1POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Quad == AAUDIO_CHANNEL_QUAD, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::QuadSide == AAUDIO_CHANNEL_QUAD_SIDE, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Surround == AAUDIO_CHANNEL_SURROUND, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::Penta == AAUDIO_CHANNEL_PENTA, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM5Point1 == AAUDIO_CHANNEL_5POINT1, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM5Point1Side == AAUDIO_CHANNEL_5POINT1_SIDE, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM6Point1 == AAUDIO_CHANNEL_6POINT1, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM7Point1 == AAUDIO_CHANNEL_7POINT1, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM5Point1Point2 == AAUDIO_CHANNEL_5POINT1POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM5Point1Point4 == AAUDIO_CHANNEL_5POINT1POINT4, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM7Point1Point2 == AAUDIO_CHANNEL_7POINT1POINT2, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM7Point1Point4 == AAUDIO_CHANNEL_7POINT1POINT4, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM9Point1Point4 == AAUDIO_CHANNEL_9POINT1POINT4, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::CM9Point1Point6 == AAUDIO_CHANNEL_9POINT1POINT6, ERRMSG);
|
||||
static_assert((uint32_t)ChannelMask::FrontBack == AAUDIO_CHANNEL_FRONT_BACK, ERRMSG);
|
||||
|
||||
ASSERT_INT32(aaudio_spatialization_behavior_t);
|
||||
|
||||
static_assert((int32_t)SpatializationBehavior::Unspecified == AAUDIO_UNSPECIFIED, ERRMSG);
|
||||
static_assert((int32_t)SpatializationBehavior::Auto == AAUDIO_SPATIALIZATION_BEHAVIOR_AUTO, ERRMSG);
|
||||
static_assert((int32_t)SpatializationBehavior::Never == AAUDIO_SPATIALIZATION_BEHAVIOR_NEVER, ERRMSG);
|
||||
|
||||
#endif
|
||||
|
||||
// The aaudio device type and aaudio policy were added in NDK 29,
|
||||
// which is the first version to support Android B (API 36).
|
||||
#if __NDK_MAJOR__ >= 30
|
||||
|
||||
ASSERT_INT32(AAudio_DeviceType);
|
||||
static_assert((int32_t)DeviceType::BuiltinEarpiece == AAUDIO_DEVICE_BUILTIN_EARPIECE, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BuiltinSpeaker == AAUDIO_DEVICE_BUILTIN_SPEAKER, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::WiredHeadset == AAUDIO_DEVICE_WIRED_HEADSET, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::WiredHeadphones == AAUDIO_DEVICE_WIRED_HEADPHONES, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::LineAnalog == AAUDIO_DEVICE_LINE_ANALOG, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::LineDigital == AAUDIO_DEVICE_LINE_DIGITAL, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BluetoothSco == AAUDIO_DEVICE_BLUETOOTH_SCO, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BluetoothA2dp == AAUDIO_DEVICE_BLUETOOTH_A2DP, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::Hdmi == AAUDIO_DEVICE_HDMI, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::HdmiArc == AAUDIO_DEVICE_HDMI_ARC, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::UsbDevice == AAUDIO_DEVICE_USB_DEVICE, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::UsbAccessory == AAUDIO_DEVICE_USB_ACCESSORY, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::Dock == AAUDIO_DEVICE_DOCK, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::FM == AAUDIO_DEVICE_FM, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BuiltinMic == AAUDIO_DEVICE_BUILTIN_MIC, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::FMTuner == AAUDIO_DEVICE_FM_TUNER, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::TVTuner == AAUDIO_DEVICE_TV_TUNER, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::Telephony == AAUDIO_DEVICE_TELEPHONY, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::AuxLine == AAUDIO_DEVICE_AUX_LINE, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::IP == AAUDIO_DEVICE_IP, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::Bus == AAUDIO_DEVICE_BUS, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::UsbHeadset == AAUDIO_DEVICE_USB_HEADSET, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::HearingAid == AAUDIO_DEVICE_HEARING_AID, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BuiltinSpeakerSafe == AAUDIO_DEVICE_BUILTIN_SPEAKER_SAFE, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::RemoteSubmix == AAUDIO_DEVICE_REMOTE_SUBMIX, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BleHeadset == AAUDIO_DEVICE_BLE_HEADSET, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BleSpeaker == AAUDIO_DEVICE_BLE_SPEAKER, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::HdmiEarc == AAUDIO_DEVICE_HDMI_EARC, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::BleBroadcast == AAUDIO_DEVICE_BLE_BROADCAST, ERRMSG);
|
||||
static_assert((int32_t)DeviceType::DockAnalog == AAUDIO_DEVICE_DOCK_ANALOG, ERRMSG);
|
||||
|
||||
ASSERT_INT32(aaudio_policy_t);
|
||||
static_assert((int32_t)MMapPolicy::Unspecified == AAUDIO_UNSPECIFIED, ERRMSG);
|
||||
static_assert((int32_t)MMapPolicy::Never == AAUDIO_POLICY_NEVER, ERRMSG);
|
||||
static_assert((int32_t)MMapPolicy::Auto == AAUDIO_POLICY_AUTO, ERRMSG);
|
||||
static_assert((int32_t)MMapPolicy::Always == AAUDIO_POLICY_ALWAYS, ERRMSG);
|
||||
|
||||
#endif // __NDK_MAJOR__ >= 29
|
||||
|
||||
#endif // AAUDIO_AAUDIO_H
|
||||
|
||||
} // namespace oboe
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_AAUDIO_LOADER_H_
|
||||
#define OBOE_AAUDIO_LOADER_H_
|
||||
|
||||
#include <unistd.h>
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
// If the NDK is before O then define this in your build
|
||||
// so that AAudio.h will not be included.
|
||||
#ifdef OBOE_NO_INCLUDE_AAUDIO
|
||||
|
||||
// Define missing types from AAudio.h
|
||||
typedef int32_t aaudio_stream_state_t;
|
||||
typedef int32_t aaudio_direction_t;
|
||||
typedef int32_t aaudio_format_t;
|
||||
typedef int32_t aaudio_data_callback_result_t;
|
||||
typedef int32_t aaudio_result_t;
|
||||
typedef int32_t aaudio_sharing_mode_t;
|
||||
typedef int32_t aaudio_performance_mode_t;
|
||||
|
||||
typedef struct AAudioStreamStruct AAudioStream;
|
||||
typedef struct AAudioStreamBuilderStruct AAudioStreamBuilder;
|
||||
|
||||
typedef aaudio_data_callback_result_t (*AAudioStream_dataCallback)(
|
||||
AAudioStream *stream,
|
||||
void *userData,
|
||||
void *audioData,
|
||||
int32_t numFrames);
|
||||
|
||||
typedef void (*AAudioStream_errorCallback)(
|
||||
AAudioStream *stream,
|
||||
void *userData,
|
||||
aaudio_result_t error);
|
||||
|
||||
// These were defined in P
|
||||
typedef int32_t aaudio_usage_t;
|
||||
typedef int32_t aaudio_content_type_t;
|
||||
typedef int32_t aaudio_input_preset_t;
|
||||
typedef int32_t aaudio_session_id_t;
|
||||
|
||||
// There are a few definitions used by Oboe.
|
||||
#define AAUDIO_OK static_cast<aaudio_result_t>(Result::OK)
|
||||
#define AAUDIO_ERROR_TIMEOUT static_cast<aaudio_result_t>(Result::ErrorTimeout)
|
||||
#define AAUDIO_STREAM_STATE_STARTING static_cast<aaudio_stream_state_t>(StreamState::Starting)
|
||||
#define AAUDIO_STREAM_STATE_STARTED static_cast<aaudio_stream_state_t>(StreamState::Started)
|
||||
#else
|
||||
#include <aaudio/AAudio.h>
|
||||
#endif
|
||||
|
||||
#ifdef __NDK_MAJOR__
|
||||
#define OBOE_USING_NDK 1
|
||||
#else
|
||||
#define __NDK_MAJOR__ 0
|
||||
#define OBOE_USING_NDK 0
|
||||
#endif
|
||||
|
||||
#if __NDK_MAJOR__ < 24
|
||||
// Defined in SC_V2
|
||||
typedef uint32_t aaudio_channel_mask_t;
|
||||
typedef int32_t aaudio_spatialization_behavior_t;
|
||||
#endif
|
||||
|
||||
#if OBOE_USING_NDK && __NDK_MAJOR__ < 29
|
||||
// Defined in Android B
|
||||
typedef void (*AAudioStream_presentationEndCallback)(
|
||||
AAudioStream* stream,
|
||||
void* userData);
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_Q__
|
||||
#define __ANDROID_API_Q__ 29
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_R__
|
||||
#define __ANDROID_API_R__ 30
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_S__
|
||||
#define __ANDROID_API_S__ 31
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_S_V2__
|
||||
#define __ANDROID_API_S_V2__ 32
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_U__
|
||||
#define __ANDROID_API_U__ 34
|
||||
#endif
|
||||
|
||||
#ifndef __ANDROID_API_B__
|
||||
#define __ANDROID_API_B__ 36
|
||||
#endif
|
||||
|
||||
#if OBOE_USING_NDK && __NDK_MAJOR__ < 30
|
||||
// These were defined in Android B
|
||||
typedef int32_t AAudio_DeviceType;
|
||||
typedef int32_t aaudio_policy_t;
|
||||
#endif
|
||||
|
||||
// TODO: find the first NDK version containing the following values
|
||||
#if OBOE_USING_NDK && __NDK_MAJOR__ <= 30
|
||||
typedef enum AAudio_FallbackMode : int32_t {
|
||||
AAUDIO_FALLBACK_MODE_DEFAULT = 0,
|
||||
AAUDIO_FALLBACK_MODE_MUTE = 1,
|
||||
AAUDIO_FALLBACK_MODE_FAIL = 2,
|
||||
} AAudio_FallbackMode;
|
||||
|
||||
typedef enum AAudio_StretchMode : int32_t {
|
||||
AAUDIO_STRETCH_MODE_DEFAULT = 0,
|
||||
AAUDIO_STRETCH_MODE_VOICE = 1,
|
||||
} AAudio_StretchMode;
|
||||
|
||||
typedef struct AAudioPlaybackParameters {
|
||||
AAudio_FallbackMode fallbackMode;
|
||||
AAudio_StretchMode stretchMode;
|
||||
float pitch;
|
||||
float speed;
|
||||
} AAudioPlaybackParameters;
|
||||
|
||||
typedef int32_t (*AAudioStream_partialDataCallback)(
|
||||
AAudioStream* stream,
|
||||
void* userData,
|
||||
void* audioData,
|
||||
int32_t numFrames);
|
||||
#endif
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* The AAudio API was not available in early versions of Android.
|
||||
* To avoid linker errors, we dynamically link with the functions by name using dlsym().
|
||||
* On older versions this linkage will safely fail.
|
||||
*/
|
||||
class AAudioLoader {
|
||||
public:
|
||||
// Use signatures for common functions.
|
||||
// Key to letter abbreviations.
|
||||
// S = Stream
|
||||
// B = Builder
|
||||
// I = int32_t
|
||||
// L = int64_t
|
||||
// T = sTate
|
||||
// K = clocKid_t
|
||||
// P = Pointer to following data type
|
||||
// C = Const prefix
|
||||
// H = cHar
|
||||
// U = uint32_t
|
||||
// O = bOol
|
||||
// R = pResentation end callback
|
||||
// M = aaudioplaybackparaMeters
|
||||
// D = Datacallback/partialDatacallback
|
||||
|
||||
typedef int32_t (*signature_I_PPB)(AAudioStreamBuilder **builder);
|
||||
|
||||
typedef const char * (*signature_CPH_I)(int32_t);
|
||||
|
||||
typedef int32_t (*signature_I_PBPPS)(AAudioStreamBuilder *,
|
||||
AAudioStream **stream); // AAudioStreamBuilder_open()
|
||||
|
||||
typedef int32_t (*signature_I_PB)(AAudioStreamBuilder *); // AAudioStreamBuilder_delete()
|
||||
// AAudioStreamBuilder_setSampleRate()
|
||||
typedef void (*signature_V_PBI)(AAudioStreamBuilder *, int32_t);
|
||||
|
||||
// AAudioStreamBuilder_setChannelMask()
|
||||
typedef void (*signature_V_PBU)(AAudioStreamBuilder *, uint32_t);
|
||||
|
||||
typedef void (*signature_V_PBCPH)(AAudioStreamBuilder *, const char *);
|
||||
|
||||
// AAudioStreamBuilder_setPrivacySensitive
|
||||
typedef void (*signature_V_PBO)(AAudioStreamBuilder *, bool);
|
||||
|
||||
typedef int32_t (*signature_I_PS)(AAudioStream *); // AAudioStream_getSampleRate()
|
||||
typedef int64_t (*signature_L_PS)(AAudioStream *); // AAudioStream_getFramesRead()
|
||||
// AAudioStream_setBufferSizeInFrames()
|
||||
typedef int32_t (*signature_I_PSI)(AAudioStream *, int32_t);
|
||||
|
||||
typedef void (*signature_V_PBPDPV)(AAudioStreamBuilder *,
|
||||
AAudioStream_dataCallback,
|
||||
void *);
|
||||
|
||||
typedef void (*signature_V_PBPEPV)(AAudioStreamBuilder *,
|
||||
AAudioStream_errorCallback,
|
||||
void *);
|
||||
|
||||
typedef void (*signature_V_PBPRPV)(AAudioStreamBuilder *,
|
||||
AAudioStream_presentationEndCallback,
|
||||
void *);
|
||||
|
||||
typedef aaudio_format_t (*signature_F_PS)(AAudioStream *stream);
|
||||
|
||||
typedef int32_t (*signature_I_PSPVIL)(AAudioStream *, void *, int32_t, int64_t);
|
||||
typedef int32_t (*signature_I_PSCPVIL)(AAudioStream *, const void *, int32_t, int64_t);
|
||||
|
||||
typedef int32_t (*signature_I_PSTPTL)(AAudioStream *,
|
||||
aaudio_stream_state_t,
|
||||
aaudio_stream_state_t *,
|
||||
int64_t);
|
||||
|
||||
typedef int32_t (*signature_I_PSKPLPL)(AAudioStream *, clockid_t, int64_t *, int64_t *);
|
||||
|
||||
typedef bool (*signature_O_PS)(AAudioStream *);
|
||||
|
||||
typedef uint32_t (*signature_U_PS)(AAudioStream *);
|
||||
|
||||
typedef int32_t (*signature_I_II)(int32_t, int32_t);
|
||||
typedef int32_t (*signature_I_I)(int32_t);
|
||||
typedef int32_t (*signature_I)();
|
||||
typedef int32_t (*signature_I_PSII)(AAudioStream *, int32_t, int32_t);
|
||||
|
||||
// AAudioStream_getDeviceIds()
|
||||
typedef int32_t (*signature_I_PSPIPI)(AAudioStream *, int32_t *, int32_t *);
|
||||
|
||||
typedef int32_t (*signature_I_PSIPL)(AAudioStream *, int32_t, int64_t *);
|
||||
|
||||
typedef int32_t (*signature_I_PSPM)(AAudioStream *, AAudioPlaybackParameters *);
|
||||
typedef int32_t (*signature_I_PSCPM)(AAudioStream *, const AAudioPlaybackParameters *);
|
||||
|
||||
static AAudioLoader* getInstance(); // singleton
|
||||
|
||||
/**
|
||||
* Open the AAudio shared library and load the function pointers.
|
||||
* This can be called multiple times.
|
||||
* It should only be called from one thread.
|
||||
*
|
||||
* The destructor will clean up after the open.
|
||||
*
|
||||
* @return 0 if successful or negative error.
|
||||
*/
|
||||
int open();
|
||||
|
||||
void *getLibHandle() const { return mLibHandle; }
|
||||
|
||||
// Function pointers into the AAudio shared library.
|
||||
signature_I_PPB createStreamBuilder = nullptr;
|
||||
|
||||
signature_I_PBPPS builder_openStream = nullptr;
|
||||
|
||||
signature_V_PBI builder_setBufferCapacityInFrames = nullptr;
|
||||
signature_V_PBI builder_setChannelCount = nullptr;
|
||||
signature_V_PBI builder_setDeviceId = nullptr;
|
||||
signature_V_PBI builder_setDirection = nullptr;
|
||||
signature_V_PBI builder_setFormat = nullptr;
|
||||
signature_V_PBI builder_setFramesPerDataCallback = nullptr;
|
||||
signature_V_PBI builder_setPerformanceMode = nullptr;
|
||||
signature_V_PBI builder_setSampleRate = nullptr;
|
||||
signature_V_PBI builder_setSharingMode = nullptr;
|
||||
signature_V_PBU builder_setChannelMask = nullptr;
|
||||
|
||||
signature_V_PBI builder_setUsage = nullptr;
|
||||
signature_V_PBI builder_setContentType = nullptr;
|
||||
signature_V_PBI builder_setInputPreset = nullptr;
|
||||
signature_V_PBI builder_setSessionId = nullptr;
|
||||
|
||||
signature_V_PBO builder_setPrivacySensitive = nullptr;
|
||||
signature_V_PBI builder_setAllowedCapturePolicy = nullptr;
|
||||
|
||||
signature_V_PBCPH builder_setPackageName = nullptr;
|
||||
signature_V_PBCPH builder_setAttributionTag = nullptr;
|
||||
|
||||
signature_V_PBO builder_setIsContentSpatialized = nullptr;
|
||||
signature_V_PBI builder_setSpatializationBehavior = nullptr;
|
||||
|
||||
signature_V_PBPDPV builder_setDataCallback = nullptr;
|
||||
signature_V_PBPEPV builder_setErrorCallback = nullptr;
|
||||
signature_V_PBPRPV builder_setPresentationEndCallback = nullptr;
|
||||
signature_V_PBPDPV builder_setPartialDataCallback = nullptr;
|
||||
|
||||
signature_I_PB builder_delete = nullptr;
|
||||
|
||||
signature_F_PS stream_getFormat = nullptr;
|
||||
|
||||
signature_I_PSPVIL stream_read = nullptr;
|
||||
signature_I_PSCPVIL stream_write = nullptr;
|
||||
|
||||
signature_I_PSTPTL stream_waitForStateChange = nullptr;
|
||||
|
||||
signature_I_PSKPLPL stream_getTimestamp = nullptr;
|
||||
|
||||
signature_I_PSPIPI stream_getDeviceIds = nullptr;
|
||||
|
||||
signature_I_PS stream_release = nullptr;
|
||||
signature_I_PS stream_close = nullptr;
|
||||
|
||||
signature_I_PS stream_getChannelCount = nullptr;
|
||||
signature_I_PS stream_getDeviceId = nullptr;
|
||||
|
||||
signature_I_PS stream_getBufferSize = nullptr;
|
||||
signature_I_PS stream_getBufferCapacity = nullptr;
|
||||
signature_I_PS stream_getFramesPerBurst = nullptr;
|
||||
signature_I_PS stream_getState = nullptr;
|
||||
signature_I_PS stream_getPerformanceMode = nullptr;
|
||||
signature_I_PS stream_getSampleRate = nullptr;
|
||||
signature_I_PS stream_getSharingMode = nullptr;
|
||||
signature_I_PS stream_getXRunCount = nullptr;
|
||||
|
||||
signature_I_PSI stream_setBufferSize = nullptr;
|
||||
signature_I_PS stream_requestStart = nullptr;
|
||||
signature_I_PS stream_requestPause = nullptr;
|
||||
signature_I_PS stream_requestFlush = nullptr;
|
||||
signature_I_PS stream_requestStop = nullptr;
|
||||
|
||||
signature_L_PS stream_getFramesRead = nullptr;
|
||||
signature_L_PS stream_getFramesWritten = nullptr;
|
||||
|
||||
signature_CPH_I convertResultToText = nullptr;
|
||||
|
||||
signature_I_PS stream_getUsage = nullptr;
|
||||
signature_I_PS stream_getContentType = nullptr;
|
||||
signature_I_PS stream_getInputPreset = nullptr;
|
||||
signature_I_PS stream_getSessionId = nullptr;
|
||||
|
||||
signature_O_PS stream_isPrivacySensitive = nullptr;
|
||||
signature_I_PS stream_getAllowedCapturePolicy = nullptr;
|
||||
|
||||
signature_U_PS stream_getChannelMask = nullptr;
|
||||
|
||||
signature_O_PS stream_isContentSpatialized = nullptr;
|
||||
signature_I_PS stream_getSpatializationBehavior = nullptr;
|
||||
|
||||
signature_I_PS stream_getHardwareChannelCount = nullptr;
|
||||
signature_I_PS stream_getHardwareSampleRate = nullptr;
|
||||
signature_F_PS stream_getHardwareFormat = nullptr;
|
||||
|
||||
|
||||
signature_I_II aaudio_getPlatformMMapPolicy = nullptr;
|
||||
signature_I_II aaudio_getPlatformMMapExclusivePolicy = nullptr;
|
||||
signature_I_I aaudio_setMMapPolicy = nullptr;
|
||||
signature_I aaudio_getMMapPolicy = nullptr;
|
||||
signature_O_PS stream_isMMapUsed = nullptr;
|
||||
|
||||
signature_I_PSII stream_setOffloadDelayPadding = nullptr;
|
||||
signature_I_PS stream_getOffloadDelay = nullptr;
|
||||
signature_I_PS stream_getOffloadPadding = nullptr;
|
||||
signature_I_PS stream_setOffloadEndOfStream = nullptr;
|
||||
|
||||
signature_I_PSIPL stream_flushFromFrame = nullptr;
|
||||
|
||||
signature_I_PSPM stream_getPlaybackParameters = nullptr;
|
||||
signature_I_PSCPM stream_setPlaybackParameters = nullptr;
|
||||
|
||||
private:
|
||||
AAudioLoader() {}
|
||||
~AAudioLoader();
|
||||
|
||||
// Load function pointers for specific signatures.
|
||||
signature_I_PPB load_I_PPB(const char *name);
|
||||
signature_CPH_I load_CPH_I(const char *name);
|
||||
signature_V_PBI load_V_PBI(const char *name);
|
||||
signature_V_PBCPH load_V_PBCPH(const char *name);
|
||||
signature_V_PBPDPV load_V_PBPDPV(const char *name);
|
||||
signature_V_PBPEPV load_V_PBPEPV(const char *name);
|
||||
signature_I_PB load_I_PB(const char *name);
|
||||
signature_I_PBPPS load_I_PBPPS(const char *name);
|
||||
signature_I_PS load_I_PS(const char *name);
|
||||
signature_L_PS load_L_PS(const char *name);
|
||||
signature_F_PS load_F_PS(const char *name);
|
||||
signature_O_PS load_O_PS(const char *name);
|
||||
signature_I_PSI load_I_PSI(const char *name);
|
||||
signature_I_PSPVIL load_I_PSPVIL(const char *name);
|
||||
signature_I_PSCPVIL load_I_PSCPVIL(const char *name);
|
||||
signature_I_PSTPTL load_I_PSTPTL(const char *name);
|
||||
signature_I_PSKPLPL load_I_PSKPLPL(const char *name);
|
||||
signature_V_PBU load_V_PBU(const char *name);
|
||||
signature_U_PS load_U_PS(const char *name);
|
||||
signature_V_PBO load_V_PBO(const char *name);
|
||||
signature_I_II load_I_II(const char *name);
|
||||
signature_I_I load_I_I(const char *name);
|
||||
signature_I load_I(const char *name);
|
||||
signature_V_PBPRPV load_V_PBPRPV(const char *name);
|
||||
signature_I_PSII load_I_PSII(const char *name);
|
||||
signature_I_PSPIPI load_I_PSPIPI(const char *name);
|
||||
signature_I_PSIPL load_I_PSIPL(const char *name);
|
||||
signature_I_PSPM load_I_PSPM(const char *name);
|
||||
signature_I_PSCPM load_I_PSCPM(const char *name);
|
||||
|
||||
void *mLibHandle = nullptr;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif //OBOE_AAUDIO_LOADER_H_
|
||||
+1186
File diff suppressed because it is too large
Load Diff
+198
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_STREAM_AAUDIO_H_
|
||||
#define OBOE_STREAM_AAUDIO_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <shared_mutex>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
#include <common/AdpfWrapper.h>
|
||||
#include "oboe/AudioStreamBuilder.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
#include "oboe/Definitions.h"
|
||||
#include "AAudioLoader.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* Implementation of OboeStream that uses AAudio.
|
||||
*
|
||||
* Do not create this class directly.
|
||||
* Use an OboeStreamBuilder to create one.
|
||||
*/
|
||||
class AudioStreamAAudio : public AudioStream {
|
||||
public:
|
||||
AudioStreamAAudio();
|
||||
explicit AudioStreamAAudio(const AudioStreamBuilder &builder);
|
||||
|
||||
virtual ~AudioStreamAAudio() = default;
|
||||
|
||||
/**
|
||||
*
|
||||
* @return true if AAudio is supported on this device.
|
||||
*/
|
||||
static bool isSupported();
|
||||
|
||||
// These functions override methods in AudioStream.
|
||||
// See AudioStream for documentation.
|
||||
Result open() override;
|
||||
Result release() override;
|
||||
Result close() override;
|
||||
|
||||
Result requestStart() override;
|
||||
Result requestPause() override;
|
||||
Result requestFlush() override;
|
||||
Result requestStop() override;
|
||||
|
||||
ResultWithValue<int32_t> write(const void *buffer,
|
||||
int32_t numFrames,
|
||||
int64_t timeoutNanoseconds) override;
|
||||
|
||||
ResultWithValue<int32_t> read(void *buffer,
|
||||
int32_t numFrames,
|
||||
int64_t timeoutNanoseconds) override;
|
||||
|
||||
ResultWithValue<int32_t> setBufferSizeInFrames(int32_t requestedFrames) override;
|
||||
int32_t getBufferSizeInFrames() override;
|
||||
ResultWithValue<int32_t> getXRunCount() override;
|
||||
bool isXRunCountSupported() const override { return true; }
|
||||
|
||||
ResultWithValue<double> calculateLatencyMillis() override;
|
||||
|
||||
Result waitForStateChange(StreamState currentState,
|
||||
StreamState *nextState,
|
||||
int64_t timeoutNanoseconds) override;
|
||||
|
||||
Result getTimestamp(clockid_t clockId,
|
||||
int64_t *framePosition,
|
||||
int64_t *timeNanoseconds) override;
|
||||
|
||||
StreamState getState() override;
|
||||
|
||||
AudioApi getAudioApi() const override {
|
||||
return AudioApi::AAudio;
|
||||
}
|
||||
|
||||
DataCallbackResult callOnAudioReady(AAudioStream *stream, void *audioData, int32_t numFrames);
|
||||
|
||||
int32_t callOnPartialAudioReady(AAudioStream *stream, void *audioData, int32_t numFrames);
|
||||
|
||||
bool isMMapUsed();
|
||||
|
||||
void closePerformanceHint() override {
|
||||
mAdpfWrapper.close();
|
||||
mAdpfOpenAttempted = false;
|
||||
}
|
||||
|
||||
oboe::Result reportWorkload(int32_t appWorkload) override {
|
||||
if (!isPerformanceHintEnabled()) {
|
||||
return oboe::Result::ErrorInvalidState;
|
||||
}
|
||||
mAdpfWrapper.reportWorkload(appWorkload);
|
||||
return oboe::Result::OK;
|
||||
}
|
||||
|
||||
oboe::Result notifyWorkloadIncrease(bool cpu, bool gpu, const char* debugName) override {
|
||||
if (!isPerformanceHintEnabled()) {
|
||||
return oboe::Result::ErrorInvalidState;
|
||||
}
|
||||
return mAdpfWrapper.notifyWorkloadIncrease(cpu, gpu, debugName);
|
||||
}
|
||||
|
||||
oboe::Result notifyWorkloadSpike(bool cpu, bool gpu, const char* debugName) override {
|
||||
if (!isPerformanceHintEnabled()) {
|
||||
return oboe::Result::ErrorInvalidState;
|
||||
}
|
||||
return mAdpfWrapper.notifyWorkloadSpike(cpu, gpu, debugName);
|
||||
}
|
||||
|
||||
oboe::Result notifyWorkloadReset(bool cpu, bool gpu, const char* debugName) override {
|
||||
if (!isPerformanceHintEnabled()) {
|
||||
return oboe::Result::ErrorInvalidState;
|
||||
}
|
||||
return mAdpfWrapper.notifyWorkloadReset(cpu, gpu, debugName);
|
||||
}
|
||||
|
||||
Result setOffloadDelayPadding(int32_t delayInFrames, int32_t paddingInFrames) override;
|
||||
ResultWithValue<int32_t> getOffloadDelay() override;
|
||||
ResultWithValue<int32_t> getOffloadPadding() override;
|
||||
Result setOffloadEndOfStream() override;
|
||||
|
||||
ResultWithValue<int64_t> flushFromFrame(
|
||||
FlushFromAccuracy accuracy, int64_t positionInFrames) override;
|
||||
|
||||
oboe::Result setPlaybackParameters(const PlaybackParameters& parameters) override;
|
||||
ResultWithValue<PlaybackParameters> getPlaybackParameters() override;
|
||||
|
||||
protected:
|
||||
static void internalErrorCallback(
|
||||
AAudioStream *stream,
|
||||
void *userData,
|
||||
aaudio_result_t error);
|
||||
|
||||
static void internalPresentationEndCallback(
|
||||
AAudioStream *stream,
|
||||
void *userData);
|
||||
|
||||
void *getUnderlyingStream() const override {
|
||||
return mAAudioStream.load();
|
||||
}
|
||||
|
||||
void updateFramesRead() override;
|
||||
void updateFramesWritten() override;
|
||||
|
||||
void logUnsupportedAttributes();
|
||||
|
||||
void beginPerformanceHintInCallback() override;
|
||||
|
||||
void endPerformanceHintInCallback(int32_t numFrames) override;
|
||||
|
||||
// set by callback (or app when idle)
|
||||
std::atomic<bool> mAdpfOpenAttempted{false};
|
||||
AdpfWrapper mAdpfWrapper;
|
||||
|
||||
private:
|
||||
// Must call under mLock. And stream must NOT be nullptr.
|
||||
Result requestStop_l(AAudioStream *stream);
|
||||
|
||||
/**
|
||||
* Launch a thread that will stop the stream.
|
||||
*/
|
||||
void launchStopThread();
|
||||
|
||||
void updateDeviceIds();
|
||||
|
||||
private:
|
||||
|
||||
std::atomic<bool> mCallbackThreadEnabled;
|
||||
std::atomic<bool> mStopThreadAllowed{false};
|
||||
|
||||
// pointer to the underlying 'C' AAudio stream, valid if open, null if closed
|
||||
std::atomic<AAudioStream *> mAAudioStream{nullptr};
|
||||
std::shared_mutex mAAudioStreamLock; // to protect mAAudioStream while closing
|
||||
|
||||
static AAudioLoader *mLibLoader;
|
||||
|
||||
// We may not use this but it is so small that it is not worth allocating dynamically.
|
||||
AudioStreamErrorCallback mDefaultErrorCallback;
|
||||
};
|
||||
|
||||
} // namespace oboe
|
||||
|
||||
#endif // OBOE_STREAM_AAUDIO_H_
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
* Copyright 2021 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "oboe/AudioClock.h"
|
||||
#include "oboe/Definitions.h"
|
||||
#include "oboe/Utilities.h"
|
||||
#include "AdpfWrapper.h"
|
||||
#include "OboeDebug.h"
|
||||
#include "Trace.h"
|
||||
|
||||
using namespace oboe;
|
||||
|
||||
typedef APerformanceHintManager* (*APH_getManager)();
|
||||
typedef APerformanceHintSession* (*APH_createSession)(APerformanceHintManager*, const int32_t*,
|
||||
size_t, int64_t);
|
||||
typedef void (*APH_reportActualWorkDuration)(APerformanceHintSession*, int64_t);
|
||||
typedef void (*APH_closeSession)(APerformanceHintSession* session);
|
||||
typedef int (*APH_notifyWorkloadIncrease)(APerformanceHintSession*, bool, bool, const char*);
|
||||
typedef int (*APH_notifyWorkloadSpike)(APerformanceHintSession*, bool, bool, const char*);
|
||||
typedef int (*APH_notifyWorkloadReset)(APerformanceHintSession*, bool, bool, const char*);
|
||||
|
||||
static bool gAPerformanceHintBindingInitialized = false;
|
||||
static APH_getManager gAPH_getManagerFn = nullptr;
|
||||
static APH_createSession gAPH_createSessionFn = nullptr;
|
||||
static APH_reportActualWorkDuration gAPH_reportActualWorkDurationFn = nullptr;
|
||||
static APH_closeSession gAPH_closeSessionFn = nullptr;
|
||||
static APH_notifyWorkloadIncrease gAPH_notifyWorkloadIncreaseFn = nullptr;
|
||||
static APH_notifyWorkloadSpike gAPH_notifyWorkloadSpikeFn = nullptr;
|
||||
static APH_notifyWorkloadReset gAPH_notifyWorkloadResetFn = nullptr;
|
||||
|
||||
#ifndef __ANDROID_API_B__
|
||||
#define __ANDROID_API_B__ 36
|
||||
#endif
|
||||
|
||||
static int loadAphFunctions() {
|
||||
if (gAPerformanceHintBindingInitialized) return true;
|
||||
|
||||
void* handle_ = dlopen("libandroid.so", RTLD_NOW | RTLD_NODELETE);
|
||||
if (handle_ == nullptr) {
|
||||
return -1000;
|
||||
}
|
||||
|
||||
gAPH_getManagerFn = (APH_getManager)dlsym(handle_, "APerformanceHint_getManager");
|
||||
if (gAPH_getManagerFn == nullptr) {
|
||||
return -1001;
|
||||
}
|
||||
|
||||
gAPH_createSessionFn = (APH_createSession)dlsym(handle_, "APerformanceHint_createSession");
|
||||
if (gAPH_createSessionFn == nullptr) {
|
||||
return -1002;
|
||||
}
|
||||
|
||||
gAPH_reportActualWorkDurationFn = (APH_reportActualWorkDuration)dlsym(
|
||||
handle_, "APerformanceHint_reportActualWorkDuration");
|
||||
if (gAPH_reportActualWorkDurationFn == nullptr) {
|
||||
return -1003;
|
||||
}
|
||||
|
||||
gAPH_closeSessionFn = (APH_closeSession)dlsym(handle_, "APerformanceHint_closeSession");
|
||||
if (gAPH_closeSessionFn == nullptr) {
|
||||
return -1004;
|
||||
}
|
||||
|
||||
// TODO: Remove pre-release check after Android B release
|
||||
if (getSdkVersion() >= __ANDROID_API_B__ || isAtLeastPreReleaseCodename("Baklava")) {
|
||||
gAPH_notifyWorkloadIncreaseFn = (APH_notifyWorkloadIncrease)dlsym(
|
||||
handle_, "APerformanceHint_notifyWorkloadIncrease");
|
||||
if (gAPH_notifyWorkloadIncreaseFn == nullptr) {
|
||||
return -1005;
|
||||
}
|
||||
gAPH_notifyWorkloadSpikeFn = (APH_notifyWorkloadSpike)dlsym(
|
||||
handle_, "APerformanceHint_notifyWorkloadSpike");
|
||||
if (gAPH_notifyWorkloadSpikeFn == nullptr) {
|
||||
return -1006;
|
||||
}
|
||||
gAPH_notifyWorkloadResetFn = (APH_notifyWorkloadReset)dlsym(
|
||||
handle_, "APerformanceHint_notifyWorkloadReset");
|
||||
if (gAPH_notifyWorkloadResetFn == nullptr) {
|
||||
return -1007;
|
||||
}
|
||||
}
|
||||
|
||||
gAPerformanceHintBindingInitialized = true;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool AdpfWrapper::sUseAlternativeHack = false; // TODO remove hack
|
||||
|
||||
int AdpfWrapper::open(pid_t threadId,
|
||||
int64_t targetDurationNanos) {
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
int result = loadAphFunctions();
|
||||
if (result < 0) return result;
|
||||
|
||||
// This is a singleton.
|
||||
APerformanceHintManager* manager = gAPH_getManagerFn();
|
||||
|
||||
int32_t thread32 = threadId;
|
||||
if (sUseAlternativeHack) {
|
||||
// TODO Remove this hack when we finish experimenting with alternative algorithms.
|
||||
// The A5 is an arbitrary signal to a hacked version of ADPF to try an alternative
|
||||
// algorithm that is not based on PID.
|
||||
targetDurationNanos = (targetDurationNanos & ~0xFF) | 0xA5;
|
||||
}
|
||||
mHintSession = gAPH_createSessionFn(manager, &thread32, 1 /* size */, targetDurationNanos);
|
||||
if (mHintSession == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void AdpfWrapper::reportActualDuration(int64_t actualDurationNanos) {
|
||||
//LOGD("ADPF Oboe %s(dur=%lld)", __func__, (long long)actualDurationNanos);
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
if (mHintSession != nullptr) {
|
||||
bool traceEnabled = Trace::getInstance().isEnabled();
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().beginSection("reportActualDuration");
|
||||
Trace::getInstance().setCounter("actualDurationNanos", actualDurationNanos);
|
||||
}
|
||||
gAPH_reportActualWorkDurationFn(mHintSession, actualDurationNanos);
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().endSection();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AdpfWrapper::close() {
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
if (mHintSession != nullptr) {
|
||||
gAPH_closeSessionFn(mHintSession);
|
||||
mHintSession = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void AdpfWrapper::onBeginCallback() {
|
||||
if (isOpen()) {
|
||||
mBeginCallbackNanos = oboe::AudioClock::getNanoseconds();
|
||||
}
|
||||
}
|
||||
|
||||
void AdpfWrapper::onEndCallback(double durationScaler) {
|
||||
if (isOpen()) {
|
||||
int64_t endCallbackNanos = oboe::AudioClock::getNanoseconds();
|
||||
int64_t actualDurationNanos = endCallbackNanos - mBeginCallbackNanos;
|
||||
int64_t scaledDurationNanos = static_cast<int64_t>(actualDurationNanos * durationScaler);
|
||||
reportActualDuration(scaledDurationNanos);
|
||||
// When the workload is non-zero, update the conversion factor from workload
|
||||
// units to nanoseconds duration.
|
||||
if (mPreviousWorkload > 0) {
|
||||
mNanosPerWorkloadUnit = ((double) scaledDurationNanos) / mPreviousWorkload;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AdpfWrapper::reportWorkload(int32_t appWorkload) {
|
||||
if (isOpen()) {
|
||||
// Compare with previous workload. If we think we will need more
|
||||
// time to render the callback then warn ADPF as soon as possible.
|
||||
if (appWorkload > mPreviousWorkload && mNanosPerWorkloadUnit > 0.0) {
|
||||
int64_t predictedDuration = (int64_t) (appWorkload * mNanosPerWorkloadUnit);
|
||||
reportActualDuration(predictedDuration);
|
||||
}
|
||||
mPreviousWorkload = appWorkload;
|
||||
}
|
||||
}
|
||||
|
||||
oboe::Result AdpfWrapper::notifyWorkloadIncrease(bool cpu, bool gpu, const char* debugName) {
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
bool traceEnabled = Trace::getInstance().isEnabled();
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().beginSection("notifyWorkloadIncrease");
|
||||
}
|
||||
if (gAPH_notifyWorkloadIncreaseFn == nullptr) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
if (mHintSession == nullptr) {
|
||||
return Result::ErrorClosed;
|
||||
}
|
||||
int result = gAPH_notifyWorkloadIncreaseFn(mHintSession, cpu, gpu, debugName);
|
||||
if (result == 0) {
|
||||
return Result::OK;
|
||||
} else if (result == EINVAL) { // no hints were requested
|
||||
return Result::ErrorInvalidHandle;
|
||||
} else if (result == EBUSY) { // the hint was rate limited
|
||||
return Result::ErrorInvalidRate;
|
||||
} else if (result == EPIPE) { // communication with the system service has failed
|
||||
return Result::ErrorNoService;
|
||||
} else if (result == ENOTSUP) { // the hint is not supported
|
||||
return Result::ErrorUnavailable;
|
||||
} else {
|
||||
return Result::ErrorInternal; // Unknown error
|
||||
}
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().endSection();
|
||||
}
|
||||
}
|
||||
|
||||
oboe::Result AdpfWrapper::notifyWorkloadSpike(bool cpu, bool gpu, const char* debugName) {
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
bool traceEnabled = Trace::getInstance().isEnabled();
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().beginSection("notifyWorkloadSpike");
|
||||
}
|
||||
if (gAPH_notifyWorkloadSpikeFn == nullptr) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
if (mHintSession == nullptr) {
|
||||
return Result::ErrorClosed;
|
||||
}
|
||||
int result = gAPH_notifyWorkloadSpikeFn(mHintSession, cpu, gpu, debugName);
|
||||
if (result == 0) {
|
||||
return Result::OK;
|
||||
} else if (result == EINVAL) { // no hints were requested
|
||||
return Result::ErrorInvalidHandle;
|
||||
} else if (result == EBUSY) { // the hint was rate limited
|
||||
return Result::ErrorInvalidRate;
|
||||
} else if (result == EPIPE) { // communication with the system service has failed
|
||||
return Result::ErrorNoService;
|
||||
} else if (result == ENOTSUP) { // the hint is not supported
|
||||
return Result::ErrorUnavailable;
|
||||
} else {
|
||||
return Result::ErrorInternal; // Unknown error
|
||||
}
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().endSection();
|
||||
}
|
||||
}
|
||||
|
||||
oboe::Result AdpfWrapper::notifyWorkloadReset(bool cpu, bool gpu, const char* debugName) {
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
bool traceEnabled = Trace::getInstance().isEnabled();
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().beginSection("notifyWorkloadReset");
|
||||
}
|
||||
if (gAPH_notifyWorkloadResetFn == nullptr) {
|
||||
return Result::ErrorUnimplemented;
|
||||
}
|
||||
if (mHintSession == nullptr) {
|
||||
return Result::ErrorClosed;
|
||||
}
|
||||
int result = gAPH_notifyWorkloadResetFn(mHintSession, cpu, gpu, debugName);
|
||||
if (result == 0) {
|
||||
return Result::OK;
|
||||
} else if (result == EINVAL) { // no hints were requested
|
||||
return Result::ErrorInvalidHandle;
|
||||
} else if (result == EBUSY) { // the hint was rate limited
|
||||
return Result::ErrorInvalidRate;
|
||||
} else if (result == EPIPE) { // communication with the system service has failed
|
||||
return Result::ErrorNoService;
|
||||
} else if (result == ENOTSUP) { // the hint is not supported
|
||||
return Result::ErrorUnavailable;
|
||||
} else {
|
||||
return Result::ErrorInternal; // Unknown error
|
||||
}
|
||||
if (traceEnabled) {
|
||||
Trace::getInstance().endSection();
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Copyright 2021 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef SYNTHMARK_ADPF_WRAPPER_H
|
||||
#define SYNTHMARK_ADPF_WRAPPER_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <mutex>
|
||||
|
||||
#include "oboe/Definitions.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
struct APerformanceHintManager;
|
||||
struct APerformanceHintSession;
|
||||
|
||||
typedef struct APerformanceHintManager APerformanceHintManager;
|
||||
typedef struct APerformanceHintSession APerformanceHintSession;
|
||||
|
||||
class AdpfWrapper {
|
||||
public:
|
||||
/**
|
||||
* Create an ADPF session that can be used to boost performance.
|
||||
* @param threadId
|
||||
* @param targetDurationNanos - nominal period of isochronous task
|
||||
* @return zero or negative error
|
||||
*/
|
||||
int open(pid_t threadId,
|
||||
int64_t targetDurationNanos);
|
||||
|
||||
bool isOpen() const {
|
||||
return (mHintSession != nullptr);
|
||||
}
|
||||
|
||||
void close();
|
||||
|
||||
/**
|
||||
* Call this at the beginning of the callback that you are measuring.
|
||||
*/
|
||||
void onBeginCallback();
|
||||
|
||||
/**
|
||||
* Call this at the end of the callback that you are measuring.
|
||||
* It is OK to skip this if you have a short callback.
|
||||
*/
|
||||
void onEndCallback(double durationScaler);
|
||||
|
||||
/**
|
||||
* For internal use only!
|
||||
* This is a hack for communicating with experimental versions of ADPF.
|
||||
* @param enabled
|
||||
*/
|
||||
static void setUseAlternative(bool enabled) {
|
||||
sUseAlternativeHack = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Report the measured duration of a callback.
|
||||
* This is normally called by onEndCallback().
|
||||
* You may want to call this directly in order to give an advance hint of a jump in workload.
|
||||
* @param actualDurationNanos
|
||||
*/
|
||||
void reportActualDuration(int64_t actualDurationNanos);
|
||||
|
||||
void reportWorkload(int32_t appWorkload);
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming increase in the workload of an audio callback
|
||||
* bound to this session. The user can specify whether the increase is expected to be
|
||||
* on the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* rate limiter.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @param cpu Indicates if the workload increase is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload increase is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorClosed if open was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
oboe::Result notifyWorkloadIncrease(bool cpu, bool gpu, const char* debugName);
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming reset in the workload of an audio callback
|
||||
* bound to this session, or the imminent start of a new workload. The user can specify
|
||||
* whether the reset is expected to affect the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* this load tracking.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @param cpu Indicates if the workload reset is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload reset is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorClosed if open was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
oboe::Result notifyWorkloadReset(bool cpu, bool gpu, const char* debugName);
|
||||
|
||||
/**
|
||||
* Informs the framework of an upcoming one-off expensive frame for an audio callback
|
||||
* bound to this session. This frame will be treated as not representative of the workload as a
|
||||
* whole, and it will be discarded the purposes of load tracking. The user can specify
|
||||
* whether the workload spike is expected to be on the CPU, GPU, or both.
|
||||
*
|
||||
* Sending hints for both CPU and GPU counts as two separate hints for the purposes of the
|
||||
* rate limiter.
|
||||
*
|
||||
* This was introduced in Android API Level 36
|
||||
*
|
||||
* @param cpu Indicates if the workload spike is expected to affect the CPU.
|
||||
* @param gpu Indicates if the workload spike is expected to affect the GPU.
|
||||
* @param debugName A required string used to identify this specific hint during
|
||||
* tracing. This debug string will only be held for the duration of the
|
||||
* method, and can be safely discarded after.
|
||||
*
|
||||
* @return Result::OK on success.
|
||||
* Result::ErrorClosed if open was not called.
|
||||
* Result::ErrorUnimplemented if the API is not supported.
|
||||
* Result::ErrorInvalidHandle if no hints were requested.
|
||||
* Result::ErrorInvalidRate if the hint was rate limited.
|
||||
* Result::ErrorNoService if communication with the system service has failed.
|
||||
* Result::ErrorUnavailable if the hint is not supported.
|
||||
*/
|
||||
oboe::Result notifyWorkloadSpike(bool cpu, bool gpu, const char* debugName);
|
||||
|
||||
private:
|
||||
std::mutex mLock;
|
||||
APerformanceHintSession *mHintSession = nullptr;
|
||||
int64_t mBeginCallbackNanos = 0;
|
||||
static bool sUseAlternativeHack;
|
||||
int32_t mPreviousWorkload = 0;
|
||||
double mNanosPerWorkloadUnit = 0.0;
|
||||
};
|
||||
|
||||
}
|
||||
#endif //SYNTHMARK_ADPF_WRAPPER_H
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include "AudioSourceCaller.h"
|
||||
|
||||
using namespace oboe;
|
||||
using namespace flowgraph;
|
||||
|
||||
int32_t AudioSourceCaller::onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) {
|
||||
AudioStreamDataCallback *callback = mStream->getDataCallback();
|
||||
int32_t result = 0;
|
||||
int32_t numFrames = numBytes / mStream->getBytesPerFrame();
|
||||
if (callback != nullptr) {
|
||||
DataCallbackResult callbackResult = callback->onAudioReady(mStream, buffer, numFrames);
|
||||
// onAudioReady() does not return the number of bytes processed so we have to assume all.
|
||||
result = (callbackResult == DataCallbackResult::Continue)
|
||||
? numBytes
|
||||
: -1;
|
||||
} else {
|
||||
auto readResult = mStream->read(buffer, numFrames, mTimeoutNanos);
|
||||
if (!readResult) return (int32_t) readResult.error();
|
||||
result = readResult.value() * mStream->getBytesPerFrame();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_AUDIO_SOURCE_CALLER_H
|
||||
#define OBOE_AUDIO_SOURCE_CALLER_H
|
||||
|
||||
#include "OboeDebug.h"
|
||||
#include "oboe/Oboe.h"
|
||||
|
||||
#include "flowgraph/FlowGraphNode.h"
|
||||
#include "FixedBlockReader.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class AudioStreamCallback;
|
||||
class AudioStream;
|
||||
|
||||
/**
|
||||
* For output streams that use a callback, call the application for more data.
|
||||
* For input streams that do not use a callback, read from the stream.
|
||||
*/
|
||||
class AudioSourceCaller : public flowgraph::FlowGraphSource, public FixedBlockProcessor {
|
||||
public:
|
||||
AudioSourceCaller(int32_t channelCount, int32_t framesPerCallback, int32_t bytesPerSample)
|
||||
: FlowGraphSource(channelCount)
|
||||
, mBlockReader(*this) {
|
||||
mBlockReader.open(channelCount * framesPerCallback * bytesPerSample);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the stream to use as a source of data.
|
||||
* @param stream
|
||||
*/
|
||||
void setStream(oboe::AudioStream *stream) {
|
||||
mStream = stream;
|
||||
}
|
||||
|
||||
oboe::AudioStream *getStream() {
|
||||
return mStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeout value to use when calling audioStream->read().
|
||||
* @param timeoutNanos Zero for no timeout or time in nanoseconds.
|
||||
*/
|
||||
void setTimeoutNanos(int64_t timeoutNanos) {
|
||||
mTimeoutNanos = timeoutNanos;
|
||||
}
|
||||
|
||||
int64_t getTimeoutNanos() const {
|
||||
return mTimeoutNanos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called internally for block size adaptation.
|
||||
* @param buffer
|
||||
* @param numBytes
|
||||
* @return
|
||||
*/
|
||||
int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) override;
|
||||
|
||||
protected:
|
||||
oboe::AudioStream *mStream = nullptr;
|
||||
int64_t mTimeoutNanos = 0;
|
||||
|
||||
FixedBlockReader mBlockReader;
|
||||
};
|
||||
|
||||
}
|
||||
#endif //OBOE_AUDIO_SOURCE_CALLER_H
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
/*
|
||||
* Copyright 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <pthread.h>
|
||||
#include <thread>
|
||||
|
||||
#include "oboe/AudioClock.h"
|
||||
#include "oboe/AudioStream.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "oboe/Utilities.h"
|
||||
#include "OboeDebug.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/*
|
||||
* AudioStream
|
||||
*/
|
||||
AudioStream::AudioStream(const AudioStreamBuilder &builder)
|
||||
: AudioStreamBase(builder) {
|
||||
LOGD("Constructor for AudioStream at %p", this);
|
||||
}
|
||||
|
||||
AudioStream::~AudioStream() {
|
||||
// This is to help debug use after free bugs.
|
||||
LOGD("Destructor for AudioStream at %p", this);
|
||||
}
|
||||
|
||||
Result AudioStream::close() {
|
||||
closePerformanceHint();
|
||||
// Update local counters so they can be read after the close.
|
||||
updateFramesWritten();
|
||||
updateFramesRead();
|
||||
return Result::OK;
|
||||
}
|
||||
|
||||
// Call this from fireDataCallback() if you want to monitor CPU scheduler.
|
||||
void AudioStream::checkScheduler() {
|
||||
int scheduler = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK; // for current thread
|
||||
if (scheduler != mPreviousScheduler) {
|
||||
LOGD("AudioStream::%s() scheduler = %s", __func__,
|
||||
((scheduler == SCHED_FIFO) ? "SCHED_FIFO" :
|
||||
((scheduler == SCHED_OTHER) ? "SCHED_OTHER" :
|
||||
((scheduler == SCHED_RR) ? "SCHED_RR" : "UNKNOWN")))
|
||||
);
|
||||
mPreviousScheduler = scheduler;
|
||||
}
|
||||
}
|
||||
|
||||
DataCallbackResult AudioStream::fireDataCallback(void *audioData, int32_t numFrames) {
|
||||
if (!isDataCallbackEnabled()) {
|
||||
LOGW("AudioStream::%s() called with data callback disabled!", __func__);
|
||||
return DataCallbackResult::Stop; // Should not be getting called
|
||||
}
|
||||
|
||||
beginPerformanceHintInCallback();
|
||||
|
||||
// Call the app to do the work.
|
||||
DataCallbackResult result;
|
||||
if (mDataCallback) {
|
||||
result = mDataCallback->onAudioReady(this, audioData, numFrames);
|
||||
} else {
|
||||
result = onDefaultCallback(audioData, numFrames);
|
||||
}
|
||||
// On Oreo, we might get called after returning stop.
|
||||
// So block that here.
|
||||
setDataCallbackEnabled(result == DataCallbackResult::Continue);
|
||||
|
||||
endPerformanceHintInCallback(numFrames);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int32_t AudioStream::firePartialDataCallback(void *audioData, int numFrames) {
|
||||
if (!isDataCallbackEnabled()) {
|
||||
LOGW("AudioStream::%s() called with data callback disabled!", __func__);
|
||||
return -1; // Should not be getting called
|
||||
}
|
||||
|
||||
beginPerformanceHintInCallback();
|
||||
|
||||
// Call the app to do the work.
|
||||
int32_t result;
|
||||
if (mPartialDataCallback) {
|
||||
result = mPartialDataCallback->onPartialAudioReady(this, audioData, numFrames);
|
||||
} else {
|
||||
LOGE("AudioStream::%s, called without a partial data callback!", __func__);
|
||||
result = -1; // This should not happen, return negative value to stop the stream.
|
||||
}
|
||||
|
||||
endPerformanceHintInCallback(numFrames);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AudioStream::waitForStateTransition(StreamState startingState,
|
||||
StreamState endingState,
|
||||
int64_t timeoutNanoseconds)
|
||||
{
|
||||
StreamState state;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mLock);
|
||||
state = getState();
|
||||
if (state == StreamState::Closed) {
|
||||
return Result::ErrorClosed;
|
||||
} else if (state == StreamState::Disconnected) {
|
||||
return Result::ErrorDisconnected;
|
||||
}
|
||||
}
|
||||
|
||||
StreamState nextState = state;
|
||||
// TODO Should this be a while()?!
|
||||
if (state == startingState && state != endingState) {
|
||||
Result result = waitForStateChange(state, &nextState, timeoutNanoseconds);
|
||||
if (result != Result::OK) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (nextState != endingState) {
|
||||
return Result::ErrorInvalidState;
|
||||
} else {
|
||||
return Result::OK;
|
||||
}
|
||||
}
|
||||
|
||||
Result AudioStream::start(int64_t timeoutNanoseconds)
|
||||
{
|
||||
Result result = requestStart();
|
||||
if (result != Result::OK) return result;
|
||||
if (timeoutNanoseconds <= 0) return result;
|
||||
result = waitForStateTransition(StreamState::Starting,
|
||||
StreamState::Started, timeoutNanoseconds);
|
||||
if (result != Result::OK) {
|
||||
LOGE("AudioStream::%s() timed out before moving from STARTING to STARTED", __func__);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AudioStream::pause(int64_t timeoutNanoseconds)
|
||||
{
|
||||
Result result = requestPause();
|
||||
if (result != Result::OK) return result;
|
||||
if (timeoutNanoseconds <= 0) return result;
|
||||
return waitForStateTransition(StreamState::Pausing,
|
||||
StreamState::Paused, timeoutNanoseconds);
|
||||
}
|
||||
|
||||
Result AudioStream::flush(int64_t timeoutNanoseconds)
|
||||
{
|
||||
Result result = requestFlush();
|
||||
if (result != Result::OK) return result;
|
||||
if (timeoutNanoseconds <= 0) return result;
|
||||
return waitForStateTransition(StreamState::Flushing,
|
||||
StreamState::Flushed, timeoutNanoseconds);
|
||||
}
|
||||
|
||||
Result AudioStream::stop(int64_t timeoutNanoseconds)
|
||||
{
|
||||
Result result = requestStop();
|
||||
if (result != Result::OK) return result;
|
||||
if (timeoutNanoseconds <= 0) return result;
|
||||
return waitForStateTransition(StreamState::Stopping,
|
||||
StreamState::Stopped, timeoutNanoseconds);
|
||||
}
|
||||
|
||||
int32_t AudioStream::getBytesPerSample() const {
|
||||
return convertFormatToSizeInBytes(mFormat);
|
||||
}
|
||||
|
||||
int64_t AudioStream::getFramesRead() {
|
||||
updateFramesRead();
|
||||
return mFramesRead;
|
||||
}
|
||||
|
||||
int64_t AudioStream::getFramesWritten() {
|
||||
updateFramesWritten();
|
||||
return mFramesWritten;
|
||||
}
|
||||
|
||||
ResultWithValue<int32_t> AudioStream::getAvailableFrames() {
|
||||
int64_t readCounter = getFramesRead();
|
||||
if (readCounter < 0) return ResultWithValue<int32_t>::createBasedOnSign(readCounter);
|
||||
int64_t writeCounter = getFramesWritten();
|
||||
if (writeCounter < 0) return ResultWithValue<int32_t>::createBasedOnSign(writeCounter);
|
||||
int32_t framesAvailable = writeCounter - readCounter;
|
||||
return ResultWithValue<int32_t>(framesAvailable);
|
||||
}
|
||||
|
||||
ResultWithValue<int32_t> AudioStream::waitForAvailableFrames(int32_t numFrames,
|
||||
int64_t timeoutNanoseconds) {
|
||||
if (numFrames == 0) return Result::OK;
|
||||
if (numFrames < 0) return Result::ErrorOutOfRange;
|
||||
|
||||
// Make sure we don't try to wait for more frames than the buffer can hold.
|
||||
// Subtract framesPerBurst because this is often called from a callback
|
||||
// and we don't want to be sleeping if the buffer is close to overflowing.
|
||||
const int32_t maxAvailableFrames = getBufferCapacityInFrames() - getFramesPerBurst();
|
||||
numFrames = std::min(numFrames, maxAvailableFrames);
|
||||
// The capacity should never be less than one burst. But clip to zero just in case.
|
||||
numFrames = std::max(0, numFrames);
|
||||
|
||||
int64_t framesAvailable = 0;
|
||||
int64_t burstInNanos = getFramesPerBurst() * kNanosPerSecond / getSampleRate();
|
||||
bool ready = false;
|
||||
int64_t deadline = AudioClock::getNanoseconds() + timeoutNanoseconds;
|
||||
do {
|
||||
ResultWithValue<int32_t> result = getAvailableFrames();
|
||||
if (!result) return result;
|
||||
framesAvailable = result.value();
|
||||
ready = (framesAvailable >= numFrames);
|
||||
if (!ready) {
|
||||
int64_t now = AudioClock::getNanoseconds();
|
||||
if (now > deadline) break;
|
||||
AudioClock::sleepForNanos(burstInNanos);
|
||||
}
|
||||
} while (!ready);
|
||||
return (!ready)
|
||||
? ResultWithValue<int32_t>(Result::ErrorTimeout)
|
||||
: ResultWithValue<int32_t>(framesAvailable);
|
||||
}
|
||||
|
||||
ResultWithValue<FrameTimestamp> AudioStream::getTimestamp(clockid_t clockId) {
|
||||
FrameTimestamp frame;
|
||||
Result result = getTimestamp(clockId, &frame.position, &frame.timestamp);
|
||||
if (result == Result::OK){
|
||||
return ResultWithValue<FrameTimestamp>(frame);
|
||||
} else {
|
||||
return ResultWithValue<FrameTimestamp>(static_cast<Result>(result));
|
||||
}
|
||||
}
|
||||
|
||||
void AudioStream::calculateDefaultDelayBeforeCloseMillis() {
|
||||
// Calculate delay time before close based on burst duration.
|
||||
// Start with a burst duration then add 1 msec as a safety margin.
|
||||
mDelayBeforeCloseMillis = std::clamp(1 + (mFramesPerBurst * 1000) / getSampleRate(),
|
||||
kMinDelayBeforeCloseMillis,
|
||||
kMaxDelayBeforeCloseMillis);
|
||||
LOGD("calculateDefaultDelayBeforeCloseMillis() default = %d",
|
||||
static_cast<int>(mDelayBeforeCloseMillis));
|
||||
}
|
||||
|
||||
} // namespace oboe
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
|
||||
#include "aaudio/AAudioExtensions.h"
|
||||
#include "aaudio/AudioStreamAAudio.h"
|
||||
#include "OboeDebug.h"
|
||||
#include "oboe/Oboe.h"
|
||||
#include "oboe/AudioStreamBuilder.h"
|
||||
#include "opensles/AudioInputStreamOpenSLES.h"
|
||||
#include "opensles/AudioOutputStreamOpenSLES.h"
|
||||
#include "opensles/AudioStreamOpenSLES.h"
|
||||
#include "QuirksManager.h"
|
||||
|
||||
#ifndef DISABLE_CONVERSION
|
||||
#include "FilterAudioStream.h"
|
||||
#endif
|
||||
|
||||
bool oboe::OboeGlobals::mWorkaroundsEnabled = true;
|
||||
|
||||
namespace oboe {
|
||||
|
||||
/**
|
||||
* The following default values are used when oboe does not have any better way of determining the optimal values
|
||||
* for an audio stream. This can happen when:
|
||||
*
|
||||
* - Client is creating a stream on API < 26 (OpenSLES) but has not supplied the optimal sample
|
||||
* rate and/or frames per burst
|
||||
* - Client is creating a stream on API 16 (OpenSLES) where AudioManager.PROPERTY_OUTPUT_* values
|
||||
* are not available
|
||||
*/
|
||||
int32_t DefaultStreamValues::SampleRate = 48000; // Common rate for mobile audio and video
|
||||
int32_t DefaultStreamValues::FramesPerBurst = 192; // 4 msec at 48000 Hz
|
||||
int32_t DefaultStreamValues::ChannelCount = 2; // Stereo
|
||||
|
||||
constexpr int knumBurstsForLowLatencyStreams = 2;
|
||||
|
||||
#ifndef OBOE_ENABLE_AAUDIO
|
||||
// Set OBOE_ENABLE_AAUDIO to 0 if you want to disable the AAudio API.
|
||||
// This might be useful if you want to force all the unit tests to use OpenSL ES.
|
||||
#define OBOE_ENABLE_AAUDIO 1
|
||||
#endif
|
||||
|
||||
bool AudioStreamBuilder::isAAudioSupported() {
|
||||
return AudioStreamAAudio::isSupported() && OBOE_ENABLE_AAUDIO;
|
||||
}
|
||||
|
||||
bool AudioStreamBuilder::isAAudioRecommended() {
|
||||
// See https://github.com/google/oboe/issues/40,
|
||||
// AAudio may not be stable on Android O, depending on how it is used.
|
||||
// To be safe, use AAudio only on O_MR1 and above.
|
||||
return (getSdkVersion() >= __ANDROID_API_O_MR1__) && isAAudioSupported();
|
||||
}
|
||||
|
||||
AudioStream *AudioStreamBuilder::build() {
|
||||
AudioStream *stream = nullptr;
|
||||
if (isAAudioRecommended() && mAudioApi != AudioApi::OpenSLES) {
|
||||
stream = new AudioStreamAAudio(*this);
|
||||
} else if (isAAudioSupported() && mAudioApi == AudioApi::AAudio) {
|
||||
stream = new AudioStreamAAudio(*this);
|
||||
LOGE("Creating AAudio stream on 8.0 because it was specified. This is error prone.");
|
||||
} else {
|
||||
if (getDirection() == oboe::Direction::Output) {
|
||||
stream = new AudioOutputStreamOpenSLES(*this);
|
||||
} else if (getDirection() == oboe::Direction::Input) {
|
||||
stream = new AudioInputStreamOpenSLES(*this);
|
||||
}
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
bool AudioStreamBuilder::isCompatible(AudioStreamBase &other) {
|
||||
return (getSampleRate() == oboe::Unspecified || getSampleRate() == other.getSampleRate())
|
||||
&& (getFormat() == (AudioFormat)oboe::Unspecified || getFormat() == other.getFormat())
|
||||
&& (getFramesPerDataCallback() == oboe::Unspecified || getFramesPerDataCallback() == other.getFramesPerDataCallback())
|
||||
&& (getChannelCount() == oboe::Unspecified || getChannelCount() == other.getChannelCount());
|
||||
}
|
||||
|
||||
Result AudioStreamBuilder::openStream(AudioStream **streamPP) {
|
||||
LOGW("Passing AudioStream pointer deprecated, Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.");
|
||||
return openStreamInternal(streamPP);
|
||||
}
|
||||
|
||||
Result AudioStreamBuilder::openStreamInternal(AudioStream **streamPP) {
|
||||
auto result = isValidConfig();
|
||||
if (result != Result::OK) {
|
||||
LOGW("%s() invalid config. Error %s", __func__, oboe::convertToText(result));
|
||||
return result;
|
||||
}
|
||||
if (mPartialDataCallback != nullptr &&
|
||||
(!OboeExtensions::isPartialDataCallbackSupported() || !willUseAAudio())) {
|
||||
LOGE("%s() Partial data callback is not supported.", __func__);
|
||||
return Result::ErrorIllegalArgument;
|
||||
}
|
||||
|
||||
#ifndef OBOE_SUPPRESS_LOG_SPAM
|
||||
LOGI("%s() %s -------- %s --------",
|
||||
__func__, getDirection() == Direction::Input ? "INPUT" : "OUTPUT", getVersionText());
|
||||
#endif
|
||||
|
||||
if (streamPP == nullptr) {
|
||||
return Result::ErrorNull;
|
||||
}
|
||||
*streamPP = nullptr;
|
||||
|
||||
AudioStream *streamP = nullptr;
|
||||
|
||||
// Maybe make a FilterInputStream.
|
||||
AudioStreamBuilder childBuilder(*this);
|
||||
|
||||
#ifndef DISABLE_CONVERSION
|
||||
// Check need for conversion and modify childBuilder for optimal stream.
|
||||
bool conversionNeeded = QuirksManager::getInstance().isConversionNeeded(*this, childBuilder);
|
||||
// Do we need to make a child stream and convert.
|
||||
if (conversionNeeded) {
|
||||
if (isPartialDataCallbackSpecified()) {
|
||||
LOGW("%s(), partial data callback is not supported when data conversion is required",
|
||||
__func__);
|
||||
return Result::ErrorIllegalArgument;
|
||||
}
|
||||
AudioStream *tempStream;
|
||||
result = childBuilder.openStreamInternal(&tempStream);
|
||||
if (result != Result::OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (isCompatible(*tempStream)) {
|
||||
// The child stream would work as the requested stream so we can just use it directly.
|
||||
*streamPP = tempStream;
|
||||
return result;
|
||||
} else {
|
||||
AudioStreamBuilder parentBuilder = *this;
|
||||
// Build a stream that is as close as possible to the childStream.
|
||||
if (getFormat() == oboe::AudioFormat::Unspecified) {
|
||||
parentBuilder.setFormat(tempStream->getFormat());
|
||||
}
|
||||
if (getChannelCount() == oboe::Unspecified) {
|
||||
parentBuilder.setChannelCount(tempStream->getChannelCount());
|
||||
}
|
||||
if (getSampleRate() == oboe::Unspecified) {
|
||||
parentBuilder.setSampleRate(tempStream->getSampleRate());
|
||||
}
|
||||
if (getFramesPerDataCallback() == oboe::Unspecified) {
|
||||
parentBuilder.setFramesPerCallback(tempStream->getFramesPerDataCallback());
|
||||
}
|
||||
|
||||
// Use childStream in a FilterAudioStream.
|
||||
LOGI("%s() create a FilterAudioStream for data conversion.", __func__);
|
||||
std::shared_ptr<AudioStream> childStream(tempStream);
|
||||
FilterAudioStream *filterStream = new FilterAudioStream(parentBuilder, childStream);
|
||||
childStream->setWeakThis(childStream);
|
||||
result = filterStream->configureFlowGraph();
|
||||
if (result != Result::OK) {
|
||||
filterStream->close();
|
||||
delete filterStream;
|
||||
// Just open streamP the old way.
|
||||
} else {
|
||||
streamP = static_cast<AudioStream *>(filterStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (streamP == nullptr) {
|
||||
streamP = build();
|
||||
if (streamP == nullptr) {
|
||||
return Result::ErrorNull;
|
||||
}
|
||||
}
|
||||
|
||||
// If MMAP has a problem in this case then disable it temporarily.
|
||||
bool wasMMapOriginallyEnabled = AAudioExtensions::getInstance().isMMapEnabled();
|
||||
bool wasMMapTemporarilyDisabled = false;
|
||||
if (wasMMapOriginallyEnabled) {
|
||||
bool isMMapSafe = QuirksManager::getInstance().isMMapSafe(childBuilder);
|
||||
if (!isMMapSafe) {
|
||||
AAudioExtensions::getInstance().setMMapEnabled(false);
|
||||
wasMMapTemporarilyDisabled = true;
|
||||
}
|
||||
}
|
||||
result = streamP->open();
|
||||
if (wasMMapTemporarilyDisabled) {
|
||||
AAudioExtensions::getInstance().setMMapEnabled(wasMMapOriginallyEnabled); // restore original
|
||||
}
|
||||
if (result == Result::OK) {
|
||||
// AAudio supports setBufferSizeInFrames() so use it.
|
||||
if (streamP->getAudioApi() == AudioApi::AAudio) {
|
||||
int32_t optimalBufferSize = -1;
|
||||
// Use a reasonable default buffer size.
|
||||
if (streamP->getDirection() == Direction::Input) {
|
||||
// For input, small size does not improve latency because the stream is usually
|
||||
// run close to empty. And a low size can result in XRuns so always use the maximum.
|
||||
optimalBufferSize = streamP->getBufferCapacityInFrames();
|
||||
} else if (streamP->getPerformanceMode() == PerformanceMode::LowLatency
|
||||
&& streamP->getDirection() == Direction::Output) { // Output check is redundant.
|
||||
optimalBufferSize = streamP->getFramesPerBurst() *
|
||||
knumBurstsForLowLatencyStreams;
|
||||
}
|
||||
if (optimalBufferSize >= 0) {
|
||||
auto setBufferResult = streamP->setBufferSizeInFrames(optimalBufferSize);
|
||||
if (!setBufferResult) {
|
||||
LOGW("Failed to setBufferSizeInFrames(%d). Error was %s",
|
||||
optimalBufferSize,
|
||||
convertToText(setBufferResult.error()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*streamPP = streamP;
|
||||
} else {
|
||||
delete streamP;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AudioStreamBuilder::openManagedStream(oboe::ManagedStream &stream) {
|
||||
LOGW("`openManagedStream` is deprecated. Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.");
|
||||
stream.reset();
|
||||
AudioStream *streamptr;
|
||||
auto result = openStream(&streamptr);
|
||||
stream.reset(streamptr);
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AudioStreamBuilder::openStream(std::shared_ptr<AudioStream> &sharedStream) {
|
||||
sharedStream.reset();
|
||||
AudioStream *streamptr;
|
||||
auto result = openStreamInternal(&streamptr);
|
||||
if (result == Result::OK) {
|
||||
sharedStream.reset(streamptr);
|
||||
// Save a weak_ptr in the stream for use with callbacks.
|
||||
streamptr->setWeakThis(sharedStream);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace oboe
|
||||
Vendored
+266
@@ -0,0 +1,266 @@
|
||||
/*
|
||||
* Copyright (C) 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "OboeDebug.h"
|
||||
#include "DataConversionFlowGraph.h"
|
||||
#include "SourceFloatCaller.h"
|
||||
#include "SourceI16Caller.h"
|
||||
#include "SourceI24Caller.h"
|
||||
#include "SourceI32Caller.h"
|
||||
|
||||
#include <flowgraph/MonoToMultiConverter.h>
|
||||
#include <flowgraph/MultiToMonoConverter.h>
|
||||
#include <flowgraph/RampLinear.h>
|
||||
#include <flowgraph/SinkFloat.h>
|
||||
#include <flowgraph/SinkI16.h>
|
||||
#include <flowgraph/SinkI24.h>
|
||||
#include <flowgraph/SinkI32.h>
|
||||
#include <flowgraph/SourceFloat.h>
|
||||
#include <flowgraph/SourceI16.h>
|
||||
#include <flowgraph/SourceI24.h>
|
||||
#include <flowgraph/SourceI32.h>
|
||||
#include <flowgraph/SampleRateConverter.h>
|
||||
|
||||
using namespace oboe;
|
||||
using namespace flowgraph;
|
||||
using namespace resampler;
|
||||
|
||||
void DataConversionFlowGraph::setSource(const void *buffer, int32_t numFrames) {
|
||||
mSource->setData(buffer, numFrames);
|
||||
}
|
||||
|
||||
static MultiChannelResampler::Quality convertOboeSRQualityToMCR(SampleRateConversionQuality quality) {
|
||||
switch (quality) {
|
||||
case SampleRateConversionQuality::Fastest:
|
||||
return MultiChannelResampler::Quality::Fastest;
|
||||
case SampleRateConversionQuality::Low:
|
||||
return MultiChannelResampler::Quality::Low;
|
||||
default:
|
||||
case SampleRateConversionQuality::Medium:
|
||||
return MultiChannelResampler::Quality::Medium;
|
||||
case SampleRateConversionQuality::High:
|
||||
return MultiChannelResampler::Quality::High;
|
||||
case SampleRateConversionQuality::Best:
|
||||
return MultiChannelResampler::Quality::Best;
|
||||
}
|
||||
}
|
||||
|
||||
// Chain together multiple processors.
|
||||
// Callback Output
|
||||
// Use SourceCaller that calls original app callback from the flowgraph.
|
||||
// The child callback from FilteredAudioStream read()s from the flowgraph.
|
||||
// Callback Input
|
||||
// Child callback from FilteredAudioStream writes()s to the flowgraph.
|
||||
// The output of the flowgraph goes through a BlockWriter to the app callback.
|
||||
// Blocking Write
|
||||
// Write buffer is set on an AudioSource.
|
||||
// Data is pulled through the graph and written to the child stream.
|
||||
// Blocking Read
|
||||
// Reads in a loop from the flowgraph Sink to fill the read buffer.
|
||||
// A SourceCaller then does a blocking read from the child Stream.
|
||||
//
|
||||
Result DataConversionFlowGraph::configure(AudioStream *sourceStream, AudioStream *sinkStream) {
|
||||
|
||||
FlowGraphPortFloatOutput *lastOutput = nullptr;
|
||||
|
||||
bool isOutput = sourceStream->getDirection() == Direction::Output;
|
||||
bool isInput = !isOutput;
|
||||
mFilterStream = isOutput ? sourceStream : sinkStream;
|
||||
|
||||
AudioFormat sourceFormat = sourceStream->getFormat();
|
||||
int32_t sourceChannelCount = sourceStream->getChannelCount();
|
||||
int32_t sourceSampleRate = sourceStream->getSampleRate();
|
||||
int32_t sourceFramesPerCallback = sourceStream->getFramesPerDataCallback();
|
||||
|
||||
AudioFormat sinkFormat = sinkStream->getFormat();
|
||||
int32_t sinkChannelCount = sinkStream->getChannelCount();
|
||||
int32_t sinkSampleRate = sinkStream->getSampleRate();
|
||||
int32_t sinkFramesPerCallback = sinkStream->getFramesPerDataCallback();
|
||||
|
||||
LOGI("%s() flowgraph converts channels: %d to %d, format: %s to %s"
|
||||
", rate: %d to %d, cbsize: %d to %d, qual = %s",
|
||||
__func__,
|
||||
sourceChannelCount, sinkChannelCount,
|
||||
oboe::convertToText(sourceFormat), oboe::convertToText(sinkFormat),
|
||||
sourceSampleRate, sinkSampleRate,
|
||||
sourceFramesPerCallback, sinkFramesPerCallback,
|
||||
oboe::convertToText(sourceStream->getSampleRateConversionQuality()));
|
||||
|
||||
// Source
|
||||
// IF OUTPUT and using a callback then call back to the app using a SourceCaller.
|
||||
// OR IF INPUT and NOT using a callback then read from the child stream using a SourceCaller.
|
||||
bool isDataCallbackSpecified = sourceStream->isDataCallbackSpecified();
|
||||
if ((isDataCallbackSpecified && isOutput)
|
||||
|| (!isDataCallbackSpecified && isInput)) {
|
||||
int32_t actualSourceFramesPerCallback = (sourceFramesPerCallback == kUnspecified)
|
||||
? sourceStream->getFramesPerBurst()
|
||||
: sourceFramesPerCallback;
|
||||
switch (sourceFormat) {
|
||||
case AudioFormat::Float:
|
||||
mSourceCaller = std::make_unique<SourceFloatCaller>(sourceChannelCount,
|
||||
actualSourceFramesPerCallback);
|
||||
break;
|
||||
case AudioFormat::I16:
|
||||
mSourceCaller = std::make_unique<SourceI16Caller>(sourceChannelCount,
|
||||
actualSourceFramesPerCallback);
|
||||
break;
|
||||
case AudioFormat::I24:
|
||||
mSourceCaller = std::make_unique<SourceI24Caller>(sourceChannelCount,
|
||||
actualSourceFramesPerCallback);
|
||||
break;
|
||||
case AudioFormat::I32:
|
||||
mSourceCaller = std::make_unique<SourceI32Caller>(sourceChannelCount,
|
||||
actualSourceFramesPerCallback);
|
||||
break;
|
||||
default:
|
||||
LOGE("%s() Unsupported source caller format = %d", __func__, static_cast<int>(sourceFormat));
|
||||
return Result::ErrorIllegalArgument;
|
||||
}
|
||||
mSourceCaller->setStream(sourceStream);
|
||||
lastOutput = &mSourceCaller->output;
|
||||
} else {
|
||||
// IF OUTPUT and NOT using a callback then write to the child stream using a BlockWriter.
|
||||
// OR IF INPUT and using a callback then write to the app using a BlockWriter.
|
||||
switch (sourceFormat) {
|
||||
case AudioFormat::Float:
|
||||
mSource = std::make_unique<SourceFloat>(sourceChannelCount);
|
||||
break;
|
||||
case AudioFormat::I16:
|
||||
mSource = std::make_unique<SourceI16>(sourceChannelCount);
|
||||
break;
|
||||
case AudioFormat::I24:
|
||||
mSource = std::make_unique<SourceI24>(sourceChannelCount);
|
||||
break;
|
||||
case AudioFormat::I32:
|
||||
mSource = std::make_unique<SourceI32>(sourceChannelCount);
|
||||
break;
|
||||
default:
|
||||
LOGE("%s() Unsupported source format = %d", __func__, static_cast<int>(sourceFormat));
|
||||
return Result::ErrorIllegalArgument;
|
||||
}
|
||||
if (isInput) {
|
||||
int32_t actualSinkFramesPerCallback = (sinkFramesPerCallback == kUnspecified)
|
||||
? sinkStream->getFramesPerBurst()
|
||||
: sinkFramesPerCallback;
|
||||
// The BlockWriter is after the Sink so use the SinkStream size.
|
||||
mBlockWriter.open(actualSinkFramesPerCallback * sinkStream->getBytesPerFrame());
|
||||
mAppBuffer = std::make_unique<uint8_t[]>(
|
||||
kDefaultBufferSize * sinkStream->getBytesPerFrame());
|
||||
}
|
||||
lastOutput = &mSource->output;
|
||||
}
|
||||
|
||||
// If we are going to reduce the number of channels then do it before the
|
||||
// sample rate converter.
|
||||
if (sourceChannelCount > sinkChannelCount) {
|
||||
if (sinkChannelCount == 1) {
|
||||
mMultiToMonoConverter = std::make_unique<MultiToMonoConverter>(sourceChannelCount);
|
||||
lastOutput->connect(&mMultiToMonoConverter->input);
|
||||
lastOutput = &mMultiToMonoConverter->output;
|
||||
} else {
|
||||
mChannelCountConverter = std::make_unique<ChannelCountConverter>(
|
||||
sourceChannelCount,
|
||||
sinkChannelCount);
|
||||
lastOutput->connect(&mChannelCountConverter->input);
|
||||
lastOutput = &mChannelCountConverter->output;
|
||||
}
|
||||
}
|
||||
|
||||
// Sample Rate conversion
|
||||
if (sourceSampleRate != sinkSampleRate) {
|
||||
// Create a resampler to do the math.
|
||||
mResampler.reset(MultiChannelResampler::make(lastOutput->getSamplesPerFrame(),
|
||||
sourceSampleRate,
|
||||
sinkSampleRate,
|
||||
convertOboeSRQualityToMCR(
|
||||
sourceStream->getSampleRateConversionQuality())));
|
||||
// Make a flowgraph node that uses the resampler.
|
||||
mRateConverter = std::make_unique<SampleRateConverter>(lastOutput->getSamplesPerFrame(),
|
||||
*mResampler.get());
|
||||
lastOutput->connect(&mRateConverter->input);
|
||||
lastOutput = &mRateConverter->output;
|
||||
}
|
||||
|
||||
// Expand the number of channels if required.
|
||||
if (sourceChannelCount < sinkChannelCount) {
|
||||
if (sourceChannelCount == 1) {
|
||||
mMonoToMultiConverter = std::make_unique<MonoToMultiConverter>(sinkChannelCount);
|
||||
lastOutput->connect(&mMonoToMultiConverter->input);
|
||||
lastOutput = &mMonoToMultiConverter->output;
|
||||
} else {
|
||||
mChannelCountConverter = std::make_unique<ChannelCountConverter>(
|
||||
sourceChannelCount,
|
||||
sinkChannelCount);
|
||||
lastOutput->connect(&mChannelCountConverter->input);
|
||||
lastOutput = &mChannelCountConverter->output;
|
||||
}
|
||||
}
|
||||
|
||||
// Sink
|
||||
switch (sinkFormat) {
|
||||
case AudioFormat::Float:
|
||||
mSink = std::make_unique<SinkFloat>(sinkChannelCount);
|
||||
break;
|
||||
case AudioFormat::I16:
|
||||
mSink = std::make_unique<SinkI16>(sinkChannelCount);
|
||||
break;
|
||||
case AudioFormat::I24:
|
||||
mSink = std::make_unique<SinkI24>(sinkChannelCount);
|
||||
break;
|
||||
case AudioFormat::I32:
|
||||
mSink = std::make_unique<SinkI32>(sinkChannelCount);
|
||||
break;
|
||||
default:
|
||||
LOGE("%s() Unsupported sink format = %d", __func__, static_cast<int>(sinkFormat));
|
||||
return Result::ErrorIllegalArgument;;
|
||||
}
|
||||
lastOutput->connect(&mSink->input);
|
||||
|
||||
return Result::OK;
|
||||
}
|
||||
|
||||
int32_t DataConversionFlowGraph::read(void *buffer, int32_t numFrames, int64_t timeoutNanos) {
|
||||
if (mSourceCaller) {
|
||||
mSourceCaller->setTimeoutNanos(timeoutNanos);
|
||||
}
|
||||
int32_t numRead = mSink->read(buffer, numFrames);
|
||||
return numRead;
|
||||
}
|
||||
|
||||
// This is similar to pushing data through the flowgraph.
|
||||
int32_t DataConversionFlowGraph::write(void *inputBuffer, int32_t numFrames) {
|
||||
// Put the data from the input at the head of the flowgraph.
|
||||
mSource->setData(inputBuffer, numFrames);
|
||||
while (true) {
|
||||
// Pull and read some data in app format into a small buffer.
|
||||
int32_t framesRead = mSink->read(mAppBuffer.get(), flowgraph::kDefaultBufferSize);
|
||||
if (framesRead <= 0) break;
|
||||
// Write to a block adapter, which will call the destination whenever it has enough data.
|
||||
int32_t bytesRead = mBlockWriter.write(mAppBuffer.get(),
|
||||
framesRead * mFilterStream->getBytesPerFrame());
|
||||
if (bytesRead < 0) return bytesRead; // TODO review
|
||||
}
|
||||
return numFrames;
|
||||
}
|
||||
|
||||
int32_t DataConversionFlowGraph::onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) {
|
||||
int32_t numFrames = numBytes / mFilterStream->getBytesPerFrame();
|
||||
mCallbackResult = mFilterStream->getDataCallback()->onAudioReady(mFilterStream, buffer, numFrames);
|
||||
// TODO handle STOP from callback, process data remaining in the block adapter
|
||||
return numBytes;
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (C) 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef OBOE_OBOE_FLOW_GRAPH_H
|
||||
#define OBOE_OBOE_FLOW_GRAPH_H
|
||||
|
||||
#include <memory>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <flowgraph/ChannelCountConverter.h>
|
||||
#include <flowgraph/MonoToMultiConverter.h>
|
||||
#include <flowgraph/MultiToMonoConverter.h>
|
||||
#include <flowgraph/SampleRateConverter.h>
|
||||
#include <oboe/Definitions.h>
|
||||
#include "AudioSourceCaller.h"
|
||||
#include "FixedBlockWriter.h"
|
||||
|
||||
namespace oboe {
|
||||
|
||||
class AudioStream;
|
||||
class AudioSourceCaller;
|
||||
|
||||
/**
|
||||
* Convert PCM channels, format and sample rate for optimal latency.
|
||||
*/
|
||||
class DataConversionFlowGraph : public FixedBlockProcessor {
|
||||
public:
|
||||
|
||||
DataConversionFlowGraph()
|
||||
: mBlockWriter(*this) {}
|
||||
|
||||
void setSource(const void *buffer, int32_t numFrames);
|
||||
|
||||
/** Connect several modules together to convert from source to sink.
|
||||
* This should only be called once for each instance.
|
||||
*
|
||||
* @param sourceFormat
|
||||
* @param sourceChannelCount
|
||||
* @param sinkFormat
|
||||
* @param sinkChannelCount
|
||||
* @return
|
||||
*/
|
||||
oboe::Result configure(oboe::AudioStream *sourceStream, oboe::AudioStream *sinkStream);
|
||||
|
||||
int32_t read(void *buffer, int32_t numFrames, int64_t timeoutNanos);
|
||||
|
||||
int32_t write(void *buffer, int32_t numFrames);
|
||||
|
||||
int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) override;
|
||||
|
||||
DataCallbackResult getDataCallbackResult() {
|
||||
return mCallbackResult;
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<flowgraph::FlowGraphSourceBuffered> mSource;
|
||||
std::unique_ptr<AudioSourceCaller> mSourceCaller;
|
||||
std::unique_ptr<flowgraph::MonoToMultiConverter> mMonoToMultiConverter;
|
||||
std::unique_ptr<flowgraph::MultiToMonoConverter> mMultiToMonoConverter;
|
||||
std::unique_ptr<flowgraph::ChannelCountConverter> mChannelCountConverter;
|
||||
std::unique_ptr<resampler::MultiChannelResampler> mResampler;
|
||||
std::unique_ptr<flowgraph::SampleRateConverter> mRateConverter;
|
||||
std::unique_ptr<flowgraph::FlowGraphSink> mSink;
|
||||
|
||||
FixedBlockWriter mBlockWriter;
|
||||
DataCallbackResult mCallbackResult = DataCallbackResult::Continue;
|
||||
AudioStream *mFilterStream = nullptr;
|
||||
std::unique_ptr<uint8_t[]> mAppBuffer;
|
||||
};
|
||||
|
||||
}
|
||||
#endif //OBOE_OBOE_FLOW_GRAPH_H
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user