адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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;
};
}
@@ -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;
};
}
@@ -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;
}
}
@@ -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;
};
}
@@ -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;
}
}
@@ -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;
};
}
@@ -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();
}
}
@@ -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
};
}
@@ -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;
}
}
@@ -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;
};
}