адаптация s13bby/osc под vst и gui. (вайбкод)
вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio. обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
# ==============================================================================
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# ==============================================================================
|
||||
|
||||
juce_add_modules(
|
||||
INSTALL_PATH "include/JUCE-${JUCE_VERSION}/modules"
|
||||
ALIAS_NAMESPACE juce
|
||||
juce_analytics
|
||||
juce_animation
|
||||
juce_audio_basics
|
||||
juce_audio_devices
|
||||
juce_audio_formats
|
||||
juce_audio_plugin_client
|
||||
juce_audio_processors
|
||||
juce_audio_processors_headless
|
||||
juce_audio_utils
|
||||
juce_box2d
|
||||
juce_core
|
||||
juce_cryptography
|
||||
juce_data_structures
|
||||
juce_dsp
|
||||
juce_events
|
||||
juce_graphics
|
||||
juce_gui_basics
|
||||
juce_gui_extra
|
||||
juce_javascript
|
||||
juce_midi_ci
|
||||
juce_opengl
|
||||
juce_osc
|
||||
juce_product_unlocking
|
||||
juce_video)
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
void Analytics::addDestination (AnalyticsDestination* destination)
|
||||
{
|
||||
destinations.add (destination);
|
||||
}
|
||||
|
||||
OwnedArray<AnalyticsDestination>& Analytics::getDestinations()
|
||||
{
|
||||
return destinations;
|
||||
}
|
||||
|
||||
void Analytics::setUserId (String newUserId)
|
||||
{
|
||||
userId = newUserId;
|
||||
}
|
||||
|
||||
void Analytics::setUserProperties (StringPairArray properties)
|
||||
{
|
||||
userProperties = properties;
|
||||
}
|
||||
|
||||
void Analytics::logEvent (const String& eventName,
|
||||
const StringPairArray& parameters,
|
||||
int eventType)
|
||||
{
|
||||
if (! isSuspended)
|
||||
{
|
||||
AnalyticsDestination::AnalyticsEvent event
|
||||
{
|
||||
eventName,
|
||||
eventType,
|
||||
Time::getMillisecondCounter(),
|
||||
parameters,
|
||||
userId,
|
||||
userProperties
|
||||
};
|
||||
|
||||
for (auto* destination : destinations)
|
||||
destination->logEvent (event);
|
||||
}
|
||||
}
|
||||
|
||||
void Analytics::setSuspended (bool shouldBeSuspended)
|
||||
{
|
||||
isSuspended = shouldBeSuspended;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A singleton class to manage analytics data.
|
||||
|
||||
Use an Analytics object to manage sending analytics data to one or more
|
||||
AnalyticsDestinations.
|
||||
|
||||
@see AnalyticsDestination, ThreadedAnalyticsDestination,
|
||||
AnalyticsDestination::AnalyticsEvent
|
||||
|
||||
@tags{Analytics}
|
||||
*/
|
||||
class JUCE_API Analytics : public DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Adds an AnalyticsDestination to the list of AnalyticsDestinations
|
||||
managed by this Analytics object.
|
||||
|
||||
The Analytics class will take ownership of the AnalyticsDestination
|
||||
passed to this function.
|
||||
|
||||
@param destination the AnalyticsDestination to manage
|
||||
*/
|
||||
void addDestination (AnalyticsDestination* destination);
|
||||
|
||||
/** Returns the array of AnalyticsDestinations managed by this class.
|
||||
|
||||
If you have added any subclasses of ThreadedAnalyticsDestination to
|
||||
this class then you can remove them from this list to force them to
|
||||
flush any pending events.
|
||||
*/
|
||||
OwnedArray<AnalyticsDestination>& getDestinations();
|
||||
|
||||
/** Sets a user ID that will be added to all AnalyticsEvents sent to
|
||||
AnalyticsDestinations.
|
||||
|
||||
@param newUserId the userId to add to AnalyticsEvents
|
||||
*/
|
||||
void setUserId (String newUserId);
|
||||
|
||||
/** Sets some user properties that will be added to all AnalyticsEvents sent
|
||||
to AnalyticsDestinations.
|
||||
|
||||
@param properties the userProperties to add to AnalyticsEvents
|
||||
*/
|
||||
void setUserProperties (StringPairArray properties);
|
||||
|
||||
/** Sends an AnalyticsEvent to all AnalyticsDestinations.
|
||||
|
||||
The AnalyticsEvent will be timestamped, and will have the userId and
|
||||
userProperties populated by values previously set by calls to
|
||||
setUserId and setUserProperties. The name, parameters and type will be
|
||||
populated by the arguments supplied to this function.
|
||||
|
||||
@param eventName the event name
|
||||
@param parameters the event parameters
|
||||
@param eventType (optional) an integer to indicate the event
|
||||
type, which will be set to 0 if not supplied.
|
||||
*/
|
||||
void logEvent (const String& eventName, const StringPairArray& parameters, int eventType = 0);
|
||||
|
||||
/** Suspends analytics submissions to AnalyticsDestinations.
|
||||
|
||||
@param shouldBeSuspended if event submission should be suspended
|
||||
*/
|
||||
void setSuspended (bool shouldBeSuspended);
|
||||
|
||||
/** @cond */
|
||||
JUCE_DECLARE_SINGLETON_INLINE (Analytics, false)
|
||||
/** @endcond */
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
Analytics() = default;
|
||||
~Analytics() override { clearSingletonInstance(); }
|
||||
|
||||
String userId;
|
||||
StringPairArray userProperties;
|
||||
|
||||
bool isSuspended = false;
|
||||
|
||||
OwnedArray<AnalyticsDestination> destinations;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Analytics)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
ButtonTracker::ButtonTracker (Button& buttonToTrack,
|
||||
const String& triggeredEventName,
|
||||
const StringPairArray& triggeredEventParameters,
|
||||
int triggeredEventType)
|
||||
: button (buttonToTrack),
|
||||
eventName (triggeredEventName),
|
||||
eventParameters (triggeredEventParameters),
|
||||
eventType (triggeredEventType)
|
||||
{
|
||||
button.addListener (this);
|
||||
}
|
||||
|
||||
ButtonTracker::~ButtonTracker()
|
||||
{
|
||||
button.removeListener (this);
|
||||
}
|
||||
|
||||
void ButtonTracker::buttonClicked (Button* b)
|
||||
{
|
||||
if (b == &button)
|
||||
{
|
||||
auto params = eventParameters;
|
||||
|
||||
if (button.getClickingTogglesState())
|
||||
params.set ("ButtonState", button.getToggleState() ? "On" : "Off");
|
||||
|
||||
Analytics::getInstance()->logEvent (eventName, params, eventType);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A class that automatically sends analytics events to the Analytics singleton
|
||||
when a button is clicked.
|
||||
|
||||
@see Analytics, AnalyticsDestination::AnalyticsEvent
|
||||
|
||||
@tags{Analytics}
|
||||
*/
|
||||
class JUCE_API ButtonTracker : private Button::Listener
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/**
|
||||
Creating one of these automatically sends analytics events to the Analytics
|
||||
singleton when the corresponding button is clicked.
|
||||
|
||||
The name and parameters of the analytics event will be populated from the
|
||||
variables supplied here. If clicking changes the button's state then the
|
||||
parameters will have a {"ButtonState", "On"/"Off"} entry added.
|
||||
|
||||
@param buttonToTrack the button to track
|
||||
@param triggeredEventName the name of the generated event
|
||||
@param triggeredEventParameters the parameters to add to the generated
|
||||
event
|
||||
@param triggeredEventType (optional) an integer to indicate the event
|
||||
type, which will be set to 0 if not supplied.
|
||||
|
||||
@see Analytics, AnalyticsDestination::AnalyticsEvent
|
||||
*/
|
||||
ButtonTracker (Button& buttonToTrack,
|
||||
const String& triggeredEventName,
|
||||
const StringPairArray& triggeredEventParameters = {},
|
||||
int triggeredEventType = 0);
|
||||
|
||||
/** Destructor. */
|
||||
~ButtonTracker() override;
|
||||
|
||||
private:
|
||||
/** @internal */
|
||||
void buttonClicked (Button*) override;
|
||||
|
||||
Button& button;
|
||||
const String eventName;
|
||||
const StringPairArray eventParameters;
|
||||
const int eventType;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonTracker)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An interface for handling analytics events collected by an Analytics object.
|
||||
|
||||
For basic analytics logging you can implement this interface and add your
|
||||
class to an Analytics object.
|
||||
|
||||
For more advanced logging you may want to subclass
|
||||
ThreadedAnalyticsDestination instead, which is more suitable for interacting
|
||||
with web servers and other time consuming destinations.
|
||||
|
||||
@see Analytics, ThreadedAnalyticsDestination
|
||||
|
||||
@tags{Analytics}
|
||||
*/
|
||||
struct JUCE_API AnalyticsDestination
|
||||
{
|
||||
/** Contains information about an event to be logged. */
|
||||
struct AnalyticsEvent
|
||||
{
|
||||
/** The name of the event. */
|
||||
String name;
|
||||
|
||||
/** An optional integer representing the type of the event. You can use
|
||||
this to indicate if the event was a screenview, session start,
|
||||
exception, etc.
|
||||
*/
|
||||
int eventType;
|
||||
|
||||
/**
|
||||
The timestamp of the event.
|
||||
|
||||
Timestamps are automatically applied by an Analytics object and are
|
||||
derived from Time::getMillisecondCounter(). As such these timestamps
|
||||
do not represent absolute times, but relative timings of events for
|
||||
each user in each session will be accurate.
|
||||
*/
|
||||
uint32 timestamp;
|
||||
|
||||
/** The parameters of the event. */
|
||||
StringPairArray parameters;
|
||||
|
||||
/** The user ID associated with the event. */
|
||||
String userID;
|
||||
|
||||
/** Properties associated with the user. */
|
||||
StringPairArray userProperties;
|
||||
};
|
||||
|
||||
/** Constructor. */
|
||||
AnalyticsDestination() = default;
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~AnalyticsDestination() = default;
|
||||
|
||||
/**
|
||||
When an AnalyticsDestination is added to an Analytics object this method
|
||||
is called when an analytics event is triggered from the Analytics
|
||||
object.
|
||||
|
||||
Override this method to log the event information somewhere useful.
|
||||
*/
|
||||
virtual void logEvent (const AnalyticsEvent& event) = 0;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AnalyticsDestination)
|
||||
};
|
||||
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
ThreadedAnalyticsDestination::ThreadedAnalyticsDestination (const String& threadName)
|
||||
: dispatcher (threadName, *this)
|
||||
{}
|
||||
|
||||
ThreadedAnalyticsDestination::~ThreadedAnalyticsDestination()
|
||||
{
|
||||
// If you hit this assertion then the analytics thread has not been shut down
|
||||
// before this class is destroyed. Call stopAnalyticsThread() in your destructor!
|
||||
jassert (! dispatcher.isThreadRunning());
|
||||
}
|
||||
|
||||
void ThreadedAnalyticsDestination::setBatchPeriod (int newBatchPeriodMilliseconds)
|
||||
{
|
||||
dispatcher.batchPeriodMilliseconds = newBatchPeriodMilliseconds;
|
||||
}
|
||||
|
||||
void ThreadedAnalyticsDestination::logEvent (const AnalyticsEvent& event)
|
||||
{
|
||||
dispatcher.addToQueue (event);
|
||||
}
|
||||
|
||||
void ThreadedAnalyticsDestination::startAnalyticsThread (int initialBatchPeriodMilliseconds)
|
||||
{
|
||||
setBatchPeriod (initialBatchPeriodMilliseconds);
|
||||
dispatcher.startThread();
|
||||
}
|
||||
|
||||
void ThreadedAnalyticsDestination::stopAnalyticsThread (int timeout)
|
||||
{
|
||||
dispatcher.signalThreadShouldExit();
|
||||
stopLoggingEvents();
|
||||
dispatcher.stopThread (timeout);
|
||||
|
||||
if (dispatcher.eventQueue.size() > 0)
|
||||
saveUnloggedEvents (dispatcher.eventQueue);
|
||||
}
|
||||
|
||||
ThreadedAnalyticsDestination::EventDispatcher::EventDispatcher (const String& dispatcherThreadName,
|
||||
ThreadedAnalyticsDestination& destination)
|
||||
: Thread (dispatcherThreadName),
|
||||
parent (destination)
|
||||
{}
|
||||
|
||||
void ThreadedAnalyticsDestination::EventDispatcher::run()
|
||||
{
|
||||
// We may have inserted some events into the queue (on the message thread)
|
||||
// before this thread has started, so make sure the old events are at the
|
||||
// front of the queue.
|
||||
{
|
||||
std::deque<AnalyticsEvent> restoredEventQueue;
|
||||
parent.restoreUnloggedEvents (restoredEventQueue);
|
||||
|
||||
const ScopedLock lock (queueAccess);
|
||||
|
||||
for (auto rit = restoredEventQueue.rbegin(); rit != restoredEventQueue.rend(); ++rit)
|
||||
eventQueue.push_front (*rit);
|
||||
}
|
||||
|
||||
const int maxBatchSize = parent.getMaximumBatchSize();
|
||||
|
||||
while (! threadShouldExit())
|
||||
{
|
||||
{
|
||||
const ScopedLock lock (queueAccess);
|
||||
|
||||
const auto numEventsInBatch = eventsToSend.size();
|
||||
const auto freeBatchCapacity = maxBatchSize - numEventsInBatch;
|
||||
|
||||
if (freeBatchCapacity > 0)
|
||||
{
|
||||
const auto numNewEvents = (int) eventQueue.size() - numEventsInBatch;
|
||||
|
||||
if (numNewEvents > 0)
|
||||
{
|
||||
const auto numEventsToAdd = jmin (numNewEvents, freeBatchCapacity);
|
||||
const auto newBatchSize = numEventsInBatch + numEventsToAdd;
|
||||
|
||||
for (auto i = numEventsInBatch; i < newBatchSize; ++i)
|
||||
eventsToSend.add (eventQueue[(size_t) i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto submissionTime = Time::getMillisecondCounter();
|
||||
|
||||
if (! eventsToSend.isEmpty())
|
||||
{
|
||||
if (parent.logBatchedEvents (eventsToSend))
|
||||
{
|
||||
const ScopedLock lock (queueAccess);
|
||||
|
||||
for (auto i = 0; i < eventsToSend.size(); ++i)
|
||||
eventQueue.pop_front();
|
||||
|
||||
eventsToSend.clearQuick();
|
||||
}
|
||||
}
|
||||
|
||||
while (Time::getMillisecondCounter() - submissionTime < (uint32) batchPeriodMilliseconds.get())
|
||||
{
|
||||
if (threadShouldExit())
|
||||
return;
|
||||
|
||||
Thread::sleep (100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ThreadedAnalyticsDestination::EventDispatcher::addToQueue (const AnalyticsEvent& event)
|
||||
{
|
||||
const ScopedLock lock (queueAccess);
|
||||
eventQueue.push_back (event);
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
namespace DestinationTestHelpers
|
||||
{
|
||||
//==============================================================================
|
||||
struct BasicDestination final : public ThreadedAnalyticsDestination
|
||||
{
|
||||
BasicDestination (std::deque<AnalyticsEvent>& loggedEvents,
|
||||
std::deque<AnalyticsEvent>& unloggedEvents)
|
||||
: ThreadedAnalyticsDestination ("ThreadedAnalyticsDestinationTest"),
|
||||
loggedEventQueue (loggedEvents),
|
||||
unloggedEventStore (unloggedEvents)
|
||||
{
|
||||
startAnalyticsThread (20);
|
||||
}
|
||||
|
||||
~BasicDestination() override
|
||||
{
|
||||
stopAnalyticsThread (1000);
|
||||
}
|
||||
|
||||
int getMaximumBatchSize() override
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
void saveUnloggedEvents (const std::deque<AnalyticsEvent>& eventsToSave) override
|
||||
{
|
||||
unloggedEventStore = eventsToSave;
|
||||
}
|
||||
|
||||
void restoreUnloggedEvents (std::deque<AnalyticsEvent>& restoredEventQueue) override
|
||||
{
|
||||
restoredEventQueue = unloggedEventStore;
|
||||
}
|
||||
|
||||
bool logBatchedEvents (const Array<AnalyticsEvent>& events) override
|
||||
{
|
||||
jassert (events.size() <= getMaximumBatchSize());
|
||||
|
||||
if (loggingIsEnabled)
|
||||
{
|
||||
const ScopedLock lock (eventQueueChanging);
|
||||
|
||||
for (auto& event : events)
|
||||
loggedEventQueue.push_back (event);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void stopLoggingEvents() override {}
|
||||
|
||||
void setLoggingEnabled (bool shouldLogEvents)
|
||||
{
|
||||
loggingIsEnabled = shouldLogEvents;
|
||||
}
|
||||
|
||||
std::deque<AnalyticsEvent>& loggedEventQueue;
|
||||
std::deque<AnalyticsEvent>& unloggedEventStore;
|
||||
bool loggingIsEnabled = true;
|
||||
CriticalSection eventQueueChanging;
|
||||
};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
struct ThreadedAnalyticsDestinationTests final : public UnitTest
|
||||
{
|
||||
ThreadedAnalyticsDestinationTests()
|
||||
: UnitTest ("ThreadedAnalyticsDestination", UnitTestCategories::analytics)
|
||||
{}
|
||||
|
||||
void compareEventQueues (const std::deque<AnalyticsDestination::AnalyticsEvent>& a,
|
||||
const std::deque<AnalyticsDestination::AnalyticsEvent>& b)
|
||||
{
|
||||
const auto numEntries = a.size();
|
||||
expectEquals ((int) b.size(), (int) numEntries);
|
||||
|
||||
for (size_t i = 0; i < numEntries; ++i)
|
||||
{
|
||||
expectEquals (a[i].name, b[i].name);
|
||||
expect (a[i].timestamp == b[i].timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
std::deque<AnalyticsDestination::AnalyticsEvent> testEvents;
|
||||
|
||||
for (int i = 0; i < 7; ++i)
|
||||
testEvents.push_back ({ String (i), 0, Time::getMillisecondCounter(), {}, "TestUser", {} });
|
||||
|
||||
std::deque<AnalyticsDestination::AnalyticsEvent> loggedEvents, unloggedEvents;
|
||||
|
||||
beginTest ("New events");
|
||||
|
||||
{
|
||||
DestinationTestHelpers::BasicDestination destination (loggedEvents, unloggedEvents);
|
||||
|
||||
for (auto& event : testEvents)
|
||||
destination.logEvent (event);
|
||||
|
||||
size_t waitTime = 0, numLoggedEvents = 0;
|
||||
|
||||
while (numLoggedEvents < testEvents.size())
|
||||
{
|
||||
if (waitTime > 4000)
|
||||
{
|
||||
expect (waitTime < 4000);
|
||||
break;
|
||||
}
|
||||
|
||||
Thread::sleep (40);
|
||||
waitTime += 40;
|
||||
|
||||
const ScopedLock lock (destination.eventQueueChanging);
|
||||
numLoggedEvents = loggedEvents.size();
|
||||
}
|
||||
}
|
||||
|
||||
compareEventQueues (loggedEvents, testEvents);
|
||||
expect (unloggedEvents.size() == 0);
|
||||
|
||||
loggedEvents.clear();
|
||||
|
||||
beginTest ("Unlogged events");
|
||||
{
|
||||
DestinationTestHelpers::BasicDestination destination (loggedEvents, unloggedEvents);
|
||||
destination.setLoggingEnabled (false);
|
||||
|
||||
for (auto& event : testEvents)
|
||||
destination.logEvent (event);
|
||||
}
|
||||
|
||||
compareEventQueues (unloggedEvents, testEvents);
|
||||
expect (loggedEvents.size() == 0);
|
||||
}
|
||||
};
|
||||
|
||||
static ThreadedAnalyticsDestinationTests threadedAnalyticsDestinationTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A base class for dispatching analytics events on a dedicated thread.
|
||||
|
||||
This class is particularly useful for sending analytics events to a web
|
||||
server without blocking the message thread. It can also save (and restore)
|
||||
events that were not dispatched so no information is lost when an internet
|
||||
connection is absent or something else prevents successful logging.
|
||||
|
||||
Once startAnalyticsThread is called the logBatchedEvents method is
|
||||
periodically invoked on an analytics thread, with the period determined by
|
||||
calls to setBatchPeriod. Here events are grouped together into batches, with
|
||||
the maximum batch size set by the implementation of getMaximumBatchSize.
|
||||
|
||||
It's important to call stopAnalyticsThread in the destructor of your
|
||||
subclass (or before then) to give the analytics thread time to shut down.
|
||||
Calling stopAnalyticsThread will, in turn, call stopLoggingEvents, which
|
||||
you should use to terminate the currently running logBatchedEvents call.
|
||||
|
||||
@see Analytics, AnalyticsDestination, AnalyticsDestination::AnalyticsEvent
|
||||
|
||||
@tags{Analytics}
|
||||
*/
|
||||
class JUCE_API ThreadedAnalyticsDestination : public AnalyticsDestination
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/**
|
||||
Creates a ThreadedAnalyticsDestination.
|
||||
|
||||
@param threadName used to identify the analytics
|
||||
thread in debug builds
|
||||
*/
|
||||
ThreadedAnalyticsDestination (const String& threadName = "Analytics thread");
|
||||
|
||||
/** Destructor. */
|
||||
~ThreadedAnalyticsDestination() override;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Override this method to provide the maximum batch size you can handle in
|
||||
your subclass.
|
||||
|
||||
Calls to logBatchedEvents will contain no more than this number of events.
|
||||
*/
|
||||
virtual int getMaximumBatchSize() = 0;
|
||||
|
||||
/**
|
||||
This method will be called periodically on the analytics thread.
|
||||
|
||||
If this method returns false then the subsequent call of this function will
|
||||
contain the same events as previous call, plus any new events that have been
|
||||
generated in the period between calls. The order of events will not be
|
||||
changed. This allows you to retry logging events until they are logged
|
||||
successfully.
|
||||
|
||||
@param events a list of events to be logged
|
||||
@returns if the events were successfully logged
|
||||
*/
|
||||
virtual bool logBatchedEvents (const Array<AnalyticsEvent>& events) = 0;
|
||||
|
||||
/**
|
||||
You must always call stopAnalyticsThread in the destructor of your subclass
|
||||
(or before then) to give the analytics thread time to shut down.
|
||||
|
||||
Calling stopAnalyticsThread triggers a call to this method. At this point
|
||||
you are guaranteed that logBatchedEvents has been called for the last time
|
||||
and you should make sure that the current call to logBatchedEvents finishes
|
||||
as quickly as possible. This method and a subsequent call to
|
||||
saveUnloggedEvents must both complete before the timeout supplied to
|
||||
stopAnalyticsThread.
|
||||
|
||||
In a normal use case stopLoggingEvents will be called on the message thread
|
||||
from the destructor of your ThreadedAnalyticsDestination subclass, and must
|
||||
stop the logBatchedEvents method which is running on the analytics thread.
|
||||
|
||||
@see stopAnalyticsThread
|
||||
*/
|
||||
virtual void stopLoggingEvents() = 0;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Call this to set the period between logBatchedEvents invocations.
|
||||
|
||||
This method is thread safe and can be used to implements things like
|
||||
exponential backoff in logBatchedEvents calls.
|
||||
|
||||
@param newSubmissionPeriodMilliseconds the new submission period to
|
||||
use in milliseconds
|
||||
*/
|
||||
void setBatchPeriod (int newSubmissionPeriodMilliseconds);
|
||||
|
||||
/**
|
||||
Adds an event to the queue, which will ultimately be submitted to
|
||||
logBatchedEvents.
|
||||
|
||||
This method is thread safe.
|
||||
|
||||
@param event the analytics event to add to the queue
|
||||
*/
|
||||
void logEvent (const AnalyticsEvent& event) override final;
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/**
|
||||
Starts the analytics thread, with an initial event batching period.
|
||||
|
||||
@param initialBatchPeriodMilliseconds the initial event batching period
|
||||
in milliseconds
|
||||
*/
|
||||
void startAnalyticsThread (int initialBatchPeriodMilliseconds);
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Triggers the shutdown of the analytics thread.
|
||||
|
||||
You must call this method in the destructor of your subclass (or before
|
||||
then) to give the analytics thread time to shut down.
|
||||
|
||||
This method invokes stopLoggingEvents and you should ensure that both the
|
||||
analytics thread and a call to saveUnloggedEvents are able to finish before
|
||||
the supplied timeout. This timeout is important because on platforms like
|
||||
iOS an app is killed if it takes too long to shut down.
|
||||
|
||||
@param timeoutMilliseconds the number of milliseconds before
|
||||
the analytics thread is forcibly
|
||||
terminated
|
||||
*/
|
||||
void stopAnalyticsThread (int timeoutMilliseconds);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
/**
|
||||
This method will be called when the analytics thread is shut down,
|
||||
giving you the chance to save any analytics events that could not be
|
||||
logged. Once saved these events can be put back into the queue of events
|
||||
when the ThreadedAnalyticsDestination is recreated via
|
||||
restoreUnloggedEvents.
|
||||
|
||||
This method should return as quickly as possible, as both
|
||||
stopLoggingEvents and this method need to complete inside the timeout
|
||||
set in stopAnalyticsThread.
|
||||
|
||||
@param eventsToSave the events that could not be logged
|
||||
|
||||
@see stopAnalyticsThread, stopLoggingEvents, restoreUnloggedEvents
|
||||
*/
|
||||
virtual void saveUnloggedEvents (const std::deque<AnalyticsEvent>& eventsToSave) = 0;
|
||||
|
||||
/**
|
||||
The counterpart to saveUnloggedEvents.
|
||||
|
||||
Events added to the event queue provided by this method will be the
|
||||
first events supplied to logBatchedEvents calls. Use this method to
|
||||
restore any unlogged events previously stored in a call to
|
||||
saveUnloggedEvents.
|
||||
|
||||
This method is called on the analytics thread.
|
||||
|
||||
@param restoredEventQueue place restored events into this queue
|
||||
|
||||
@see saveUnloggedEvents
|
||||
*/
|
||||
virtual void restoreUnloggedEvents (std::deque<AnalyticsEvent>& restoredEventQueue) = 0;
|
||||
|
||||
struct EventDispatcher : public Thread
|
||||
{
|
||||
EventDispatcher (const String& threadName, ThreadedAnalyticsDestination&);
|
||||
|
||||
void run() override;
|
||||
void addToQueue (const AnalyticsEvent&);
|
||||
|
||||
ThreadedAnalyticsDestination& parent;
|
||||
|
||||
std::deque<AnalyticsEvent> eventQueue;
|
||||
CriticalSection queueAccess;
|
||||
|
||||
Atomic<int> batchPeriodMilliseconds { 1000 };
|
||||
|
||||
Array<AnalyticsEvent> eventsToSend;
|
||||
};
|
||||
|
||||
const String destinationName;
|
||||
EventDispatcher dispatcher;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadedAnalyticsDestination)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#ifdef JUCE_ANALYTICS_H_INCLUDED
|
||||
/* When you add this cpp file to your project, you mustn't include it in a file where you've
|
||||
already included any other headers - just put it inside a file on its own, possibly with your config
|
||||
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
|
||||
header files that the compiler may be using.
|
||||
*/
|
||||
#error "Incorrect use of JUCE cpp file"
|
||||
#endif
|
||||
|
||||
#include "juce_analytics.h"
|
||||
|
||||
#include "destinations/juce_ThreadedAnalyticsDestination.cpp"
|
||||
#include "analytics/juce_Analytics.cpp"
|
||||
#include "analytics/juce_ButtonTracker.cpp"
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
The block below describes the properties of this module, and is read by
|
||||
the Projucer to automatically generate project code that uses it.
|
||||
For details about the syntax and how to create or use a module, see the
|
||||
JUCE Module Format.md file.
|
||||
|
||||
|
||||
BEGIN_JUCE_MODULE_DECLARATION
|
||||
|
||||
ID: juce_analytics
|
||||
vendor: juce
|
||||
version: 9.0.5
|
||||
name: JUCE analytics classes
|
||||
description: Classes to collect analytics and send to destinations
|
||||
website: http://www.juce.com/juce
|
||||
license: AGPLv3/Commercial
|
||||
minimumCppStandard: 17
|
||||
|
||||
dependencies: juce_gui_basics
|
||||
|
||||
END_JUCE_MODULE_DECLARATION
|
||||
|
||||
*******************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
#define JUCE_ANALYTICS_H_INCLUDED
|
||||
|
||||
#include <juce_gui_basics/juce_gui_basics.h>
|
||||
|
||||
#include "destinations/juce_AnalyticsDestination.h"
|
||||
#include "destinations/juce_ThreadedAnalyticsDestination.h"
|
||||
#include "analytics/juce_Analytics.h"
|
||||
#include "analytics/juce_ButtonTracker.h"
|
||||
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 Animator::Impl
|
||||
{
|
||||
public:
|
||||
virtual ~Impl() = default;
|
||||
|
||||
virtual double getDurationMs() const
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
shouldStart = true;
|
||||
shouldComplete = false;
|
||||
}
|
||||
|
||||
void complete()
|
||||
{
|
||||
shouldComplete = true;
|
||||
}
|
||||
|
||||
Animator::Status update (double timestampMs)
|
||||
{
|
||||
if (std::exchange (shouldStart, false))
|
||||
{
|
||||
onStart (timestampMs);
|
||||
running = true;
|
||||
}
|
||||
|
||||
if (! running)
|
||||
return Animator::Status::idle;
|
||||
|
||||
const auto status = internalUpdate (timestampMs);
|
||||
|
||||
if (status != Animator::Status::finished && ! shouldComplete)
|
||||
return status;
|
||||
|
||||
shouldComplete = false;
|
||||
running = false;
|
||||
onComplete();
|
||||
return Animator::Status::finished;
|
||||
}
|
||||
|
||||
virtual bool isComplete() const { return shouldComplete; }
|
||||
|
||||
virtual void onStart (double timeStampMs) = 0;
|
||||
virtual void onComplete() = 0;
|
||||
virtual Animator::Status internalUpdate (double timestampMs) = 0;
|
||||
|
||||
bool shouldStart = false, shouldComplete = false, running = false;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
Animator::Animator (std::shared_ptr<Impl> ai)
|
||||
: ptr (std::move (ai))
|
||||
{
|
||||
jassert (ptr != nullptr);
|
||||
}
|
||||
|
||||
double Animator::getDurationMs() const
|
||||
{
|
||||
return ptr->getDurationMs();
|
||||
}
|
||||
|
||||
void Animator::start() const
|
||||
{
|
||||
ptr->start();
|
||||
}
|
||||
|
||||
void Animator::complete() const
|
||||
{
|
||||
ptr->complete();
|
||||
}
|
||||
|
||||
Animator::Status Animator::update (double timestampMs) const
|
||||
{
|
||||
return ptr->update (timestampMs);
|
||||
}
|
||||
|
||||
bool Animator::isComplete() const
|
||||
{
|
||||
return ptr->isComplete();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
struct AnimatorTests : public UnitTest
|
||||
{
|
||||
AnimatorTests()
|
||||
: UnitTest ("Animator", UnitTestCategories::gui)
|
||||
{
|
||||
}
|
||||
|
||||
struct TestEvents
|
||||
{
|
||||
enum class TestEventType
|
||||
{
|
||||
animatorStarted,
|
||||
animatorEnded
|
||||
};
|
||||
|
||||
struct TestEvent
|
||||
{
|
||||
TestEvent (TestEventType e, int a) : eventType (e), animatorId (a) {}
|
||||
|
||||
TestEventType eventType;
|
||||
int animatorId;
|
||||
};
|
||||
|
||||
void started (int animatorId)
|
||||
{
|
||||
events.emplace_back (TestEventType::animatorStarted, animatorId);
|
||||
}
|
||||
|
||||
void ended (int animatorId)
|
||||
{
|
||||
events.emplace_back (TestEventType::animatorEnded, animatorId);
|
||||
}
|
||||
|
||||
bool animatorStartedBeforeAnotherStarted (int animator, int before)
|
||||
{
|
||||
for (const auto& event : events)
|
||||
{
|
||||
if (event.animatorId == before && event.eventType == TestEventType::animatorStarted)
|
||||
return false;
|
||||
|
||||
if (event.animatorId == animator && event.eventType == TestEventType::animatorStarted)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool animatorStartedBeforeAnotherEnded (int animator, int before)
|
||||
{
|
||||
for (const auto& event : events)
|
||||
{
|
||||
if (event.animatorId == before && event.eventType == TestEventType::animatorEnded)
|
||||
return false;
|
||||
|
||||
if (event.animatorId == animator && event.eventType == TestEventType::animatorStarted)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<TestEvent> events;
|
||||
};
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("AnimatorSet starts end ends Animators in the right order");
|
||||
{
|
||||
TestEvents events;
|
||||
|
||||
auto createTestAnimator = [&events] (int animatorId)
|
||||
{
|
||||
return ValueAnimatorBuilder {}
|
||||
.withOnStartCallback ([&events, animatorId]
|
||||
{
|
||||
events.started (animatorId);
|
||||
return [] (auto) {};
|
||||
})
|
||||
.withOnCompleteCallback ([&events, animatorId]
|
||||
{
|
||||
events.ended (animatorId);
|
||||
})
|
||||
.build();
|
||||
};
|
||||
|
||||
auto stage1 = AnimatorSetBuilder { createTestAnimator (1) };
|
||||
stage1.followedBy (createTestAnimator (2));
|
||||
stage1.togetherWith (createTestAnimator (3));
|
||||
|
||||
Animator animator = stage1.build();
|
||||
animator.start();
|
||||
|
||||
for (double timeMs = 0.0; animator.update (timeMs) != Animator::Status::finished; timeMs += 16.667)
|
||||
;
|
||||
|
||||
expect (events.animatorStartedBeforeAnotherEnded (1, 2));
|
||||
expect (! events.animatorStartedBeforeAnotherEnded (2, 1));
|
||||
expect (events.animatorStartedBeforeAnotherEnded (3, 1));
|
||||
expect (events.animatorStartedBeforeAnotherStarted (3, 2));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static AnimatorTests animatorTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Wrapper class for managing the lifetime of all the different animator kinds created through the
|
||||
builder classes.
|
||||
|
||||
It uses reference counting. If you copy an Animator the resulting object will refer to the same
|
||||
underlying instance, and the underlying instance is guaranteed to remain valid for as long as
|
||||
you have an Animator object referencing it.
|
||||
|
||||
An Animator object can be registered with the AnimatorUpdater, which only stores a weak
|
||||
reference to the underlying instance. If an AnimatorUpdater references the underlying instance
|
||||
and it becomes deleted due to all Animator objects being deleted, the updater will automatically
|
||||
remove it from its queue, so manually removing it is not required.
|
||||
|
||||
@see ValueAnimatorBuilder, AnimatorSetBuilder, AnimatorUpdater, VBlankAnimatorUpdater
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class JUCE_API Animator
|
||||
{
|
||||
public:
|
||||
class Impl;
|
||||
|
||||
/** The state of an Animator that determines how AnimatorUpdaters and other Animators will
|
||||
interact with it.
|
||||
*/
|
||||
enum class Status
|
||||
{
|
||||
/** The Animator is idle and its state is not progressing even if it is attached to an
|
||||
AnimatorUpdater.
|
||||
*/
|
||||
idle,
|
||||
|
||||
/** The Animator is active and its state is progressing whenever its update function is
|
||||
called.
|
||||
*/
|
||||
inProgress,
|
||||
|
||||
/** The Animator finished its run and its onCompletion callback may be called. It requires
|
||||
no further calls to its update function.
|
||||
*/
|
||||
finished
|
||||
};
|
||||
|
||||
/** @internal
|
||||
|
||||
Constructor. Used by the builder classes.
|
||||
|
||||
@see ValueAnimatorBuilder, AnimatorSetBuilder
|
||||
*/
|
||||
explicit Animator (std::shared_ptr<Impl>);
|
||||
|
||||
/** Returns the total animation duration in milliseconds. */
|
||||
double getDurationMs() const;
|
||||
|
||||
/** Marks the Animator ready for starting. You must call this function to allow the Animator to
|
||||
move out of the idle state.
|
||||
|
||||
After calling this function the Animator's on start callback will be executed at the next
|
||||
update immediately followed by the first call to it's update function.
|
||||
|
||||
You can call this function before or after adding the Animator to an AnimatorUpdater. Until
|
||||
start() is called the Animator will just sit idly in the updater's queue.
|
||||
*/
|
||||
void start() const;
|
||||
|
||||
/** Marks the Animator ready to be completed. ValueAnimators will be completed automatically
|
||||
when they reach a progress >= 1.0 unless they are infinitely running. AnimatorSets will also
|
||||
complete on their own when all of their constituent Animators complete.
|
||||
|
||||
Using this function you can fast track the completion of an Animator. After calling this
|
||||
function isComplete will return true, and it's guaranteed that you will receive an update
|
||||
callback with a progress value of 1.0. After this the onComplete callback will be executed.
|
||||
*/
|
||||
void complete() const;
|
||||
|
||||
/** Called periodically for active Animators by the AnimatorUpdater classes. The passed in
|
||||
timestamp must be monotonically increasing. This allows the underlying Animator
|
||||
to follow its progression towards completion.
|
||||
|
||||
While you can call this function in special circumstances, you will generally want an
|
||||
AnimatorUpdater to do it. Using the VBlankAnimatorUpdater ensures that update is called in
|
||||
sync with the monitor's vertical refresh resulting in smooth animations.
|
||||
|
||||
@see AnimatorUpdater, VBlankAnimatorUpdater
|
||||
*/
|
||||
Status update (double timestampMs) const;
|
||||
|
||||
/** Returns true if the Animator has reached the point of completion either because complete()
|
||||
has been called on it, or in case of the ValueAnimator, if it reached a progress of >= 1.0.
|
||||
|
||||
You typically don't need to call this function, because in any case a completed Animator
|
||||
will receive an update callback with a progress value of 1.0 and following that the
|
||||
on complete callback will be called.
|
||||
*/
|
||||
bool isComplete() const;
|
||||
|
||||
/** Comparison function used by the implementation to store Animators in ordered collections.
|
||||
It can also be used to determine equality of Animator objects based on whether they
|
||||
reference the same underlying implementation.
|
||||
*/
|
||||
struct JUCE_API Compare
|
||||
{
|
||||
/** Comparison function. */
|
||||
bool operator() (const Animator& a, const Animator& b) const { return a.ptr < b.ptr; }
|
||||
};
|
||||
|
||||
/** @internal
|
||||
|
||||
Stores a weak reference to the Animator's underlying implementation. Animator objects store
|
||||
a strong reference to the implementation, so it won't be deleted as long as an Animator
|
||||
object references it. Instead of copying the Animator, you can use makeWeak() to create a
|
||||
weak reference, which will not prevent deletion of the underlying implementation, but allows
|
||||
you to create a strong reference using the lock function for as long as the underlying
|
||||
object is alive.
|
||||
|
||||
This class is used by the AnimatorUpdater, and it's unlikely you will need to use it
|
||||
directly.
|
||||
|
||||
@see AnimatorUpdater, VBlankAnimatorUpdater
|
||||
*/
|
||||
class JUCE_API Weak
|
||||
{
|
||||
public:
|
||||
/** Constructor used by the Animator implementation. To obtain a weak reference use
|
||||
Animator::makeWeak().
|
||||
*/
|
||||
Weak() = default;
|
||||
|
||||
/** Constructor used by the Animator implementation. To obtain a weak reference use
|
||||
Animator::makeWeak().
|
||||
*/
|
||||
explicit Weak (std::shared_ptr<Impl> p) : ptr (p), originalPtr (p.get()) {}
|
||||
|
||||
/** If the referenced Animator implementation object still exists it returns an Animator
|
||||
object storing a strong reference to it.
|
||||
|
||||
If the implementation object was deleted it returns a nullopt.
|
||||
*/
|
||||
std::optional<Animator> lock() const
|
||||
{
|
||||
if (const auto l = ptr.lock())
|
||||
return Animator { l };
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
/** @internal
|
||||
|
||||
Used internally for storing the reference in a std::map.
|
||||
*/
|
||||
void* getKey() const
|
||||
{
|
||||
return originalPtr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::weak_ptr<Impl> ptr;
|
||||
Impl* originalPtr{};
|
||||
};
|
||||
|
||||
/** @internal
|
||||
|
||||
Returns a weak reference to the underlying implementation. You can use Weak::lock() to
|
||||
obtain a strong reference as long as the underlying object has not been deleted.
|
||||
*/
|
||||
Weak makeWeak() const { return Weak { ptr }; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<Impl> ptr;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,291 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 DelayAnimator : public Animator::Impl
|
||||
{
|
||||
public:
|
||||
double getDurationMs() const override { return delayMs; }
|
||||
|
||||
static Animator build (double delayMsIn, std::function<void()> callbackIn = nullptr)
|
||||
{
|
||||
return Animator { rawToUniquePtr (new DelayAnimator (delayMsIn, std::move (callbackIn))) };
|
||||
}
|
||||
|
||||
private:
|
||||
DelayAnimator (double delayMsIn, std::function<void()> callbackIn)
|
||||
: onCompletion (std::move (callbackIn)),
|
||||
delayMs (delayMsIn)
|
||||
{
|
||||
}
|
||||
|
||||
Animator::Status internalUpdate (double timestampMs) override
|
||||
{
|
||||
if (timestampMs - startedAtMs >= delayMs)
|
||||
return Animator::Status::finished;
|
||||
|
||||
return Animator::Status::inProgress;
|
||||
}
|
||||
|
||||
void onStart (double timeMs) override { startedAtMs = timeMs; }
|
||||
|
||||
void onComplete() override { NullCheckedInvocation::invoke (onCompletion); }
|
||||
|
||||
std::function<void()> onCompletion;
|
||||
double startedAtMs = 0.0, delayMs = 0.0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
struct AnimatorSetData
|
||||
{
|
||||
explicit AnimatorSetData (Animator root)
|
||||
: roots { root }, entries { { root, {} } } {}
|
||||
|
||||
struct Entry
|
||||
{
|
||||
std::optional<Animator> parent; // If no parent, this is the root node
|
||||
std::set<Animator, Animator::Compare> children;
|
||||
};
|
||||
|
||||
auto getRoots() const { return roots; }
|
||||
|
||||
auto getChildren (const Animator& a) const
|
||||
{
|
||||
if (const auto iter = entries.find (a); iter != entries.end())
|
||||
return iter->second.children;
|
||||
|
||||
return std::set<Animator, Animator::Compare>();
|
||||
}
|
||||
|
||||
std::set<Animator, Animator::Compare> roots;
|
||||
std::map<Animator, Entry, Animator::Compare> entries;
|
||||
std::function<double (double)> timeTransform;
|
||||
};
|
||||
|
||||
class AnimatorSet : public Animator::Impl
|
||||
{
|
||||
public:
|
||||
explicit AnimatorSet (AnimatorSetData dataIn) : data (std::move (dataIn)) {}
|
||||
|
||||
double getDurationMs() const override
|
||||
{
|
||||
const auto roots = data.getRoots();
|
||||
return getMaxDuration (roots.begin(), roots.end());
|
||||
}
|
||||
|
||||
private:
|
||||
void onStart (double timestampMs) override
|
||||
{
|
||||
startedAtMs = timestampMs;
|
||||
active = data.getRoots();
|
||||
|
||||
for (const auto& i : active)
|
||||
i.start();
|
||||
}
|
||||
|
||||
void onComplete() override {}
|
||||
|
||||
Animator::Status internalUpdate (double timestampMs) override
|
||||
{
|
||||
const auto internalTimestampMs = [&]
|
||||
{
|
||||
if (data.timeTransform == nullptr)
|
||||
return timestampMs;
|
||||
|
||||
return data.timeTransform (timestampMs - startedAtMs);
|
||||
}();
|
||||
|
||||
if (isComplete())
|
||||
{
|
||||
for (auto i : active)
|
||||
i.complete();
|
||||
|
||||
while (updateAnimatorSet (internalTimestampMs) != Animator::Status::finished)
|
||||
{
|
||||
}
|
||||
|
||||
return Animator::Status::finished;
|
||||
}
|
||||
|
||||
return updateAnimatorSet (internalTimestampMs);
|
||||
}
|
||||
|
||||
Animator::Status updateAnimatorSet (double timestampMs)
|
||||
{
|
||||
std::set<Animator, Animator::Compare> animatorsToRemove;
|
||||
const auto currentlyActive = active;
|
||||
|
||||
for (const auto& animator : currentlyActive)
|
||||
{
|
||||
const auto status = animator.update (timestampMs);
|
||||
|
||||
if (status == Animator::Status::finished)
|
||||
{
|
||||
animatorsToRemove.insert (animator);
|
||||
|
||||
for (const auto& j : data.getChildren (animator))
|
||||
{
|
||||
j.start();
|
||||
|
||||
if (isComplete())
|
||||
j.complete();
|
||||
|
||||
active.insert (j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (auto i : animatorsToRemove)
|
||||
active.erase (i);
|
||||
|
||||
return active.empty() ? Animator::Status::finished : Animator::Status::inProgress;
|
||||
}
|
||||
|
||||
template <typename It>
|
||||
double getMaxDuration (It begin, It end) const
|
||||
{
|
||||
return std::accumulate (begin, end, 0.0, [this] (const auto acc, const auto& anim)
|
||||
{
|
||||
const auto children = data.getChildren (anim);
|
||||
return std::max (acc, anim.getDurationMs() + getMaxDuration (children.begin(), children.end()));
|
||||
});
|
||||
}
|
||||
|
||||
const AnimatorSetData data;
|
||||
std::set<Animator, Animator::Compare> active;
|
||||
double startedAtMs = 0.0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
struct AnimatorSetBuilder::AnimatorSetBuilderState
|
||||
{
|
||||
explicit AnimatorSetBuilderState (Animator animator)
|
||||
: data (std::move (animator)) {}
|
||||
|
||||
bool valid = true;
|
||||
AnimatorSetData data;
|
||||
};
|
||||
|
||||
AnimatorSetBuilder::AnimatorSetBuilder (Animator startingAnimator)
|
||||
: AnimatorSetBuilder (startingAnimator,
|
||||
std::make_shared<AnimatorSetBuilderState> (startingAnimator))
|
||||
{}
|
||||
|
||||
AnimatorSetBuilder::AnimatorSetBuilder (double delayMs)
|
||||
: AnimatorSetBuilder (DelayAnimator::build (delayMs, nullptr))
|
||||
{}
|
||||
|
||||
AnimatorSetBuilder::AnimatorSetBuilder (std::function<void()> cb)
|
||||
: AnimatorSetBuilder (DelayAnimator::build (0.0, std::move (cb)))
|
||||
{}
|
||||
|
||||
AnimatorSetBuilder::AnimatorSetBuilder (std::shared_ptr<AnimatorSetBuilderState> dataIn)
|
||||
: cursor (*dataIn->data.getRoots().begin()), state (std::move (dataIn))
|
||||
{}
|
||||
|
||||
AnimatorSetBuilder::AnimatorSetBuilder (Animator cursorIn, std::shared_ptr<AnimatorSetBuilderState> dataIn)
|
||||
: cursor (cursorIn), state (std::move (dataIn))
|
||||
{}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::togetherWith (Animator animator)
|
||||
{
|
||||
add (state->data.entries.at (cursor).parent, animator);
|
||||
return { animator, state };
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::followedBy (Animator animator)
|
||||
{
|
||||
add (cursor, animator);
|
||||
return { animator, state };
|
||||
}
|
||||
|
||||
void AnimatorSetBuilder::add (std::optional<Animator> parent, Animator child)
|
||||
{
|
||||
state->data.entries.emplace (child, AnimatorSetData::Entry { parent, {} });
|
||||
|
||||
if (parent.has_value())
|
||||
state->data.entries.at (*parent).children.insert (child);
|
||||
else
|
||||
state->data.roots.insert (child);
|
||||
}
|
||||
|
||||
Animator AnimatorSetBuilder::build()
|
||||
{
|
||||
if (state == nullptr)
|
||||
{
|
||||
/* If you're hitting this assertion, you've already used this AnimatorSetBuilder to build an
|
||||
AnimatorSet.
|
||||
|
||||
To create another AnimatorSet you need to use another AnimatorSetBuilder independently
|
||||
created with the AnimatorSetBuilder (Animator) constructor.
|
||||
*/
|
||||
jassertfalse;
|
||||
return ValueAnimatorBuilder{}.build();
|
||||
}
|
||||
|
||||
auto animator = Animator { std::make_unique<AnimatorSet> (std::move (state->data)) };
|
||||
state = nullptr;
|
||||
return animator;
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::followedBy (double delayMs)
|
||||
{
|
||||
return followedBy (DelayAnimator::build (delayMs, nullptr));
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::followedBy (std::function<void()> cb)
|
||||
{
|
||||
return followedBy (DelayAnimator::build (0.0, std::move (cb)));
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::togetherWith (double delayMs)
|
||||
{
|
||||
return togetherWith (DelayAnimator::build (delayMs, nullptr));
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::togetherWith (std::function<void()> cb)
|
||||
{
|
||||
return togetherWith (DelayAnimator::build (0.0, std::move (cb)));
|
||||
}
|
||||
|
||||
AnimatorSetBuilder AnimatorSetBuilder::withTimeTransform (std::function<double (double)> timeTransformIn)
|
||||
{
|
||||
state->data.timeTransform = std::move (timeTransformIn);
|
||||
return *this;
|
||||
}
|
||||
|
||||
} // 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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A builder class that can be used to construct an Animator wrapping an AnimatorSet
|
||||
implementation. It allows you to compose larger, complex animations by executing multiple
|
||||
constituent Animator instances in a coordinated manner. It essentially builds an Animator
|
||||
with an execution graph referencing other Animators.
|
||||
|
||||
Unlike ValueAnimatorBuilder, objects of AnimatorSetBuilder returned by its member functions
|
||||
reference the same underlying, modifiable builder instance. For this reason build() can be
|
||||
called only once on an underlying builder instance. This is to allow you to attach Animators to
|
||||
different points of the execution graph.
|
||||
|
||||
E.g. to have two functions followed by different amounts of delay, each followed by another
|
||||
function you would write the following.
|
||||
|
||||
@code
|
||||
// Both objects reference the same execution graph, but also refer to different Animators in it
|
||||
auto builderReferencingFirst = AnimatorSetBuilder { firstFunction };
|
||||
auto builderReferencingSecond = builderReferencingFirst.togetherWith (secondFunction);
|
||||
|
||||
builderReferencingFirst.followedBy (200).followedBy (thirdFunction);
|
||||
builderReferencingSecond.followedBy (500).followedBy (fourthFunction);
|
||||
|
||||
// You could use any one of the builder objects that refer to the same execution graph
|
||||
auto animator = builderReferencingFirst.build();
|
||||
@endcode
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class JUCE_API AnimatorSetBuilder
|
||||
{
|
||||
public:
|
||||
/** Creates a new builder instance specifying the startingAnimator as the first Animator that is
|
||||
started.
|
||||
*/
|
||||
explicit AnimatorSetBuilder (Animator startingAnimator);
|
||||
|
||||
/** Creates a builder with an empty starting animation that completes after delayMs.
|
||||
*/
|
||||
explicit AnimatorSetBuilder (double delayMs);
|
||||
|
||||
/** Creates a builder with a starting animation that completes at the first update and executes
|
||||
the provided callback function.
|
||||
*/
|
||||
explicit AnimatorSetBuilder (std::function<void()> cb);
|
||||
|
||||
/** Adds an Animator to the execution graph that will start executing at the same time as the
|
||||
Animator provided last to this builder object.
|
||||
*/
|
||||
AnimatorSetBuilder togetherWith (Animator animator);
|
||||
|
||||
/** Adds an empty Animator to the execution graph that will start executing at the same time as
|
||||
the Animator provided last to this builder object, and completes in delayMs.
|
||||
*/
|
||||
AnimatorSetBuilder togetherWith (double delayMs);
|
||||
|
||||
/** Adds an empty Animator to the execution graph that will start executing at the same time as
|
||||
the Animator provided last to this builder object, completes upon its first update, and
|
||||
executes the provided callback.
|
||||
*/
|
||||
AnimatorSetBuilder togetherWith (std::function<void()> cb);
|
||||
|
||||
/** Adds an Animator to the execution graph that will start executing after the Animator
|
||||
provided last to this builder object completes.
|
||||
*/
|
||||
AnimatorSetBuilder followedBy (Animator animator);
|
||||
|
||||
/** Adds an empty Animator to the execution graph that will start executing after the Animator
|
||||
provided last to this builder object
|
||||
*/
|
||||
AnimatorSetBuilder followedBy (double delayMs);
|
||||
|
||||
/** Adds an empty Animator to the execution graph that will start executing after the Animator
|
||||
provided last to this builder object, completes upon its first update, and executes the
|
||||
provided callback.
|
||||
*/
|
||||
AnimatorSetBuilder followedBy (std::function<void()> cb);
|
||||
|
||||
/** Specifies a time transformation function that the built Animator should utilise, allowing
|
||||
accelerating and decelerating the entire set of Animators.
|
||||
|
||||
The provided function should be monotonically increasing.
|
||||
*/
|
||||
AnimatorSetBuilder withTimeTransform (std::function<double (double)> transform);
|
||||
|
||||
/** Builds an Animator that executes the previously described and parameterised execution graph.
|
||||
|
||||
This function should only be called once for every AnimatorSetBuilder created by its public
|
||||
constructor.
|
||||
*/
|
||||
Animator build();
|
||||
|
||||
private:
|
||||
struct AnimatorSetBuilderState;
|
||||
|
||||
explicit AnimatorSetBuilder (std::shared_ptr<AnimatorSetBuilderState> dataIn);
|
||||
|
||||
AnimatorSetBuilder (Animator cursorIn, std::shared_ptr<AnimatorSetBuilderState> dataIn);
|
||||
|
||||
void add (std::optional<Animator> parent, Animator child);
|
||||
|
||||
Animator cursor;
|
||||
std::shared_ptr<AnimatorSetBuilderState> state;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
void AnimatorUpdater::addAnimator (const Animator& animator)
|
||||
{
|
||||
addAnimator (animator, nullptr);
|
||||
}
|
||||
|
||||
void AnimatorUpdater::addAnimator (const Animator& animator, std::function<void()> onComplete)
|
||||
{
|
||||
Entry entry { animator.makeWeak(), std::move (onComplete) };
|
||||
animators[entry.animator.getKey()] = std::move (entry);
|
||||
}
|
||||
|
||||
void AnimatorUpdater::removeAnimator (const Animator& animator)
|
||||
{
|
||||
if (auto it = animators.find (animator.makeWeak().getKey()); it != animators.end())
|
||||
{
|
||||
if (it == currentIterator)
|
||||
{
|
||||
++currentIterator;
|
||||
iteratorServiced = false;
|
||||
}
|
||||
|
||||
animators.erase (it);
|
||||
}
|
||||
}
|
||||
|
||||
void AnimatorUpdater::update()
|
||||
{
|
||||
update (Time::getMillisecondCounterHiRes());
|
||||
}
|
||||
|
||||
void AnimatorUpdater::update (double timestampMs)
|
||||
{
|
||||
if (reentrancyGuard)
|
||||
{
|
||||
// If this is hit, one of the animators is trying to update itself
|
||||
// recursively. This is a bad idea! Inspect the callstack to find the
|
||||
// cause of the problem.
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
const ScopedValueSetter setter { reentrancyGuard, true };
|
||||
|
||||
for (currentIterator = animators.begin(); currentIterator != animators.end();)
|
||||
{
|
||||
auto& current = *currentIterator;
|
||||
|
||||
if (const auto locked = current.second.animator.lock())
|
||||
{
|
||||
iteratorServiced = true;
|
||||
|
||||
if (locked->update (timestampMs) == Animator::Status::finished)
|
||||
NullCheckedInvocation::invoke (current.second.onComplete);
|
||||
|
||||
if (iteratorServiced && currentIterator != animators.end())
|
||||
++currentIterator;
|
||||
}
|
||||
else
|
||||
{
|
||||
currentIterator = animators.erase (currentIterator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helper class to update several animators at once, without owning or otherwise extending the
|
||||
lifetimes of those animators.
|
||||
|
||||
The intended use case is to register Animators with an updater as opposed to separately calling
|
||||
Animator::update() on each of them. Calling update() then will update all registered Animators.
|
||||
In case an Animator's underlying implementation is deleted (all Animator objects that were
|
||||
strongly referencing it were deleted) it is automatically removed by the AnimatorUpdater.
|
||||
|
||||
If you want to update all your Animators in sync with the display refresh you will probably want
|
||||
to use the VBlankAnimatorUpdater.
|
||||
|
||||
The order in which Animator::update() functions are called for registered Animators is not
|
||||
specified, as Animators should be implemented in a way where it doesn't matter.
|
||||
|
||||
@see VBlankAnimatorUpdater
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class JUCE_API AnimatorUpdater
|
||||
{
|
||||
public:
|
||||
/** Registers an Animator with the updater.
|
||||
*/
|
||||
void addAnimator (const Animator& animator);
|
||||
|
||||
/** Registers an Animator with the updater and specifies a callback to be called upon the
|
||||
completion of the Animator.
|
||||
|
||||
This callback can be used for cleanup purposes e.g.
|
||||
|
||||
@code
|
||||
animatorUpdater.addAnimator (someComponentPtr->getAnimator(),
|
||||
[&someComponentPtr] { someComponentPtr.reset(); });
|
||||
@endcode
|
||||
*/
|
||||
void addAnimator (const Animator& animator, std::function<void()> onComplete);
|
||||
|
||||
/** Removes an Animator
|
||||
*/
|
||||
void removeAnimator (const Animator& animator);
|
||||
|
||||
/** Calls Animator::update() for all registered Animators that are still alive. References to
|
||||
deleted Animators are removed.
|
||||
|
||||
Uses Time::getMillisecondCounterHiRes() to calculate the necessary timestamp. Consider using
|
||||
a VBlankAnimatorUpdater instead for using timestamps that are synchronised across all
|
||||
VBlankAnimatorUpdater instances.
|
||||
*/
|
||||
void update();
|
||||
|
||||
/** Calls Animator::update() for all registered Animators that are still alive. References to
|
||||
deleted Animators are removed.
|
||||
|
||||
The supplied timestamp should be monotonically increasing for correct behaviour. Ideally
|
||||
this should be a timestamp supplied by a VBlankAttachment. Consider using the
|
||||
VBlankAnimatorUpdater class, which takes care of supplying the right timestamp.
|
||||
|
||||
@see VBlankAnimatorUpdater
|
||||
*/
|
||||
void update (double timestampMs);
|
||||
|
||||
private:
|
||||
struct JUCE_API Entry
|
||||
{
|
||||
Entry() = default;
|
||||
|
||||
Entry(Animator::Weak animatorIn, std::function<void()> onCompleteIn)
|
||||
: animator (animatorIn),
|
||||
onComplete (std::move (onCompleteIn))
|
||||
{}
|
||||
|
||||
Animator::Weak animator;
|
||||
std::function<void()> onComplete;
|
||||
};
|
||||
|
||||
std::map<void*, Entry> animators;
|
||||
std::map<void*, Entry>::iterator currentIterator;
|
||||
|
||||
bool iteratorServiced = false;
|
||||
bool reentrancyGuard = false;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
std::function<float (float)> Easings::createCubicBezier (float x1, float y1, float x2, float y2)
|
||||
{
|
||||
// The x axis represents time, it's important this always stays in the range 0 - 1
|
||||
jassert (isPositiveAndNotGreaterThan (x1, 1.0f));
|
||||
jassert (isPositiveAndNotGreaterThan (x2, 1.0f));
|
||||
|
||||
chromium::gfx::CubicBezier cubicBezier { (double) x1, (double) y1, (double) x2, (double) y2 };
|
||||
return [bezier = std::move (cubicBezier)] (float v) { return (float) bezier.Solve (v); };
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createCubicBezier (Point<float> controlPoint1,
|
||||
Point<float> controlPoint2)
|
||||
{
|
||||
return createCubicBezier (controlPoint1.getX(),
|
||||
controlPoint1.getY(),
|
||||
controlPoint2.getX(),
|
||||
controlPoint2.getY());
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEase()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.25f, 0.1f, 0.25f, 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEaseIn()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.42f, 0.0f, 1.0f, 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEaseOut()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.0f, 0.0f, 0.58f, 1.0f);;
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEaseInOut()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.42f, 0.0f, 0.58f, 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createLinear()
|
||||
{
|
||||
return [] (auto x){ return x; };
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEaseOutBack()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.34f, 1.56f, 0.64f, 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createEaseInOutCubic()
|
||||
{
|
||||
const static auto f = createCubicBezier (0.65f, 0.0f, 0.35f, 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createSpring (const SpringEasingOptions& options)
|
||||
{
|
||||
return [=] (float v)
|
||||
{
|
||||
const auto t = std::clamp (v, 0.0f, 1.0f);
|
||||
const auto omega = 2.0f * MathConstants<float>::pi * options.getFrequency();
|
||||
const auto physicalValue = 1.0f - std::exp (-options.getAttenuation() * t) * std::cos (omega * t);
|
||||
const auto squish = 1.0f / options.getExtraAttenuationRange();
|
||||
const auto shift = 1.0f - options.getExtraAttenuationRange();
|
||||
const auto weight = std::clamp (std::pow (squish * (std::max (t - shift, 0.0f)), 2.0f), 0.0f, 1.0f);
|
||||
return weight + (1.0f - weight) * physicalValue;
|
||||
};
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createBounce (int numBounces)
|
||||
{
|
||||
jassert (numBounces >= 0);
|
||||
numBounces = std::max (0, numBounces);
|
||||
|
||||
const auto alpha = std::pow (0.05f, 1.0f / (float) numBounces);
|
||||
|
||||
const auto fallTime = [] (float h)
|
||||
{
|
||||
return std::sqrt (2.0f * h);
|
||||
};
|
||||
|
||||
std::vector<float> bounceTimes;
|
||||
bounceTimes.reserve ((size_t) (numBounces + 1));
|
||||
bounceTimes.push_back (fallTime (1.0f));
|
||||
|
||||
for (int i = 1; i < numBounces + 1; ++i)
|
||||
bounceTimes.push_back (bounceTimes.back() + 2.0f * fallTime (std::pow (alpha, (float) i)));
|
||||
|
||||
for (auto& bounce : bounceTimes)
|
||||
bounce /= bounceTimes.back();
|
||||
|
||||
return [alpha, times = std::move (bounceTimes)] (float v)
|
||||
{
|
||||
v = std::clamp (v, 0.0f, 1.0f);
|
||||
|
||||
const auto boundIt = std::lower_bound (times.begin(), times.end(), v);
|
||||
|
||||
if (boundIt == times.end())
|
||||
return 1.0f;
|
||||
|
||||
const auto i = (size_t) std::distance (times.begin(), boundIt);
|
||||
const auto height = i == 0 ? 1.0f : std::pow (alpha, (float) i);
|
||||
const auto center = i == 0 ? 0.0f : (times[i] + times[i - 1]) / 2.0f;
|
||||
const auto distToZero = i == 0 ? times[i] : (times[i] - times[i - 1]) / 2.0f;
|
||||
return 1.0f - height * (1.0f - std::pow (1.0f / distToZero * (v - center), 2.0f));
|
||||
};
|
||||
}
|
||||
|
||||
std::function<float (float)> Easings::createOnOffRamp()
|
||||
{
|
||||
return [] (float x) { return 1.0f - std::abs (2.0f * (x - 0.5f)); };
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/** A selection of options available for customising a spring style easing function.
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class SpringEasingOptions
|
||||
{
|
||||
public:
|
||||
/** Specifies the number of oscillations the easing would undergo.
|
||||
|
||||
This also affects the speed of the movement.
|
||||
|
||||
@see getFrequency, withAttenuation, withExtraAttenuationRange
|
||||
*/
|
||||
[[nodiscard]] auto withFrequency (float newFrequency) const
|
||||
{
|
||||
return withMember (*this, &SpringEasingOptions::frequency, newFrequency);
|
||||
}
|
||||
|
||||
/** Affects how quickly the oscillations die down.
|
||||
|
||||
@see getAttenuation, withFrequency, withExtraAttenuationRange
|
||||
*/
|
||||
[[nodiscard]] auto withAttenuation (float newAttenuation) const
|
||||
{
|
||||
return withMember (*this, &SpringEasingOptions::attenuation, newAttenuation);
|
||||
}
|
||||
|
||||
/** Specifies the input value at which an extra non-physical attenuation begins to be applied.
|
||||
The value must be in the range [0.05f, 0.98f].
|
||||
|
||||
This ensures that the easing always reaches an output value of 1.0f when the input value is
|
||||
1.0f. If the attenuation is set sufficiently high this won't have a visible effect.
|
||||
|
||||
@see getExtraAttenuationRange, withFrequency, withAttenuation
|
||||
*/
|
||||
[[nodiscard]] auto withExtraAttenuationRange (float newExtraAttenuationRange) const
|
||||
{
|
||||
return withMember (*this, &SpringEasingOptions::extraAttenuationRange, std::clamp (newExtraAttenuationRange, 0.05f, 0.98f));
|
||||
}
|
||||
|
||||
/** Returns the value specified by withFrequency.
|
||||
|
||||
If no value was specified the default value is 3.0f.
|
||||
|
||||
@see withFrequency
|
||||
*/
|
||||
[[nodiscard]] auto getFrequency() const { return frequency; }
|
||||
|
||||
/** Returns the value specified by withAttenuation.
|
||||
|
||||
If no value was specified the default value is 3.0f.
|
||||
|
||||
@see withAttenuation
|
||||
*/
|
||||
[[nodiscard]] auto getAttenuation() const { return attenuation; }
|
||||
|
||||
/** Returns the value specified by withExtraAttenuationRange
|
||||
|
||||
If no value was specified the default value is 0.25f.
|
||||
|
||||
@see withExtraAttenuationRange
|
||||
*/
|
||||
[[nodiscard]] auto getExtraAttenuationRange() const { return extraAttenuationRange; }
|
||||
|
||||
private:
|
||||
float frequency = 3.0f;
|
||||
float attenuation = 3.0f;
|
||||
float extraAttenuationRange = 0.25f;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a number of easing functions that you can pass into ValueAnimatorBuilder::withEasing to
|
||||
transform the linear progression of animations.
|
||||
|
||||
Using createSpring() for example would transform a rigid movement into one that is reminiscent
|
||||
of a weight attached to a spring.
|
||||
|
||||
For examples of all the easing functions see the AnimationEasingDemo in the DemoRunner.
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
struct Easings
|
||||
{
|
||||
/** Returns a cubic Bezier function with the control points (x1, y1), (x2, y2). These points are
|
||||
the two middle points of a cubic Bezier function's four control points, the first and last
|
||||
being (0, 0), and (1, 1).
|
||||
*/
|
||||
static std::function<float (float)> createCubicBezier (float x1, float y1, float x2, float y2);
|
||||
|
||||
/** Returns a cubic Bezier function with two control points. These points are the two middle
|
||||
points of a cubic Bezier function's four control points, the first and last being (0, 0),
|
||||
and (1, 1).
|
||||
*/
|
||||
static std::function<float (float)> createCubicBezier (Point<float> controlPoint1,
|
||||
Point<float> controlPoint2);
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.25f, 0.1f, 0.25f, 1.0f). This indicates
|
||||
that the interpolation starts slowly, accelerates sharply, and then slows gradually towards
|
||||
the end. It is similar to createEaseInOut(), though it accelerates more sharply at the
|
||||
beginning.
|
||||
|
||||
This is equivalent to using the "ease" keyword when specifying a timing-function in CSS.
|
||||
|
||||
This is the default easing used by the ValueAnimatorBuilder class if no other easing
|
||||
function is specified.
|
||||
|
||||
@see createCubicBezier, createEaseIn, createEaseOut, createEaseInOut
|
||||
*/
|
||||
static std::function<float (float)> createEase();
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.42f, 0.0f, 1.0f, 1.0f). This indicates that
|
||||
the interpolation starts slowly, then progressively speeds up until the end, at which point
|
||||
it stops abruptly.
|
||||
|
||||
This is equivalent to using the "ease-in" keyword when specifying a timing-function in CSS.
|
||||
|
||||
@see createCubicBezier, createEase, createEaseOut, createEaseInOut
|
||||
*/
|
||||
static std::function<float (float)> createEaseIn();
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.0f, 0.0f, 0.58f, 1.0f). This indicates that
|
||||
the interpolation starts abruptly and then progressively slows down towards the end.
|
||||
|
||||
This is equivalent to using the "ease-out" keyword when specifying a timing-function in CSS.
|
||||
|
||||
@see createCubicBezier, createEase, createEaseIn, createEaseInOut, createEaseOutBack
|
||||
*/
|
||||
static std::function<float (float)> createEaseOut();
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.34f, 1.56f, 0.64f, 1.0f). This indicates
|
||||
that the interpolation starts abruptly, quickly decelerating before overshooting the target
|
||||
value by approximately 10% and changing direction to slowly head back towards the target
|
||||
value.
|
||||
|
||||
Like createSpring() this will overshoot causing it to return float values exceeding 1.0f.
|
||||
|
||||
This is equivalent to easeOutBack as specified on https://easings.net/#easeOutBack.
|
||||
|
||||
@see createCubicBezier, createEaseOutBack, createSpring
|
||||
*/
|
||||
static std::function<float (float)> createEaseOutBack();
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.42f, 0.0f, 0.58f, 1.0f). This indicates
|
||||
that the interpolation starts slowly, speeds up, and then slows down towards the end. At the
|
||||
beginning, it behaves like createEaseIn(); at the end, it behaves like createEaseOut().
|
||||
|
||||
This is equivalent to using the "ease-in-out" keyword when specifying a timing-function in
|
||||
CSS.
|
||||
|
||||
@see createCubicBezier, createEase, createEaseIn, createEaseInOut
|
||||
*/
|
||||
static std::function<float (float)> createEaseInOut();
|
||||
|
||||
/** Returns the easing function createCubicBezier (0.65f, 0.0f, 0.35f, 1.0f). This indicates
|
||||
that the interpolation starts slowly, speeds up, and then slows down towards the end. It
|
||||
behaves similar to createEaseInOut() but is more exaggerated and has a more symmetrical
|
||||
curve.
|
||||
|
||||
This is equivalent to easeInOutCubic as specified on https://easings.net/#easeInOutCubic.
|
||||
|
||||
@see createCubicBezier, createEaseInOut
|
||||
*/
|
||||
static std::function<float (float)> createEaseInOutCubic();
|
||||
|
||||
/** Returns an easing function with a constant rate of interpolation, with no change in the rate
|
||||
of progress throughout the duration (that is, no acceleration or deceleration).
|
||||
*/
|
||||
static std::function<float (float)> createLinear();
|
||||
|
||||
/** Returns an easing function that behaves like a spring with a weight attached.
|
||||
|
||||
Like createEaseOutBack() this might overshoot causing it to return float values exceeding
|
||||
1.0f.
|
||||
|
||||
@see createEaseOutBack
|
||||
*/
|
||||
static std::function<float (float)> createSpring (const SpringEasingOptions& options = {});
|
||||
|
||||
/** Returns an easing function that behaves like a bouncy ball dropped on the ground.
|
||||
|
||||
The function will bounce numBounces times on the input range of [0, 1] before coming to
|
||||
stop, each bounce is less pronounced than the previous.
|
||||
|
||||
This is equivalent to easeInOutCubic as specified on https://easings.net/#easeOutBounce.
|
||||
*/
|
||||
static std::function<float (float)> createBounce (int numBounces = 3);
|
||||
|
||||
/** Returns an easing function that reaches 1.0f when the input value is 0.5f, before returning
|
||||
to 0.0f when the input values reaches 1.0f.
|
||||
|
||||
This is useful for making a repeating pulsation.
|
||||
*/
|
||||
static std::function<float (float)> createOnOffRamp();
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helper class for using linear interpolation between a begin and an end value.
|
||||
|
||||
The ValueType could be any numerical type, or a std::tuple containing numerical types. This
|
||||
class is mainly intended to be used with the latter.
|
||||
|
||||
This way you can interpolate multiple values by supplying a single float value, which you can
|
||||
access in an Animator's value change callback.
|
||||
|
||||
E.g.
|
||||
@code
|
||||
const auto boundsToTuple = [] (auto b)
|
||||
{
|
||||
return std::make_tuple (b.getX(), b.getY(), b.getWidth(), b.getHeight());
|
||||
};
|
||||
|
||||
const auto begin = boundsToTuple (component.getBoundsInParent());
|
||||
const auto end = boundsToTuple (targetBounds);
|
||||
const auto limits = makeAnimationLimits (begin, end);
|
||||
|
||||
// This is the value change callback of an Animator, where you will transition a Component from
|
||||
// one bounds to the next. See the AnimatorsDemo for a more detailed example.
|
||||
const auto valueChanged = [&component, limits] (auto v)
|
||||
{
|
||||
const auto [x, y, w, h] = limits.lerp (v);
|
||||
component.setBounds (x, y, w, h);
|
||||
};
|
||||
@endcode
|
||||
|
||||
@see ValueAnimatorBuilder::ValueChangedCallback
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
template <typename ValueType>
|
||||
class JUCE_API StaticAnimationLimits
|
||||
{
|
||||
public:
|
||||
/** Constructor. You can use it to interpolate between a 0 initialised numerical value or tuple
|
||||
and the provided end state.
|
||||
*/
|
||||
explicit StaticAnimationLimits (const ValueType& endIn)
|
||||
: StaticAnimationLimits ({}, endIn) {}
|
||||
|
||||
/** Constructor. Creates an object that will interpolate between the two provided beginning and
|
||||
end states. The ValueType can be a numerical type or a std::tuple containing numerical
|
||||
types.
|
||||
*/
|
||||
StaticAnimationLimits (const ValueType& beginIn, const ValueType& endIn)
|
||||
: begin (beginIn), end (endIn) {}
|
||||
|
||||
/** Evaluation operator. Returns a value that is a linear interpolation of the beginning and end
|
||||
state. It's a shorthand for the lerp() function.
|
||||
*/
|
||||
ValueType operator() (float value) const
|
||||
{
|
||||
return lerp (value);
|
||||
}
|
||||
|
||||
/** Returns a value that is a linear interpolation of the beginning and end state.
|
||||
*/
|
||||
ValueType lerp (float value) const
|
||||
{
|
||||
using namespace detail::ArrayAndTupleOps;
|
||||
|
||||
if constexpr (std::is_integral_v<ValueType>)
|
||||
return (ValueType) std::round ((float) begin + ((float) (end - begin) * value));
|
||||
else
|
||||
return (ValueType) (begin + ((end - begin) * value));
|
||||
}
|
||||
|
||||
private:
|
||||
ValueType begin{}, end{};
|
||||
};
|
||||
|
||||
/** Creates an instance of StaticAnimationLimits, deducing ValueType from
|
||||
the function argument.
|
||||
*/
|
||||
template <typename ValueType>
|
||||
StaticAnimationLimits<ValueType> makeAnimationLimits (const ValueType& end)
|
||||
{
|
||||
return StaticAnimationLimits<ValueType> (end);
|
||||
}
|
||||
|
||||
/** Creates an instance of StaticAnimationLimits, deducing ValueType from
|
||||
the function arguments.
|
||||
*/
|
||||
template <typename ValueType>
|
||||
StaticAnimationLimits<ValueType> makeAnimationLimits (const ValueType& begin, const ValueType& end)
|
||||
{
|
||||
return StaticAnimationLimits<ValueType> (begin, end);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 AnimatorUpdater, but automatically calls update() whenever the screen refreshes.
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class JUCE_API VBlankAnimatorUpdater : private AnimatorUpdater
|
||||
{
|
||||
public:
|
||||
/** Constructs a VBlankAnimatorUpdater that is synchronised to the refresh rate of the monitor
|
||||
that the provided Component is being displayed on.
|
||||
*/
|
||||
explicit VBlankAnimatorUpdater (Component* c)
|
||||
: vBlankAttachment (c, [this] (double timestampSec)
|
||||
{
|
||||
update (timestampSec * 1000.0);
|
||||
})
|
||||
{
|
||||
}
|
||||
|
||||
using AnimatorUpdater::addAnimator, AnimatorUpdater::removeAnimator;
|
||||
|
||||
private:
|
||||
VBlankAttachment vBlankAttachment;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 ValueAnimator : public Animator::Impl
|
||||
{
|
||||
public:
|
||||
explicit ValueAnimator (ValueAnimatorBuilder optionsIn) : options (std::move (optionsIn)) {}
|
||||
|
||||
auto getValue() const
|
||||
{
|
||||
using namespace detail::ArrayAndTupleOps;
|
||||
|
||||
return options.getEasing() == nullptr ? getProgress() : options.getEasing() (getProgress());
|
||||
}
|
||||
|
||||
float getProgress() const
|
||||
{
|
||||
if (isComplete())
|
||||
return 1.0f;
|
||||
|
||||
return timeBasedProgress;
|
||||
}
|
||||
|
||||
/** Returns the time in milliseconds that it takes for the progress to go from 0.0 to 1.0.
|
||||
|
||||
This is the value returned even if the Animator is infinitely running.
|
||||
*/
|
||||
double getDurationMs() const override
|
||||
{
|
||||
return options.getDurationMs();
|
||||
}
|
||||
|
||||
bool isComplete() const override
|
||||
{
|
||||
return Animator::Impl::isComplete()
|
||||
|| (! options.isInfinitelyRunning() && timeBasedProgress >= 1.0f);
|
||||
}
|
||||
|
||||
private:
|
||||
Animator::Status internalUpdate (double timestampMs) override
|
||||
{
|
||||
timeBasedProgress = (float) ((timestampMs - startedAtMs) / options.getDurationMs());
|
||||
|
||||
NullCheckedInvocation::invoke (onValueChanged, getValue());
|
||||
|
||||
if (! options.isInfinitelyRunning())
|
||||
return getProgress() >= 1.0 ? Animator::Status::finished : Animator::Status::inProgress;
|
||||
|
||||
return Animator::Status::inProgress;
|
||||
}
|
||||
|
||||
void onStart (double timeMs) override
|
||||
{
|
||||
startedAtMs = timeMs;
|
||||
timeBasedProgress = 0.0f;
|
||||
|
||||
if (auto fn = options.getOnStartWithValueChanged())
|
||||
onValueChanged = fn();
|
||||
}
|
||||
|
||||
void onComplete() override
|
||||
{
|
||||
NullCheckedInvocation::invoke (options.getOnComplete());
|
||||
}
|
||||
|
||||
double startedAtMs = 0.0;
|
||||
float timeBasedProgress = 0.0f;
|
||||
|
||||
const ValueAnimatorBuilder options;
|
||||
ValueAnimatorBuilder::ValueChangedCallback onValueChanged;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
Animator ValueAnimatorBuilder::build() const& { return Animator { std::make_unique<ValueAnimator> (*this) }; }
|
||||
Animator ValueAnimatorBuilder::build() && { return Animator { std::make_unique<ValueAnimator> (std::move (*this)) }; }
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A builder class that can be used to construct an Animator wrapping a ValueAnimator
|
||||
implementation.
|
||||
|
||||
Every ValueAnimatorBuilder object is immutable, and every "with..." function returns a new
|
||||
object. Each object can be used independently and as many times as required to build an Animator
|
||||
object.
|
||||
|
||||
Calling build() multiple times will return an independent Animator object referencing a new
|
||||
instance of the underlying implementation. Such Animator objects don't affect each other's
|
||||
lifetime. The copy of an Animator object however shares ownership with the object that it was
|
||||
copied from.
|
||||
|
||||
You can treat ValueAnimatorBuilder instances as disposable objects that are only needed until
|
||||
you call build() on them. You can then store only the returned Animator object, which can be
|
||||
started and completed multiple times as needed.
|
||||
|
||||
All functions beginning with "with..." are optional and can be used to affect the created
|
||||
Animator's behaviour by overriding defaults.
|
||||
|
||||
@tags{Animations}
|
||||
*/
|
||||
class JUCE_API ValueAnimatorBuilder
|
||||
{
|
||||
public:
|
||||
/** The type of the value change callback. The float parameter is related to the time parameter
|
||||
passed to Animator::update(). The update function is typically called by an AnimatorUpdater.
|
||||
The parameter will have a value of 0.0 during the first call of the value change callback,
|
||||
and it will reach 1.0 when the time passed equals the duration of the Animator. This however
|
||||
can be changed if an EasingFn is also specified. Correctly written easing functions should
|
||||
preserve the 0.0 and 1.0 start and end values, but intermittent values can fall outside the
|
||||
range of [0.0, 1.0].
|
||||
|
||||
After a call with a progress value of 1.0, the on complete callback will be called and the
|
||||
updates will stop, unless the Animator is infinitely running, in which case the progress
|
||||
will go beyond 1.0 and on complete will not be called until after Animator::complete() has
|
||||
been called.
|
||||
|
||||
A value change callback is optional. If you want to use one, you need to create it inside
|
||||
your on start callback that you must pass to withOnStartCallback().
|
||||
|
||||
@see withOnStartCallback, withDurationMs, withEasing, runningInfinitely
|
||||
*/
|
||||
using ValueChangedCallback = std::function<void (float)>;
|
||||
|
||||
/** The type of the on start callback. It can be used to do any initialisation necessary at the
|
||||
start of an animation, then it must return a ValueChangedCallback.
|
||||
|
||||
The ValueChangedCallback is called during every update of the Animator after the on start
|
||||
callback and before the on complete callback.
|
||||
|
||||
The on start callback is called during the first update that the Animator receives after
|
||||
Animator::start() has been called. Immediately after the on start callback the first call to
|
||||
the value changed callback is made.
|
||||
|
||||
@see ValueChangedCallback
|
||||
*/
|
||||
using OnStartReturningValueChangedCallback = std::function<ValueChangedCallback()>;
|
||||
|
||||
/** The type of an optional easing function that can be passed to the withEasing() builder
|
||||
function.
|
||||
|
||||
If this function is specified it will be called with the progress value going from 0.0 to
|
||||
1.0 (and beyond in case of an infinitely running Animator), that would otherwise be passed
|
||||
directly to the value change callback. The return value is then passed to the on value
|
||||
change callback instead.
|
||||
|
||||
This function can be used to change the linear progression of the animation and create
|
||||
effects like rubber band like motion.
|
||||
|
||||
@see ValueChangedCallback
|
||||
*/
|
||||
using EasingFn = std::function<float (float)>;
|
||||
|
||||
/** Use this function to specify an optional on start callback.
|
||||
|
||||
Alternatively you can use the withOnStartReturningValueChangedCallback function that allows
|
||||
you to return the ValueChangedCallback from inside your on start callback.
|
||||
|
||||
You can only use either withOnStartCallback() or withOnStartReturningValueChangedCallback().
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withOnStartCallback (std::function<void()> onStartCallback) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::onStartReturningValueChanged,
|
||||
[start = std::move (onStartCallback), previous = onStartReturningValueChanged]
|
||||
{
|
||||
NullCheckedInvocation::invoke (start);
|
||||
return previous != nullptr ? previous() : nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
/** Use this function to specify an optional on change callback.
|
||||
|
||||
Alternatively you can use the withOnStartReturningValueChangedCallback function that allows
|
||||
you to return the ValueChangedCallback from inside your on start callback.
|
||||
|
||||
You can only use either withValueChangedCallback or withOnStartReturningValueChangedCallback.
|
||||
|
||||
@see OnStartReturningValueChangedCallback
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withValueChangedCallback (ValueChangedCallback valueChangedCallback) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::onStartReturningValueChanged,
|
||||
[changed = std::move (valueChangedCallback), previous = onStartReturningValueChanged]
|
||||
{
|
||||
return [changed, previousChanged = previous != nullptr ? previous() : nullptr] (float x)
|
||||
{
|
||||
NullCheckedInvocation::invoke (previousChanged, x);
|
||||
NullCheckedInvocation::invoke (changed, x);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Use this function to specify an optional on start callback.
|
||||
|
||||
The return value of the provided function is a ValueChangedCallback. This allows you to
|
||||
construct a new ValueChangedCallback on every on start event, capturing state that is also
|
||||
constructed at the time of starting.
|
||||
|
||||
If you don't need to return a new ValueChangedCallback on every animation start, you can use
|
||||
the simpler variants withOnStartCallback and withValueChangedCallback. However you cannot
|
||||
use those functions together with this one.
|
||||
|
||||
@see OnStartReturningValueChangedCallback, withOnStartCallback, withValueChangedCallback
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withOnStartReturningValueChangedCallback (OnStartReturningValueChangedCallback value) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::onStartReturningValueChanged, std::move (value));
|
||||
}
|
||||
|
||||
/** Use this function to optionally specify an on complete callback. This function will be
|
||||
called after the Animator reached a progress value >= 1.0, or in the case of an
|
||||
infinitely running animation, if Animator::complete() has been called.
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withOnCompleteCallback (std::function<void()> value) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::onComplete, std::move (value));
|
||||
}
|
||||
|
||||
/** Use this function to specify the time it takes for the Animator to reach a progress of 1.0.
|
||||
|
||||
The default value is 300 ms.
|
||||
|
||||
A progress of 1.0 will be reached after this time elapses even if the Animator is infinitely
|
||||
running.
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withDurationMs (double durationMsIn) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::durationMs, durationMsIn);
|
||||
}
|
||||
|
||||
/** Supply a function that transforms the linear progression of time.
|
||||
|
||||
@see EasingFn
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder withEasing (EasingFn fn) const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::easing, std::move (fn));
|
||||
}
|
||||
|
||||
/** This function specifies that the Animator will keep running even after its progress > 1.0
|
||||
and its on complete function will not be called until Animator::complete() is called.
|
||||
*/
|
||||
[[nodiscard]] ValueAnimatorBuilder runningInfinitely() const
|
||||
{
|
||||
return with (&ValueAnimatorBuilder::infinitelyRunning, true);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Getter function used by the corresponding Animator implementation.
|
||||
*/
|
||||
auto& getOnComplete() const
|
||||
{
|
||||
return onComplete;
|
||||
}
|
||||
|
||||
/** Getter function used by the corresponding Animator implementation.
|
||||
*/
|
||||
auto& getOnStartWithValueChanged() const
|
||||
{
|
||||
return onStartReturningValueChanged;
|
||||
}
|
||||
|
||||
/** Getter function used by the corresponding Animator implementation.
|
||||
*/
|
||||
auto getDurationMs() const
|
||||
{
|
||||
return durationMs;
|
||||
}
|
||||
|
||||
/** Getter function used by the corresponding Animator implementation.
|
||||
*/
|
||||
auto isInfinitelyRunning() const
|
||||
{
|
||||
return infinitelyRunning;
|
||||
}
|
||||
|
||||
/** Getter function used by the corresponding Animator implementation.
|
||||
*/
|
||||
auto& getEasing() const
|
||||
{
|
||||
return easing;
|
||||
}
|
||||
|
||||
/** The build() function will instantiate a new underlying implementation with the specified
|
||||
parameters and return an Animator object referencing it. Calling build() multiple times
|
||||
will return unrelated Animator objects, that reference separate underlying implementation
|
||||
instances.
|
||||
*/
|
||||
Animator build() const&;
|
||||
|
||||
/** The build() function will instantiate a new underlying implementation with the specified
|
||||
parameters and return an Animator object referencing it. Calling build() multiple times
|
||||
will return unrelated Animator objects, that reference separate underlying implementation
|
||||
instances.
|
||||
|
||||
This overload will be called on rvalue handles.
|
||||
*/
|
||||
Animator build() &&;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
template <typename Member, typename Value>
|
||||
ValueAnimatorBuilder with (Member&& member, Value&& value) const noexcept
|
||||
{
|
||||
auto copy = *this;
|
||||
copy.*member = std::forward<Value> (value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
OnStartReturningValueChangedCallback onStartReturningValueChanged;
|
||||
std::function<void()> onComplete;
|
||||
double durationMs = 300.0;
|
||||
bool infinitelyRunning = false;
|
||||
EasingFn easing = Easings::createEase();
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,7 @@
|
||||
Upstream: https://chromium.googlesource.com/chromium/src
|
||||
Commit: 3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c
|
||||
|
||||
cubic_bezier.h and cubic_bezier.cc are from ui/gfx/geometry at the commit
|
||||
above, modified for JUCE: include paths flattened, the base and
|
||||
geometry_export dependencies removed, DCHECK replaced with jassert, and
|
||||
base::clamp replaced with std::clamp.
|
||||
@@ -0,0 +1,272 @@
|
||||
// Copyright 2014 The Chromium Authors
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "cubic_bezier.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace gfx {
|
||||
|
||||
namespace {
|
||||
|
||||
const int kMaxNewtonIterations = 4;
|
||||
|
||||
} // namespace
|
||||
|
||||
static const double kBezierEpsilon = 1e-7;
|
||||
|
||||
double CubicBezier::ToFinite(double value) {
|
||||
// TODO(crbug.com/1275541): We can clamp this in numeric operation helper
|
||||
// function like ClampedNumeric.
|
||||
if (std::isinf(value)) {
|
||||
if (value > 0)
|
||||
return std::numeric_limits<double>::max();
|
||||
return std::numeric_limits<double>::lowest();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
CubicBezier::CubicBezier(double p1x, double p1y, double p2x, double p2y) {
|
||||
InitCoefficients(p1x, p1y, p2x, p2y);
|
||||
InitGradients(p1x, p1y, p2x, p2y);
|
||||
InitRange(p1y, p2y);
|
||||
InitSpline();
|
||||
}
|
||||
|
||||
CubicBezier::CubicBezier(const CubicBezier& other) = default;
|
||||
|
||||
void CubicBezier::InitCoefficients(double p1x,
|
||||
double p1y,
|
||||
double p2x,
|
||||
double p2y) {
|
||||
// Calculate the polynomial coefficients, implicit first and last control
|
||||
// points are (0,0) and (1,1).
|
||||
cx_ = 3.0 * p1x;
|
||||
bx_ = 3.0 * (p2x - p1x) - cx_;
|
||||
ax_ = 1.0 - cx_ - bx_;
|
||||
|
||||
cy_ = ToFinite(3.0 * p1y);
|
||||
by_ = ToFinite(3.0 * (p2y - p1y) - cy_);
|
||||
ay_ = ToFinite(1.0 - cy_ - by_);
|
||||
|
||||
#ifndef NDEBUG
|
||||
// Bezier curves with x-coordinates outside the range [0,1] for internal
|
||||
// control points may have multiple values for t for a given value of x.
|
||||
// In this case, calls to SolveCurveX may produce ambiguous results.
|
||||
monotonically_increasing_ = p1x >= 0 && p1x <= 1 && p2x >= 0 && p2x <= 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
void CubicBezier::InitGradients(double p1x,
|
||||
double p1y,
|
||||
double p2x,
|
||||
double p2y) {
|
||||
// End-point gradients are used to calculate timing function results
|
||||
// outside the range [0, 1].
|
||||
//
|
||||
// There are four possibilities for the gradient at each end:
|
||||
// (1) the closest control point is not horizontally coincident with regard to
|
||||
// (0, 0) or (1, 1). In this case the line between the end point and
|
||||
// the control point is tangent to the bezier at the end point.
|
||||
// (2) the closest control point is coincident with the end point. In
|
||||
// this case the line between the end point and the far control
|
||||
// point is tangent to the bezier at the end point.
|
||||
// (3) both internal control points are coincident with an endpoint. There
|
||||
// are two special case that fall into this category:
|
||||
// CubicBezier(0, 0, 0, 0) and CubicBezier(1, 1, 1, 1). Both are
|
||||
// equivalent to linear.
|
||||
// (4) the closest control point is horizontally coincident with the end
|
||||
// point, but vertically distinct. In this case the gradient at the
|
||||
// end point is Infinite. However, this causes issues when
|
||||
// interpolating. As a result, we break down to a simple case of
|
||||
// 0 gradient under these conditions.
|
||||
|
||||
if (p1x > 0)
|
||||
start_gradient_ = p1y / p1x;
|
||||
else if (!p1y && p2x > 0)
|
||||
start_gradient_ = p2y / p2x;
|
||||
else if (!p1y && !p2y)
|
||||
start_gradient_ = 1;
|
||||
else
|
||||
start_gradient_ = 0;
|
||||
|
||||
if (p2x < 1)
|
||||
end_gradient_ = (p2y - 1) / (p2x - 1);
|
||||
else if (p2y == 1 && p1x < 1)
|
||||
end_gradient_ = (p1y - 1) / (p1x - 1);
|
||||
else if (p2y == 1 && p1y == 1)
|
||||
end_gradient_ = 1;
|
||||
else
|
||||
end_gradient_ = 0;
|
||||
}
|
||||
|
||||
// This works by taking taking the derivative of the cubic bezier, on the y
|
||||
// axis. We can then solve for where the derivative is zero to find the min
|
||||
// and max distance along the line. We the have to solve those in terms of time
|
||||
// rather than distance on the x-axis
|
||||
void CubicBezier::InitRange(double p1y, double p2y) {
|
||||
range_min_ = 0;
|
||||
range_max_ = 1;
|
||||
if (0 <= p1y && p1y < 1 && 0 <= p2y && p2y <= 1)
|
||||
return;
|
||||
|
||||
const double epsilon = kBezierEpsilon;
|
||||
|
||||
// Represent the function's derivative in the form at^2 + bt + c
|
||||
// as in sampleCurveDerivativeY.
|
||||
// (Technically this is (dy/dt)*(1/3), which is suitable for finding zeros
|
||||
// but does not actually give the slope of the curve.)
|
||||
const double a = 3.0 * ay_;
|
||||
const double b = 2.0 * by_;
|
||||
const double c = cy_;
|
||||
|
||||
// Check if the derivative is constant.
|
||||
if (std::abs(a) < epsilon && std::abs(b) < epsilon)
|
||||
return;
|
||||
|
||||
// Zeros of the function's derivative.
|
||||
double t1 = 0;
|
||||
double t2 = 0;
|
||||
|
||||
if (std::abs(a) < epsilon) {
|
||||
// The function's derivative is linear.
|
||||
t1 = -c / b;
|
||||
} else {
|
||||
// The function's derivative is a quadratic. We find the zeros of this
|
||||
// quadratic using the quadratic formula.
|
||||
double discriminant = b * b - 4 * a * c;
|
||||
if (discriminant < 0)
|
||||
return;
|
||||
double discriminant_sqrt = sqrt(discriminant);
|
||||
t1 = (-b + discriminant_sqrt) / (2 * a);
|
||||
t2 = (-b - discriminant_sqrt) / (2 * a);
|
||||
}
|
||||
|
||||
double sol1 = 0;
|
||||
double sol2 = 0;
|
||||
|
||||
// If the solution is in the range [0,1] then we include it, otherwise we
|
||||
// ignore it.
|
||||
|
||||
// An interesting fact about these beziers is that they are only
|
||||
// actually evaluated in [0,1]. After that we take the tangent at that point
|
||||
// and linearly project it out.
|
||||
if (0 < t1 && t1 < 1)
|
||||
sol1 = SampleCurveY(t1);
|
||||
|
||||
if (0 < t2 && t2 < 1)
|
||||
sol2 = SampleCurveY(t2);
|
||||
|
||||
range_min_ = std::min({range_min_, sol1, sol2});
|
||||
range_max_ = std::max({range_max_, sol1, sol2});
|
||||
}
|
||||
|
||||
void CubicBezier::InitSpline() {
|
||||
double delta_t = 1.0 / (CUBIC_BEZIER_SPLINE_SAMPLES - 1);
|
||||
for (int i = 0; i < CUBIC_BEZIER_SPLINE_SAMPLES; i++) {
|
||||
spline_samples_[i] = SampleCurveX(i * delta_t);
|
||||
}
|
||||
}
|
||||
|
||||
double CubicBezier::GetDefaultEpsilon() {
|
||||
return kBezierEpsilon;
|
||||
}
|
||||
|
||||
double CubicBezier::SolveCurveX(double x, double epsilon) const {
|
||||
jassert (x >= 0.0);
|
||||
jassert (x <= 1.0);
|
||||
|
||||
double t0;
|
||||
double t1;
|
||||
double t2 = x;
|
||||
double x2;
|
||||
double d2;
|
||||
int i;
|
||||
|
||||
#ifndef NDEBUG
|
||||
jassert (monotonically_increasing_);
|
||||
#endif
|
||||
|
||||
// Linear interpolation of spline curve for initial guess.
|
||||
double delta_t = 1.0 / (CUBIC_BEZIER_SPLINE_SAMPLES - 1);
|
||||
for (i = 1; i < CUBIC_BEZIER_SPLINE_SAMPLES; i++) {
|
||||
if (x <= spline_samples_[i]) {
|
||||
t1 = delta_t * i;
|
||||
t0 = t1 - delta_t;
|
||||
t2 = t0 + (t1 - t0) * (x - spline_samples_[i - 1]) /
|
||||
(spline_samples_[i] - spline_samples_[i - 1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Perform a few iterations of Newton's method -- normally very fast.
|
||||
// See https://en.wikipedia.org/wiki/Newton%27s_method.
|
||||
double newton_epsilon = std::min(kBezierEpsilon, epsilon);
|
||||
for (i = 0; i < kMaxNewtonIterations; i++) {
|
||||
x2 = SampleCurveX(t2) - x;
|
||||
if (fabs(x2) < newton_epsilon)
|
||||
return t2;
|
||||
d2 = SampleCurveDerivativeX(t2);
|
||||
if (fabs(d2) < kBezierEpsilon)
|
||||
break;
|
||||
t2 = t2 - x2 / d2;
|
||||
}
|
||||
if (fabs(x2) < epsilon)
|
||||
return t2;
|
||||
|
||||
// Fall back to the bisection method for reliability.
|
||||
while (t0 < t1) {
|
||||
x2 = SampleCurveX(t2);
|
||||
if (fabs(x2 - x) < epsilon)
|
||||
return t2;
|
||||
if (x > x2)
|
||||
t0 = t2;
|
||||
else
|
||||
t1 = t2;
|
||||
t2 = (t1 + t0) * .5;
|
||||
}
|
||||
|
||||
// Failure.
|
||||
return t2;
|
||||
}
|
||||
|
||||
double CubicBezier::Solve(double x) const {
|
||||
return SolveWithEpsilon(x, kBezierEpsilon);
|
||||
}
|
||||
|
||||
double CubicBezier::SlopeWithEpsilon(double x, double epsilon) const {
|
||||
x = std::clamp(x, 0.0, 1.0);
|
||||
double t = SolveCurveX(x, epsilon);
|
||||
double dx = SampleCurveDerivativeX(t);
|
||||
double dy = SampleCurveDerivativeY(t);
|
||||
// TODO(crbug.com/1275534): We should clamp NaN to a proper value.
|
||||
// Please see the issue for detail.
|
||||
if (!dx && !dy)
|
||||
return 0;
|
||||
return ToFinite(dy / dx);
|
||||
}
|
||||
|
||||
double CubicBezier::Slope(double x) const {
|
||||
return SlopeWithEpsilon(x, kBezierEpsilon);
|
||||
}
|
||||
|
||||
double CubicBezier::GetX1() const {
|
||||
return cx_ / 3.0;
|
||||
}
|
||||
|
||||
double CubicBezier::GetY1() const {
|
||||
return cy_ / 3.0;
|
||||
}
|
||||
|
||||
double CubicBezier::GetX2() const {
|
||||
return (bx_ + cx_) / 3.0 + GetX1();
|
||||
}
|
||||
|
||||
double CubicBezier::GetY2() const {
|
||||
return (by_ + cy_) / 3.0 + GetY1();
|
||||
}
|
||||
|
||||
} // namespace gfx
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright 2014 The Chromium Authors
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef UI_GFX_GEOMETRY_CUBIC_BEZIER_H_
|
||||
#define UI_GFX_GEOMETRY_CUBIC_BEZIER_H_
|
||||
|
||||
namespace gfx {
|
||||
|
||||
#define CUBIC_BEZIER_SPLINE_SAMPLES 11
|
||||
|
||||
class CubicBezier {
|
||||
public:
|
||||
CubicBezier(double p1x, double p1y, double p2x, double p2y);
|
||||
CubicBezier(const CubicBezier& other);
|
||||
|
||||
CubicBezier& operator=(const CubicBezier&) = delete;
|
||||
|
||||
double SampleCurveX(double t) const {
|
||||
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
|
||||
// The x values are in the range [0, 1]. So it isn't needed toFinite
|
||||
// clamping.
|
||||
// https://drafts.csswg.org/css-easing-1/#funcdef-cubic-bezier-easing-function-cubic-bezier
|
||||
return ((ax_ * t + bx_) * t + cx_) * t;
|
||||
}
|
||||
|
||||
double SampleCurveY(double t) const {
|
||||
return ToFinite(((ay_ * t + by_) * t + cy_) * t);
|
||||
}
|
||||
|
||||
double SampleCurveDerivativeX(double t) const {
|
||||
return (3.0 * ax_ * t + 2.0 * bx_) * t + cx_;
|
||||
}
|
||||
|
||||
double SampleCurveDerivativeY(double t) const {
|
||||
return ToFinite(
|
||||
ToFinite(ToFinite(3.0 * ay_) * t + ToFinite(2.0 * by_)) * t + cy_);
|
||||
}
|
||||
|
||||
static double GetDefaultEpsilon();
|
||||
|
||||
// Given an x value, find a parametric value it came from.
|
||||
// x must be in [0, 1] range. Doesn't use gradients.
|
||||
double SolveCurveX(double x, double epsilon) const;
|
||||
|
||||
// Evaluates y at the given x with default epsilon.
|
||||
double Solve(double x) const;
|
||||
// Evaluates y at the given x. The epsilon parameter provides a hint as to the
|
||||
// required accuracy and is not guaranteed. Uses gradients if x is
|
||||
// out of [0, 1] range.
|
||||
double SolveWithEpsilon(double x, double epsilon) const {
|
||||
if (x < 0.0)
|
||||
return ToFinite(0.0 + start_gradient_ * x);
|
||||
if (x > 1.0)
|
||||
return ToFinite(1.0 + end_gradient_ * (x - 1.0));
|
||||
return SampleCurveY(SolveCurveX(x, epsilon));
|
||||
}
|
||||
|
||||
// Returns an approximation of dy/dx at the given x with default epsilon.
|
||||
double Slope(double x) const;
|
||||
// Returns an approximation of dy/dx at the given x.
|
||||
// Clamps x to range [0, 1].
|
||||
double SlopeWithEpsilon(double x, double epsilon) const;
|
||||
|
||||
// These getters are used rarely. We reverse compute them from coefficients.
|
||||
// See CubicBezier::InitCoefficients. The speed has been traded for memory.
|
||||
double GetX1() const;
|
||||
double GetY1() const;
|
||||
double GetX2() const;
|
||||
double GetY2() const;
|
||||
|
||||
// Gets the bezier's minimum y value in the interval [0, 1].
|
||||
double range_min() const { return range_min_; }
|
||||
// Gets the bezier's maximum y value in the interval [0, 1].
|
||||
double range_max() const { return range_max_; }
|
||||
|
||||
private:
|
||||
void InitCoefficients(double p1x, double p1y, double p2x, double p2y);
|
||||
void InitGradients(double p1x, double p1y, double p2x, double p2y);
|
||||
void InitRange(double p1y, double p2y);
|
||||
void InitSpline();
|
||||
static double ToFinite(double value);
|
||||
|
||||
double ax_;
|
||||
double bx_;
|
||||
double cx_;
|
||||
|
||||
double ay_;
|
||||
double by_;
|
||||
double cy_;
|
||||
|
||||
double start_gradient_;
|
||||
double end_gradient_;
|
||||
|
||||
double range_min_;
|
||||
double range_max_;
|
||||
|
||||
double spline_samples_[CUBIC_BEZIER_SPLINE_SAMPLES];
|
||||
|
||||
#ifndef NDEBUG
|
||||
// Guard against attempted to solve for t given x in the event that the curve
|
||||
// may have multiple values for t for some values of x in [0, 1].
|
||||
bool monotonically_increasing_;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
|
||||
#endif // UI_GFX_GEOMETRY_CUBIC_BEZIER_H_
|
||||
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#ifndef DOXYGEN
|
||||
//==============================================================================
|
||||
/** The contents of this namespace are used to implement Animator and should not
|
||||
be used elsewhere. Their interfaces (and existence) are liable to change!
|
||||
*/
|
||||
namespace juce::detail::ArrayAndTupleOps
|
||||
{
|
||||
template <typename, typename = void>
|
||||
constexpr auto hasTupleSize = false;
|
||||
|
||||
template <typename T>
|
||||
constexpr auto hasTupleSize<T, std::void_t<decltype (std::tuple_size<T>::value)>> = true;
|
||||
|
||||
static_assert (! hasTupleSize<float>);
|
||||
static_assert (hasTupleSize<std::tuple<float, float>>);
|
||||
static_assert (hasTupleSize<std::array<float, 5>>);
|
||||
|
||||
template <typename A, typename B, typename Op, size_t... Ix, std::enable_if_t<hasTupleSize<B>, int> = 0>
|
||||
constexpr auto& assignOpImpl (A& a, const B& b, Op&& op, std::index_sequence<Ix...>)
|
||||
{
|
||||
(op (std::get<Ix> (a), std::get<Ix> (b)), ...);
|
||||
return a;
|
||||
}
|
||||
|
||||
template <typename A, typename B, typename Op, size_t... Ix, std::enable_if_t<! hasTupleSize<B>, int> = 0>
|
||||
constexpr auto& assignOpImpl (A& a, const B& b, Op&& op, std::index_sequence<Ix...>)
|
||||
{
|
||||
(op (std::get<Ix> (a), b), ...);
|
||||
return a;
|
||||
}
|
||||
|
||||
template <typename A, typename B, typename Op, std::enable_if_t<hasTupleSize<A>, int> = 0>
|
||||
constexpr auto& assignOpImpl (A& a, const B& b, Op&& op)
|
||||
{
|
||||
return assignOpImpl (a, b, std::forward<Op> (op), std::make_index_sequence<std::tuple_size_v<A>>());
|
||||
}
|
||||
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0>
|
||||
constexpr auto& operator+= (A& a, const B& b)
|
||||
{
|
||||
return assignOpImpl (a, b, [] (auto& x, auto y)
|
||||
{
|
||||
using Tx = std::remove_reference_t<decltype (x)>;
|
||||
using Ty = std::remove_reference_t<decltype (y)>;
|
||||
|
||||
if constexpr (std::is_integral_v<Tx> && std::is_floating_point_v<Ty>)
|
||||
x = (Tx) std::round ((Ty) x + y);
|
||||
else
|
||||
x += y;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0>
|
||||
constexpr auto& operator-= (A& a, const B& b)
|
||||
{
|
||||
return assignOpImpl (a, b, [] (auto& x, auto y)
|
||||
{
|
||||
using Tx = std::remove_reference_t<decltype (x)>;
|
||||
using Ty = std::remove_reference_t<decltype (y)>;
|
||||
|
||||
if constexpr (std::is_integral_v<Tx> && std::is_floating_point_v<Ty>)
|
||||
x = (Tx) std::round ((Ty) x - y);
|
||||
else
|
||||
x -= y;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0>
|
||||
constexpr auto& operator*= (A& a, const B& b)
|
||||
{
|
||||
return assignOpImpl (a, b, [] (auto& x, auto y)
|
||||
{
|
||||
using Tx = std::remove_reference_t<decltype (x)>;
|
||||
using Ty = std::remove_reference_t<decltype (y)>;
|
||||
|
||||
if constexpr (std::is_integral_v<Tx> && std::is_floating_point_v<Ty>)
|
||||
x = (Tx) std::round ((Ty) x * y);
|
||||
else
|
||||
x *= y;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0>
|
||||
constexpr auto& operator/= (A& a, const B& b)
|
||||
{
|
||||
return assignOpImpl (a, b, [] (auto& x, auto y)
|
||||
{
|
||||
using Tx = std::remove_reference_t<decltype (x)>;
|
||||
using Ty = std::remove_reference_t<decltype (y)>;
|
||||
|
||||
if constexpr (std::is_integral_v<Tx> && std::is_floating_point_v<Ty>)
|
||||
x = (Tx) std::round ((Ty) x / y);
|
||||
else
|
||||
x /= y;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0> constexpr auto operator+ (const A& a, const B& b) { A copy { a }; return copy += b; }
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0> constexpr auto operator- (const A& a, const B& b) { A copy { a }; return copy -= b; }
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0> constexpr auto operator* (const A& a, const B& b) { A copy { a }; return copy *= b; }
|
||||
template <typename A, typename B, std::enable_if_t<hasTupleSize<A>, int> = 0> constexpr auto operator/ (const A& a, const B& b) { A copy { a }; return copy /= b; }
|
||||
|
||||
static_assert (std::tuple (1.0f, 5.0) + 3.0f == std::tuple (4.0f, 8.0));
|
||||
static_assert (std::tuple (1.0f, 5.0) - 1.0f == std::tuple (0.0f, 4.0));
|
||||
static_assert (std::tuple (1, 2, 3) * std::tuple (4, 5, 6) == std::tuple (4, 10, 18));
|
||||
} // namespace juce::detail::ArrayAndTupleOps
|
||||
#endif
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#ifdef JUCE_ANIMATION_H_INCLUDED
|
||||
/* When you add this cpp file to your project, you mustn't include it in a file where you've
|
||||
already included any other headers - just put it inside a file on its own, possibly with your config
|
||||
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
|
||||
header files that the compiler may be using.
|
||||
*/
|
||||
#error "Incorrect use of JUCE cpp file"
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
#include "juce_animation.h"
|
||||
|
||||
//==============================================================================
|
||||
namespace chromium
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4701 6001)
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wfloat-conversion",
|
||||
"-Wfloat-equal",
|
||||
"-Wconditional-uninitialized")
|
||||
|
||||
|
||||
#include "detail/chromium/cubic_bezier.h"
|
||||
#include "detail/chromium/cubic_bezier.cc"
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
} // namespace chromium
|
||||
|
||||
//==============================================================================
|
||||
#include "animation/juce_Animator.cpp"
|
||||
#include "animation/juce_AnimatorSetBuilder.cpp"
|
||||
#include "animation/juce_AnimatorUpdater.cpp"
|
||||
#include "animation/juce_Easings.cpp"
|
||||
#include "animation/juce_ValueAnimatorBuilder.cpp"
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
The block below describes the properties of this module, and is read by
|
||||
the Projucer to automatically generate project code that uses it.
|
||||
For details about the syntax and how to create or use a module, see the
|
||||
JUCE Module Format.md file.
|
||||
|
||||
|
||||
BEGIN_JUCE_MODULE_DECLARATION
|
||||
|
||||
ID: juce_animation
|
||||
vendor: juce
|
||||
version: 9.0.5
|
||||
name: JUCE Animation classes
|
||||
description: Classes for defining and handling animations.
|
||||
website: http://www.juce.com/juce
|
||||
license: AGPLv3/Commercial
|
||||
minimumCppStandard: 17
|
||||
|
||||
dependencies: juce_gui_basics
|
||||
|
||||
END_JUCE_MODULE_DECLARATION
|
||||
|
||||
*******************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
#define JUCE_ANIMATION_H_INCLUDED
|
||||
|
||||
#include <juce_gui_basics/juce_gui_basics.h>
|
||||
|
||||
//==============================================================================
|
||||
#include "detail/juce_ArrayAndTupleOps.h"
|
||||
|
||||
//==============================================================================
|
||||
#include "animation/juce_Animator.h"
|
||||
#include "animation/juce_AnimatorSetBuilder.h"
|
||||
#include "animation/juce_AnimatorUpdater.h"
|
||||
#include "animation/juce_Easings.h"
|
||||
#include "animation/juce_StaticAnimationLimits.h"
|
||||
#include "animation/juce_ValueAnimatorBuilder.h"
|
||||
#include "animation/juce_VBlankAnimatorUpdater.h"
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
bool AudioPlayHead::FrameRate::operator== (const FrameRate& other) const
|
||||
{
|
||||
const auto tie = [] (const FrameRate& x) { return std::tie (x.base, x.drop, x.pulldown); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool AudioPlayHead::TimeSignature::operator== (const TimeSignature& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tie (x.numerator, x.denominator); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool AudioPlayHead::LoopPoints::operator== (const LoopPoints& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tie (x.ppqStart, x.ppqEnd); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const noexcept
|
||||
{
|
||||
const auto tie = [] (const CurrentPositionInfo& i)
|
||||
{
|
||||
return std::tie (i.timeInSamples,
|
||||
i.ppqPosition,
|
||||
i.editOriginTime,
|
||||
i.ppqPositionOfLastBarStart,
|
||||
i.frameRate,
|
||||
i.isPlaying,
|
||||
i.isRecording,
|
||||
i.bpm,
|
||||
i.timeSigNumerator,
|
||||
i.timeSigDenominator,
|
||||
i.ppqLoopStart,
|
||||
i.ppqLoopEnd,
|
||||
i.isLooping);
|
||||
};
|
||||
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool AudioPlayHead::PositionInfo::operator== (const PositionInfo& other) const noexcept
|
||||
{
|
||||
const auto tie = [] (const PositionInfo& i)
|
||||
{
|
||||
return std::make_tuple (i.getTimeInSamples(),
|
||||
i.getTimeInSeconds(),
|
||||
i.getPpqPosition(),
|
||||
i.getEditOriginTime(),
|
||||
i.getPpqPositionOfLastBarStart(),
|
||||
i.getFrameRate(),
|
||||
i.getBarCount(),
|
||||
i.getTimeSignature(),
|
||||
i.getBpm(),
|
||||
i.getLoopPoints(),
|
||||
i.getHostTimeNs(),
|
||||
i.getIsPlaying(),
|
||||
i.getIsRecording(),
|
||||
i.getIsLooping());
|
||||
};
|
||||
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool AudioPlayHead::canControlTransport() { return false; }
|
||||
void AudioPlayHead::transportPlay ([[maybe_unused]] bool shouldStartPlaying) {}
|
||||
void AudioPlayHead::transportRecord ([[maybe_unused]] bool shouldStartRecording) {}
|
||||
void AudioPlayHead::transportRewind() {}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,552 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A subclass of AudioPlayHead can supply information about the position and
|
||||
status of a moving play head during audio playback.
|
||||
|
||||
One of these can be supplied to an AudioProcessor object so that it can find
|
||||
out about the position of the audio that it is rendering.
|
||||
|
||||
@see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioPlayHead
|
||||
{
|
||||
protected:
|
||||
//==============================================================================
|
||||
AudioPlayHead() = default;
|
||||
|
||||
public:
|
||||
virtual ~AudioPlayHead() = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Frame rate types. */
|
||||
enum FrameRateType
|
||||
{
|
||||
fps23976 = 0,
|
||||
fps24 = 1,
|
||||
fps25 = 2,
|
||||
fps2997 = 3,
|
||||
fps30 = 4,
|
||||
fps2997drop = 5,
|
||||
fps30drop = 6,
|
||||
fps60 = 7,
|
||||
fps60drop = 8,
|
||||
fpsUnknown = 99
|
||||
};
|
||||
|
||||
/** More descriptive frame rate type. */
|
||||
class JUCE_API FrameRate
|
||||
{
|
||||
public:
|
||||
/** Creates a frame rate with a base rate of 0. */
|
||||
FrameRate() = default;
|
||||
|
||||
/** Creates a FrameRate instance from a FrameRateType. */
|
||||
FrameRate (FrameRateType type) : FrameRate (fromType (type)) {}
|
||||
|
||||
/** Gets the FrameRateType that matches the state of this FrameRate.
|
||||
|
||||
Returns fpsUnknown if this FrameRate cannot be represented by any of the
|
||||
other enum fields.
|
||||
*/
|
||||
FrameRateType getType() const
|
||||
{
|
||||
switch (base)
|
||||
{
|
||||
case 24: return pulldown ? fps23976 : fps24;
|
||||
case 25: return fps25;
|
||||
case 30: return pulldown ? (drop ? fps2997drop : fps2997)
|
||||
: (drop ? fps30drop : fps30);
|
||||
case 60: return drop ? fps60drop : fps60;
|
||||
}
|
||||
|
||||
return fpsUnknown;
|
||||
}
|
||||
|
||||
/** Returns the plain rate, without taking pulldown into account. */
|
||||
int getBaseRate() const { return base; }
|
||||
|
||||
/** Returns true if drop-frame timecode is in use. */
|
||||
bool isDrop() const { return drop; }
|
||||
|
||||
/** Returns true if the effective framerate is actually equal to the base rate divided by 1.001 */
|
||||
bool isPullDown() const { return pulldown; }
|
||||
|
||||
/** Returns the actual rate described by this object, taking pulldown into account. */
|
||||
double getEffectiveRate() const { return pulldown ? (double) base / 1.001 : (double) base; }
|
||||
|
||||
/** Returns a copy of this object with the specified base rate. */
|
||||
[[nodiscard]] FrameRate withBaseRate (int x) const { return with (&FrameRate::base, x); }
|
||||
|
||||
/** Returns a copy of this object with drop frames enabled or disabled, as specified. */
|
||||
[[nodiscard]] FrameRate withDrop (bool x = true) const { return with (&FrameRate::drop, x); }
|
||||
|
||||
/** Returns a copy of this object with pulldown enabled or disabled, as specified. */
|
||||
[[nodiscard]] FrameRate withPullDown (bool x = true) const { return with (&FrameRate::pulldown, x); }
|
||||
|
||||
/** Returns true if this instance is equal to other. */
|
||||
bool operator== (const FrameRate& other) const;
|
||||
|
||||
/** Returns true if this instance is not equal to other. */
|
||||
bool operator!= (const FrameRate& other) const { return ! (*this == other); }
|
||||
|
||||
private:
|
||||
static FrameRate fromType (FrameRateType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case fps23976: return FrameRate().withBaseRate (24).withPullDown();
|
||||
case fps24: return FrameRate().withBaseRate (24);
|
||||
case fps25: return FrameRate().withBaseRate (25);
|
||||
case fps2997: return FrameRate().withBaseRate (30).withPullDown();
|
||||
case fps30: return FrameRate().withBaseRate (30);
|
||||
case fps2997drop: return FrameRate().withBaseRate (30).withDrop().withPullDown();
|
||||
case fps30drop: return FrameRate().withBaseRate (30).withDrop();
|
||||
case fps60: return FrameRate().withBaseRate (60);
|
||||
case fps60drop: return FrameRate().withBaseRate (60).withDrop();
|
||||
case fpsUnknown: break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename Member, typename Value>
|
||||
FrameRate with (Member&& member, Value&& value) const
|
||||
{
|
||||
auto copy = *this;
|
||||
copy.*member = std::forward<Value> (value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
int base = 0;
|
||||
bool drop = false, pulldown = false;
|
||||
};
|
||||
|
||||
/** Describes a musical time signature.
|
||||
|
||||
@see PositionInfo::getTimeSignature() PositionInfo::setTimeSignature()
|
||||
*/
|
||||
struct JUCE_API TimeSignature
|
||||
{
|
||||
/** Time signature numerator, e.g. the 3 of a 3/4 time sig */
|
||||
int numerator = 4;
|
||||
|
||||
/** Time signature denominator, e.g. the 4 of a 3/4 time sig */
|
||||
int denominator = 4;
|
||||
|
||||
bool operator== (const TimeSignature& other) const;
|
||||
|
||||
bool operator!= (const TimeSignature& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
};
|
||||
|
||||
/** Holds the begin and end points of a looped region.
|
||||
|
||||
@see PositionInfo::getIsLooping() PositionInfo::setIsLooping() PositionInfo::getLoopPoints() PositionInfo::setLoopPoints()
|
||||
*/
|
||||
struct JUCE_API LoopPoints
|
||||
{
|
||||
/** The current cycle start position in units of quarter-notes. */
|
||||
double ppqStart = 0;
|
||||
|
||||
/** The current cycle end position in units of quarter-notes. */
|
||||
double ppqEnd = 0;
|
||||
|
||||
bool operator== (const LoopPoints& other) const;
|
||||
|
||||
bool operator!= (const LoopPoints& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** This type is deprecated; prefer PositionInfo instead.
|
||||
|
||||
Some position info may be unavailable, depending on the host or plugin format.
|
||||
Unfortunately, CurrentPositionInfo doesn't have any way of differentiating between
|
||||
default values and values that have been set explicitly.
|
||||
*/
|
||||
struct JUCE_API CurrentPositionInfo
|
||||
{
|
||||
/** The tempo in BPM */
|
||||
double bpm = 120.0;
|
||||
|
||||
/** Time signature numerator, e.g. the 3 of a 3/4 time sig */
|
||||
int timeSigNumerator = 4;
|
||||
|
||||
/** Time signature denominator, e.g. the 4 of a 3/4 time sig */
|
||||
int timeSigDenominator = 4;
|
||||
|
||||
/** The current play position, in samples from the start of the timeline. */
|
||||
int64 timeInSamples = 0;
|
||||
/** The current play position, in seconds from the start of the timeline. */
|
||||
double timeInSeconds = 0;
|
||||
|
||||
/** For timecode, the position of the start of the timeline, in seconds from 00:00:00:00. */
|
||||
double editOriginTime = 0;
|
||||
|
||||
/** The current play position, in units of quarter-notes. */
|
||||
double ppqPosition = 0;
|
||||
|
||||
/** The position of the start of the last bar, in units of quarter-notes.
|
||||
|
||||
This is the time from the start of the timeline to the start of the current
|
||||
bar, in ppq units.
|
||||
|
||||
Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
|
||||
it's not available, the value will be 0.
|
||||
*/
|
||||
double ppqPositionOfLastBarStart = 0;
|
||||
|
||||
/** The video frame rate, if applicable. */
|
||||
FrameRate frameRate = FrameRateType::fps23976;
|
||||
|
||||
/** True if the transport is currently playing. */
|
||||
bool isPlaying = false;
|
||||
|
||||
/** True if the transport is currently recording.
|
||||
|
||||
(When isRecording is true, then isPlaying will also be true).
|
||||
*/
|
||||
bool isRecording = false;
|
||||
|
||||
/** The current cycle start position in units of quarter-notes.
|
||||
Note that not all hosts or plugin formats may provide this value.
|
||||
@see isLooping
|
||||
*/
|
||||
double ppqLoopStart = 0;
|
||||
|
||||
/** The current cycle end position in units of quarter-notes.
|
||||
Note that not all hosts or plugin formats may provide this value.
|
||||
@see isLooping
|
||||
*/
|
||||
double ppqLoopEnd = 0;
|
||||
|
||||
/** True if the transport is currently looping. */
|
||||
bool isLooping = false;
|
||||
|
||||
//==============================================================================
|
||||
bool operator== (const CurrentPositionInfo& other) const noexcept;
|
||||
|
||||
bool operator!= (const CurrentPositionInfo& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
void resetToDefault()
|
||||
{
|
||||
*this = CurrentPositionInfo{};
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Describes the time at the start of the current audio callback.
|
||||
|
||||
Not all hosts and plugin formats can provide all of the possible time
|
||||
information, so most of the getter functions in this class return
|
||||
an Optional that will only be engaged if the host provides the corresponding
|
||||
information. As a plugin developer, you should code defensively so that
|
||||
the plugin behaves sensibly even when the host fails to provide timing
|
||||
information.
|
||||
|
||||
A default-constructed instance of this class will return nullopt from
|
||||
all functions that return an Optional.
|
||||
*/
|
||||
class PositionInfo
|
||||
{
|
||||
public:
|
||||
/** Returns the number of samples that have elapsed. */
|
||||
Optional<int64_t> getTimeInSamples() const { return getOptional (flagTimeSamples, timeInSamples); }
|
||||
|
||||
/** @see getTimeInSamples() */
|
||||
void setTimeInSamples (Optional<int64_t> timeInSamplesIn) { setOptional (flagTimeSamples, timeInSamples, timeInSamplesIn); }
|
||||
|
||||
/** Returns the number of seconds that have elapsed. */
|
||||
Optional<double> getTimeInSeconds() const { return getOptional (flagTimeSeconds, timeInSeconds); }
|
||||
|
||||
/** @see getTimeInSamples() */
|
||||
void setTimeInSeconds (Optional<double> timeInSecondsIn) { setOptional (flagTimeSeconds, timeInSeconds, timeInSecondsIn); }
|
||||
|
||||
/** Returns the bpm, if available. */
|
||||
Optional<double> getBpm() const { return getOptional (flagTempo, tempoBpm); }
|
||||
|
||||
/** @see getBpm() */
|
||||
void setBpm (Optional<double> bpmIn) { setOptional (flagTempo, tempoBpm, bpmIn); }
|
||||
|
||||
/** Returns the time signature, if available. */
|
||||
Optional<TimeSignature> getTimeSignature() const { return getOptional (flagTimeSignature, timeSignature); }
|
||||
|
||||
/** @see getTimeSignature() */
|
||||
void setTimeSignature (Optional<TimeSignature> timeSignatureIn) { setOptional (flagTimeSignature, timeSignature, timeSignatureIn); }
|
||||
|
||||
/** Returns host loop points, if available. */
|
||||
Optional<LoopPoints> getLoopPoints() const { return getOptional (flagLoopPoints, loopPoints); }
|
||||
|
||||
/** @see getLoopPoints() */
|
||||
void setLoopPoints (Optional<LoopPoints> loopPointsIn) { setOptional (flagLoopPoints, loopPoints, loopPointsIn); }
|
||||
|
||||
/** The number of bars since the beginning of the timeline.
|
||||
|
||||
This value isn't available in all hosts or in all plugin formats.
|
||||
*/
|
||||
Optional<int64_t> getBarCount() const { return getOptional (flagBarCount, barCount); }
|
||||
|
||||
/** @see getBarCount() */
|
||||
void setBarCount (Optional<int64_t> barCountIn) { setOptional (flagBarCount, barCount, barCountIn); }
|
||||
|
||||
/** The position of the start of the last bar, in units of quarter-notes.
|
||||
|
||||
This is the time from the start of the timeline to the start of the current
|
||||
bar, in ppq units.
|
||||
|
||||
Note - this value may be unavailable on some hosts, e.g. Pro-Tools.
|
||||
*/
|
||||
Optional<double> getPpqPositionOfLastBarStart() const { return getOptional (flagLastBarStartPpq, lastBarStartPpq); }
|
||||
|
||||
/** @see getPpqPositionOfLastBarStart() */
|
||||
void setPpqPositionOfLastBarStart (Optional<double> positionIn) { setOptional (flagLastBarStartPpq, lastBarStartPpq, positionIn); }
|
||||
|
||||
/** The video frame rate, if available. */
|
||||
Optional<FrameRate> getFrameRate() const { return getOptional (flagFrameRate, frame); }
|
||||
|
||||
/** @see getFrameRate() */
|
||||
void setFrameRate (Optional<FrameRate> frameRateIn) { setOptional (flagFrameRate, frame, frameRateIn); }
|
||||
|
||||
/** The current play position, in units of quarter-notes. */
|
||||
Optional<double> getPpqPosition() const { return getOptional (flagPpqPosition, positionPpq); }
|
||||
|
||||
/** @see getPpqPosition() */
|
||||
void setPpqPosition (Optional<double> ppqPositionIn) { setOptional (flagPpqPosition, positionPpq, ppqPositionIn); }
|
||||
|
||||
/** For timecode, the position of the start of the timeline, in seconds from 00:00:00:00. */
|
||||
Optional<double> getEditOriginTime() const { return getOptional (flagOriginTime, originTime); }
|
||||
|
||||
/** @see getEditOriginTime() */
|
||||
void setEditOriginTime (Optional<double> editOriginTimeIn) { setOptional (flagOriginTime, originTime, editOriginTimeIn); }
|
||||
|
||||
/** Get the host's callback time in nanoseconds, if available. */
|
||||
Optional<uint64_t> getHostTimeNs() const { return getOptional (flagHostTimeNs, hostTimeNs); }
|
||||
|
||||
/** @see getHostTimeNs() */
|
||||
void setHostTimeNs (Optional<uint64_t> hostTimeNsIn) { setOptional (flagHostTimeNs, hostTimeNs, hostTimeNsIn); }
|
||||
|
||||
/** True if the transport is currently playing. */
|
||||
bool getIsPlaying() const { return getFlag (flagIsPlaying); }
|
||||
|
||||
/** @see getIsPlaying() */
|
||||
void setIsPlaying (bool isPlayingIn) { setFlag (flagIsPlaying, isPlayingIn); }
|
||||
|
||||
/** True if the transport is currently recording.
|
||||
|
||||
(When isRecording is true, then isPlaying will also be true).
|
||||
*/
|
||||
bool getIsRecording() const { return getFlag (flagIsRecording); }
|
||||
|
||||
/** @see getIsRecording() */
|
||||
void setIsRecording (bool isRecordingIn) { setFlag (flagIsRecording, isRecordingIn); }
|
||||
|
||||
/** True if the transport is currently looping. */
|
||||
bool getIsLooping() const { return getFlag (flagIsLooping); }
|
||||
|
||||
/** @see getIsLooping() */
|
||||
void setIsLooping (bool isLoopingIn) { setFlag (flagIsLooping, isLoopingIn); }
|
||||
|
||||
bool operator== (const PositionInfo& other) const noexcept;
|
||||
|
||||
bool operator!= (const PositionInfo& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
private:
|
||||
bool getFlag (int64_t flagToCheck) const
|
||||
{
|
||||
return (flagToCheck & flags) != 0;
|
||||
}
|
||||
|
||||
void setFlag (int64_t flagToCheck, bool value)
|
||||
{
|
||||
flags = (value ? flags | flagToCheck : flags & ~flagToCheck);
|
||||
}
|
||||
|
||||
template <typename Value>
|
||||
Optional<Value> getOptional (int64_t flagToCheck, Value value) const
|
||||
{
|
||||
return getFlag (flagToCheck) ? makeOptional (std::move (value)) : nullopt;
|
||||
}
|
||||
|
||||
template <typename Value>
|
||||
void setOptional (int64_t flagToCheck, Value& value, Optional<Value> opt)
|
||||
{
|
||||
if (opt.hasValue())
|
||||
value = *opt;
|
||||
|
||||
setFlag (flagToCheck, opt.hasValue());
|
||||
}
|
||||
|
||||
enum
|
||||
{
|
||||
flagTimeSignature = 1 << 0,
|
||||
flagLoopPoints = 1 << 1,
|
||||
flagFrameRate = 1 << 2,
|
||||
flagTimeSeconds = 1 << 3,
|
||||
flagLastBarStartPpq = 1 << 4,
|
||||
flagPpqPosition = 1 << 5,
|
||||
flagOriginTime = 1 << 6,
|
||||
flagTempo = 1 << 7,
|
||||
flagTimeSamples = 1 << 8,
|
||||
flagBarCount = 1 << 9,
|
||||
flagHostTimeNs = 1 << 10,
|
||||
flagIsPlaying = 1 << 11,
|
||||
flagIsRecording = 1 << 12,
|
||||
flagIsLooping = 1 << 13
|
||||
};
|
||||
|
||||
TimeSignature timeSignature;
|
||||
LoopPoints loopPoints;
|
||||
FrameRate frame = FrameRateType::fps23976;
|
||||
double timeInSeconds = 0.0;
|
||||
double lastBarStartPpq = 0.0;
|
||||
double positionPpq = 0.0;
|
||||
double originTime = 0.0;
|
||||
double tempoBpm = 0.0;
|
||||
int64_t timeInSamples = 0;
|
||||
int64_t barCount = 0;
|
||||
uint64_t hostTimeNs = 0;
|
||||
int64_t flags = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Deprecated, use getPosition() instead.
|
||||
|
||||
Fills-in the given structure with details about the transport's
|
||||
position at the start of the current processing block. If this method returns
|
||||
false then the current play head position is not available and the given
|
||||
structure will be undefined.
|
||||
|
||||
You can ONLY call this from your processBlock() method! Calling it at other
|
||||
times will produce undefined behaviour, as the host may not have any context
|
||||
in which a time would make sense, and some hosts will almost certainly have
|
||||
multithreading issues if it's not called on the audio thread.
|
||||
*/
|
||||
[[deprecated ("Use getPosition instead. Not all hosts are able to provide all time position information; getPosition differentiates clearly between set and unset fields.")]]
|
||||
bool getCurrentPosition (CurrentPositionInfo& result)
|
||||
{
|
||||
if (const auto pos = getPosition())
|
||||
{
|
||||
result.resetToDefault();
|
||||
|
||||
if (const auto sig = pos->getTimeSignature())
|
||||
{
|
||||
result.timeSigNumerator = sig->numerator;
|
||||
result.timeSigDenominator = sig->denominator;
|
||||
}
|
||||
|
||||
if (const auto loop = pos->getLoopPoints())
|
||||
{
|
||||
result.ppqLoopStart = loop->ppqStart;
|
||||
result.ppqLoopEnd = loop->ppqEnd;
|
||||
}
|
||||
|
||||
if (const auto frame = pos->getFrameRate())
|
||||
result.frameRate = *frame;
|
||||
|
||||
if (const auto timeInSeconds = pos->getTimeInSeconds())
|
||||
result.timeInSeconds = *timeInSeconds;
|
||||
|
||||
if (const auto lastBarStartPpq = pos->getPpqPositionOfLastBarStart())
|
||||
result.ppqPositionOfLastBarStart = *lastBarStartPpq;
|
||||
|
||||
if (const auto ppqPosition = pos->getPpqPosition())
|
||||
result.ppqPosition = *ppqPosition;
|
||||
|
||||
if (const auto originTime = pos->getEditOriginTime())
|
||||
result.editOriginTime = *originTime;
|
||||
|
||||
if (const auto bpm = pos->getBpm())
|
||||
result.bpm = *bpm;
|
||||
|
||||
if (const auto timeInSamples = pos->getTimeInSamples())
|
||||
result.timeInSamples = *timeInSamples;
|
||||
|
||||
result.isPlaying = pos->getIsPlaying();
|
||||
result.isRecording = pos->getIsRecording();
|
||||
result.isLooping = pos->getIsLooping();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Fetches details about the transport's position at the start of the current
|
||||
processing block. If this method returns nullopt then the current play head
|
||||
position is not available.
|
||||
|
||||
A non-null return value just indicates that the host was able to provide
|
||||
*some* relevant timing information. Individual PositionInfo getters may
|
||||
still return nullopt.
|
||||
|
||||
You can ONLY call this from your processBlock() method! Calling it at other
|
||||
times will produce undefined behaviour, as the host may not have any context
|
||||
in which a time would make sense, and some hosts will almost certainly have
|
||||
multithreading issues if it's not called on the audio thread.
|
||||
*/
|
||||
virtual Optional<PositionInfo> getPosition() const = 0;
|
||||
|
||||
/** Returns true if this object can control the transport. */
|
||||
virtual bool canControlTransport();
|
||||
|
||||
/** Starts or stops the audio. */
|
||||
virtual void transportPlay (bool shouldStartPlaying);
|
||||
|
||||
/** Starts or stops recording the audio. */
|
||||
virtual void transportRecord (bool shouldStartRecording);
|
||||
|
||||
/** Rewinds the audio. */
|
||||
virtual void transportRewind();
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,875 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
|
||||
|
||||
AudioChannelSet::AudioChannelSet (uint32 c) : channels (static_cast<int64> (c))
|
||||
{
|
||||
}
|
||||
|
||||
AudioChannelSet::AudioChannelSet (const std::initializer_list<ChannelType>& c)
|
||||
{
|
||||
for (auto channel : c)
|
||||
addChannel (channel);
|
||||
}
|
||||
|
||||
bool AudioChannelSet::operator== (const AudioChannelSet& other) const noexcept { return channels == other.channels; }
|
||||
bool AudioChannelSet::operator!= (const AudioChannelSet& other) const noexcept { return channels != other.channels; }
|
||||
bool AudioChannelSet::operator< (const AudioChannelSet& other) const noexcept { return channels < other.channels; }
|
||||
|
||||
String AudioChannelSet::getChannelTypeName (AudioChannelSet::ChannelType type)
|
||||
{
|
||||
if (type >= discreteChannel0)
|
||||
return "Discrete " + String (type - discreteChannel0 + 1);
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case left: return NEEDS_TRANS ("Left");
|
||||
case right: return NEEDS_TRANS ("Right");
|
||||
case centre: return NEEDS_TRANS ("Centre");
|
||||
case LFE: return NEEDS_TRANS ("LFE");
|
||||
case leftSurround: return NEEDS_TRANS ("Left Surround");
|
||||
case rightSurround: return NEEDS_TRANS ("Right Surround");
|
||||
case leftCentre: return NEEDS_TRANS ("Left Centre");
|
||||
case rightCentre: return NEEDS_TRANS ("Right Centre");
|
||||
case centreSurround: return NEEDS_TRANS ("Centre Surround");
|
||||
case leftSurroundRear: return NEEDS_TRANS ("Left Surround Rear");
|
||||
case rightSurroundRear: return NEEDS_TRANS ("Right Surround Rear");
|
||||
case topMiddle: return NEEDS_TRANS ("Top Middle");
|
||||
case topFrontLeft: return NEEDS_TRANS ("Top Front Left");
|
||||
case topFrontCentre: return NEEDS_TRANS ("Top Front Centre");
|
||||
case topFrontRight: return NEEDS_TRANS ("Top Front Right");
|
||||
case topRearLeft: return NEEDS_TRANS ("Top Rear Left");
|
||||
case topRearCentre: return NEEDS_TRANS ("Top Rear Centre");
|
||||
case topRearRight: return NEEDS_TRANS ("Top Rear Right");
|
||||
case wideLeft: return NEEDS_TRANS ("Wide Left");
|
||||
case wideRight: return NEEDS_TRANS ("Wide Right");
|
||||
case LFE2: return NEEDS_TRANS ("LFE 2");
|
||||
case leftSurroundSide: return NEEDS_TRANS ("Left Surround Side");
|
||||
case rightSurroundSide: return NEEDS_TRANS ("Right Surround Side");
|
||||
case ambisonicW: return NEEDS_TRANS ("Ambisonic W");
|
||||
case ambisonicX: return NEEDS_TRANS ("Ambisonic X");
|
||||
case ambisonicY: return NEEDS_TRANS ("Ambisonic Y");
|
||||
case ambisonicZ: return NEEDS_TRANS ("Ambisonic Z");
|
||||
case topSideLeft: return NEEDS_TRANS ("Top Side Left");
|
||||
case topSideRight: return NEEDS_TRANS ("Top Side Right");
|
||||
case ambisonicACN4: return NEEDS_TRANS ("Ambisonic 4");
|
||||
case ambisonicACN5: return NEEDS_TRANS ("Ambisonic 5");
|
||||
case ambisonicACN6: return NEEDS_TRANS ("Ambisonic 6");
|
||||
case ambisonicACN7: return NEEDS_TRANS ("Ambisonic 7");
|
||||
case ambisonicACN8: return NEEDS_TRANS ("Ambisonic 8");
|
||||
case ambisonicACN9: return NEEDS_TRANS ("Ambisonic 9");
|
||||
case ambisonicACN10: return NEEDS_TRANS ("Ambisonic 10");
|
||||
case ambisonicACN11: return NEEDS_TRANS ("Ambisonic 11");
|
||||
case ambisonicACN12: return NEEDS_TRANS ("Ambisonic 12");
|
||||
case ambisonicACN13: return NEEDS_TRANS ("Ambisonic 13");
|
||||
case ambisonicACN14: return NEEDS_TRANS ("Ambisonic 14");
|
||||
case ambisonicACN15: return NEEDS_TRANS ("Ambisonic 15");
|
||||
case ambisonicACN16: return NEEDS_TRANS ("Ambisonic 16");
|
||||
case ambisonicACN17: return NEEDS_TRANS ("Ambisonic 17");
|
||||
case ambisonicACN18: return NEEDS_TRANS ("Ambisonic 18");
|
||||
case ambisonicACN19: return NEEDS_TRANS ("Ambisonic 19");
|
||||
case ambisonicACN20: return NEEDS_TRANS ("Ambisonic 20");
|
||||
case ambisonicACN21: return NEEDS_TRANS ("Ambisonic 21");
|
||||
case ambisonicACN22: return NEEDS_TRANS ("Ambisonic 22");
|
||||
case ambisonicACN23: return NEEDS_TRANS ("Ambisonic 23");
|
||||
case ambisonicACN24: return NEEDS_TRANS ("Ambisonic 24");
|
||||
case ambisonicACN25: return NEEDS_TRANS ("Ambisonic 25");
|
||||
case ambisonicACN26: return NEEDS_TRANS ("Ambisonic 26");
|
||||
case ambisonicACN27: return NEEDS_TRANS ("Ambisonic 27");
|
||||
case ambisonicACN28: return NEEDS_TRANS ("Ambisonic 28");
|
||||
case ambisonicACN29: return NEEDS_TRANS ("Ambisonic 29");
|
||||
case ambisonicACN30: return NEEDS_TRANS ("Ambisonic 30");
|
||||
case ambisonicACN31: return NEEDS_TRANS ("Ambisonic 31");
|
||||
case ambisonicACN32: return NEEDS_TRANS ("Ambisonic 32");
|
||||
case ambisonicACN33: return NEEDS_TRANS ("Ambisonic 33");
|
||||
case ambisonicACN34: return NEEDS_TRANS ("Ambisonic 34");
|
||||
case ambisonicACN35: return NEEDS_TRANS ("Ambisonic 35");
|
||||
case ambisonicACN36: return NEEDS_TRANS ("Ambisonic 36");
|
||||
case ambisonicACN37: return NEEDS_TRANS ("Ambisonic 37");
|
||||
case ambisonicACN38: return NEEDS_TRANS ("Ambisonic 38");
|
||||
case ambisonicACN39: return NEEDS_TRANS ("Ambisonic 39");
|
||||
case ambisonicACN40: return NEEDS_TRANS ("Ambisonic 40");
|
||||
case ambisonicACN41: return NEEDS_TRANS ("Ambisonic 41");
|
||||
case ambisonicACN42: return NEEDS_TRANS ("Ambisonic 42");
|
||||
case ambisonicACN43: return NEEDS_TRANS ("Ambisonic 43");
|
||||
case ambisonicACN44: return NEEDS_TRANS ("Ambisonic 44");
|
||||
case ambisonicACN45: return NEEDS_TRANS ("Ambisonic 45");
|
||||
case ambisonicACN46: return NEEDS_TRANS ("Ambisonic 46");
|
||||
case ambisonicACN47: return NEEDS_TRANS ("Ambisonic 47");
|
||||
case ambisonicACN48: return NEEDS_TRANS ("Ambisonic 48");
|
||||
case ambisonicACN49: return NEEDS_TRANS ("Ambisonic 49");
|
||||
case ambisonicACN50: return NEEDS_TRANS ("Ambisonic 50");
|
||||
case ambisonicACN51: return NEEDS_TRANS ("Ambisonic 51");
|
||||
case ambisonicACN52: return NEEDS_TRANS ("Ambisonic 52");
|
||||
case ambisonicACN53: return NEEDS_TRANS ("Ambisonic 53");
|
||||
case ambisonicACN54: return NEEDS_TRANS ("Ambisonic 54");
|
||||
case ambisonicACN55: return NEEDS_TRANS ("Ambisonic 55");
|
||||
case ambisonicACN56: return NEEDS_TRANS ("Ambisonic 56");
|
||||
case ambisonicACN57: return NEEDS_TRANS ("Ambisonic 57");
|
||||
case ambisonicACN58: return NEEDS_TRANS ("Ambisonic 58");
|
||||
case ambisonicACN59: return NEEDS_TRANS ("Ambisonic 59");
|
||||
case ambisonicACN60: return NEEDS_TRANS ("Ambisonic 60");
|
||||
case ambisonicACN61: return NEEDS_TRANS ("Ambisonic 61");
|
||||
case ambisonicACN62: return NEEDS_TRANS ("Ambisonic 62");
|
||||
case ambisonicACN63: return NEEDS_TRANS ("Ambisonic 63");
|
||||
case bottomFrontLeft: return NEEDS_TRANS ("Bottom Front Left");
|
||||
case bottomFrontCentre: return NEEDS_TRANS ("Bottom Front Centre");
|
||||
case bottomFrontRight: return NEEDS_TRANS ("Bottom Front Right");
|
||||
case proximityLeft: return NEEDS_TRANS ("Proximity Left");
|
||||
case proximityRight: return NEEDS_TRANS ("Proximity Right");
|
||||
case bottomSideLeft: return NEEDS_TRANS ("Bottom Side Left");
|
||||
case bottomSideRight: return NEEDS_TRANS ("Bottom Side Right");
|
||||
case bottomRearLeft: return NEEDS_TRANS ("Bottom Rear Left");
|
||||
case bottomRearCentre: return NEEDS_TRANS ("Bottom Rear Centre");
|
||||
case bottomRearRight: return NEEDS_TRANS ("Bottom Rear Right");
|
||||
case discreteChannel0:
|
||||
case unknown:
|
||||
default: break;
|
||||
}
|
||||
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
String AudioChannelSet::getAbbreviatedChannelTypeName (AudioChannelSet::ChannelType type)
|
||||
{
|
||||
if (type >= discreteChannel0)
|
||||
return String (type - discreteChannel0 + 1);
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case left: return "L";
|
||||
case right: return "R";
|
||||
case centre: return "C";
|
||||
case LFE: return "Lfe";
|
||||
case leftSurround: return "Ls";
|
||||
case rightSurround: return "Rs";
|
||||
case leftCentre: return "Lc";
|
||||
case rightCentre: return "Rc";
|
||||
case centreSurround: return "Cs";
|
||||
case leftSurroundRear: return "Lrs";
|
||||
case rightSurroundRear: return "Rrs";
|
||||
case topMiddle: return "Tm";
|
||||
case topFrontLeft: return "Tfl";
|
||||
case topFrontCentre: return "Tfc";
|
||||
case topFrontRight: return "Tfr";
|
||||
case topRearLeft: return "Trl";
|
||||
case topRearCentre: return "Trc";
|
||||
case topRearRight: return "Trr";
|
||||
case wideLeft: return "Wl";
|
||||
case wideRight: return "Wr";
|
||||
case LFE2: return "Lfe2";
|
||||
case leftSurroundSide: return "Lss";
|
||||
case rightSurroundSide: return "Rss";
|
||||
case ambisonicACN0: return "ACN0";
|
||||
case ambisonicACN1: return "ACN1";
|
||||
case ambisonicACN2: return "ACN2";
|
||||
case ambisonicACN3: return "ACN3";
|
||||
case ambisonicACN4: return "ACN4";
|
||||
case ambisonicACN5: return "ACN5";
|
||||
case ambisonicACN6: return "ACN6";
|
||||
case ambisonicACN7: return "ACN7";
|
||||
case ambisonicACN8: return "ACN8";
|
||||
case ambisonicACN9: return "ACN9";
|
||||
case ambisonicACN10: return "ACN10";
|
||||
case ambisonicACN11: return "ACN11";
|
||||
case ambisonicACN12: return "ACN12";
|
||||
case ambisonicACN13: return "ACN13";
|
||||
case ambisonicACN14: return "ACN14";
|
||||
case ambisonicACN15: return "ACN15";
|
||||
case ambisonicACN16: return "ACN16";
|
||||
case ambisonicACN17: return "ACN17";
|
||||
case ambisonicACN18: return "ACN18";
|
||||
case ambisonicACN19: return "ACN19";
|
||||
case ambisonicACN20: return "ACN20";
|
||||
case ambisonicACN21: return "ACN21";
|
||||
case ambisonicACN22: return "ACN22";
|
||||
case ambisonicACN23: return "ACN23";
|
||||
case ambisonicACN24: return "ACN24";
|
||||
case ambisonicACN25: return "ACN25";
|
||||
case ambisonicACN26: return "ACN26";
|
||||
case ambisonicACN27: return "ACN27";
|
||||
case ambisonicACN28: return "ACN28";
|
||||
case ambisonicACN29: return "ACN29";
|
||||
case ambisonicACN30: return "ACN30";
|
||||
case ambisonicACN31: return "ACN31";
|
||||
case ambisonicACN32: return "ACN32";
|
||||
case ambisonicACN33: return "ACN33";
|
||||
case ambisonicACN34: return "ACN34";
|
||||
case ambisonicACN35: return "ACN35";
|
||||
case ambisonicACN36: return "ACN36";
|
||||
case ambisonicACN37: return "ACN37";
|
||||
case ambisonicACN38: return "ACN38";
|
||||
case ambisonicACN39: return "ACN39";
|
||||
case ambisonicACN40: return "ACN40";
|
||||
case ambisonicACN41: return "ACN41";
|
||||
case ambisonicACN42: return "ACN42";
|
||||
case ambisonicACN43: return "ACN43";
|
||||
case ambisonicACN44: return "ACN44";
|
||||
case ambisonicACN45: return "ACN45";
|
||||
case ambisonicACN46: return "ACN46";
|
||||
case ambisonicACN47: return "ACN47";
|
||||
case ambisonicACN48: return "ACN48";
|
||||
case ambisonicACN49: return "ACN49";
|
||||
case ambisonicACN50: return "ACN50";
|
||||
case ambisonicACN51: return "ACN51";
|
||||
case ambisonicACN52: return "ACN52";
|
||||
case ambisonicACN53: return "ACN53";
|
||||
case ambisonicACN54: return "ACN54";
|
||||
case ambisonicACN55: return "ACN55";
|
||||
case ambisonicACN56: return "ACN56";
|
||||
case ambisonicACN57: return "ACN57";
|
||||
case ambisonicACN58: return "ACN58";
|
||||
case ambisonicACN59: return "ACN59";
|
||||
case ambisonicACN60: return "ACN60";
|
||||
case ambisonicACN61: return "ACN61";
|
||||
case ambisonicACN62: return "ACN62";
|
||||
case ambisonicACN63: return "ACN63";
|
||||
case topSideLeft: return "Tsl";
|
||||
case topSideRight: return "Tsr";
|
||||
case bottomFrontLeft: return "Bfl";
|
||||
case bottomFrontCentre: return "Bfc";
|
||||
case bottomFrontRight: return "Bfr";
|
||||
case proximityLeft: return "Pl";
|
||||
case proximityRight: return "Pr";
|
||||
case bottomSideLeft: return "Bsl";
|
||||
case bottomSideRight: return "Bsr";
|
||||
case bottomRearLeft: return "Brl";
|
||||
case bottomRearCentre: return "Brc";
|
||||
case bottomRearRight: return "Brr";
|
||||
case discreteChannel0:
|
||||
case unknown:
|
||||
default: break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
AudioChannelSet::ChannelType AudioChannelSet::getChannelTypeFromAbbreviation (const String& abbr)
|
||||
{
|
||||
if (abbr.length() > 0 && (abbr[0] >= '0' && abbr[0] <= '9'))
|
||||
return static_cast<AudioChannelSet::ChannelType> (static_cast<int> (discreteChannel0)
|
||||
+ abbr.getIntValue() - 1);
|
||||
|
||||
if (abbr == "L") return left;
|
||||
if (abbr == "R") return right;
|
||||
if (abbr == "C") return centre;
|
||||
if (abbr == "Lfe") return LFE;
|
||||
if (abbr == "Ls") return leftSurround;
|
||||
if (abbr == "Rs") return rightSurround;
|
||||
if (abbr == "Lc") return leftCentre;
|
||||
if (abbr == "Rc") return rightCentre;
|
||||
if (abbr == "Cs") return centreSurround;
|
||||
if (abbr == "Lrs") return leftSurroundRear;
|
||||
if (abbr == "Rrs") return rightSurroundRear;
|
||||
if (abbr == "Tm") return topMiddle;
|
||||
if (abbr == "Tfl") return topFrontLeft;
|
||||
if (abbr == "Tfc") return topFrontCentre;
|
||||
if (abbr == "Tfr") return topFrontRight;
|
||||
if (abbr == "Trl") return topRearLeft;
|
||||
if (abbr == "Trc") return topRearCentre;
|
||||
if (abbr == "Trr") return topRearRight;
|
||||
if (abbr == "Wl") return wideLeft;
|
||||
if (abbr == "Wr") return wideRight;
|
||||
if (abbr == "Lfe2") return LFE2;
|
||||
if (abbr == "Lss") return leftSurroundSide;
|
||||
if (abbr == "Rss") return rightSurroundSide;
|
||||
if (abbr == "W") return ambisonicW;
|
||||
if (abbr == "X") return ambisonicX;
|
||||
if (abbr == "Y") return ambisonicY;
|
||||
if (abbr == "Z") return ambisonicZ;
|
||||
if (abbr == "ACN0") return ambisonicACN0;
|
||||
if (abbr == "ACN1") return ambisonicACN1;
|
||||
if (abbr == "ACN2") return ambisonicACN2;
|
||||
if (abbr == "ACN3") return ambisonicACN3;
|
||||
if (abbr == "ACN4") return ambisonicACN4;
|
||||
if (abbr == "ACN5") return ambisonicACN5;
|
||||
if (abbr == "ACN6") return ambisonicACN6;
|
||||
if (abbr == "ACN7") return ambisonicACN7;
|
||||
if (abbr == "ACN8") return ambisonicACN8;
|
||||
if (abbr == "ACN9") return ambisonicACN9;
|
||||
if (abbr == "ACN10") return ambisonicACN10;
|
||||
if (abbr == "ACN11") return ambisonicACN11;
|
||||
if (abbr == "ACN12") return ambisonicACN12;
|
||||
if (abbr == "ACN13") return ambisonicACN13;
|
||||
if (abbr == "ACN14") return ambisonicACN14;
|
||||
if (abbr == "ACN15") return ambisonicACN15;
|
||||
if (abbr == "ACN16") return ambisonicACN16;
|
||||
if (abbr == "ACN17") return ambisonicACN17;
|
||||
if (abbr == "ACN18") return ambisonicACN18;
|
||||
if (abbr == "ACN19") return ambisonicACN19;
|
||||
if (abbr == "ACN20") return ambisonicACN20;
|
||||
if (abbr == "ACN21") return ambisonicACN21;
|
||||
if (abbr == "ACN22") return ambisonicACN22;
|
||||
if (abbr == "ACN23") return ambisonicACN23;
|
||||
if (abbr == "ACN24") return ambisonicACN24;
|
||||
if (abbr == "ACN25") return ambisonicACN25;
|
||||
if (abbr == "ACN26") return ambisonicACN26;
|
||||
if (abbr == "ACN27") return ambisonicACN27;
|
||||
if (abbr == "ACN28") return ambisonicACN28;
|
||||
if (abbr == "ACN29") return ambisonicACN29;
|
||||
if (abbr == "ACN30") return ambisonicACN30;
|
||||
if (abbr == "ACN31") return ambisonicACN31;
|
||||
if (abbr == "ACN32") return ambisonicACN32;
|
||||
if (abbr == "ACN33") return ambisonicACN33;
|
||||
if (abbr == "ACN34") return ambisonicACN34;
|
||||
if (abbr == "ACN35") return ambisonicACN35;
|
||||
if (abbr == "ACN36") return ambisonicACN36;
|
||||
if (abbr == "ACN37") return ambisonicACN37;
|
||||
if (abbr == "ACN38") return ambisonicACN38;
|
||||
if (abbr == "ACN39") return ambisonicACN39;
|
||||
if (abbr == "ACN40") return ambisonicACN40;
|
||||
if (abbr == "ACN41") return ambisonicACN41;
|
||||
if (abbr == "ACN42") return ambisonicACN42;
|
||||
if (abbr == "ACN43") return ambisonicACN43;
|
||||
if (abbr == "ACN44") return ambisonicACN44;
|
||||
if (abbr == "ACN45") return ambisonicACN45;
|
||||
if (abbr == "ACN46") return ambisonicACN46;
|
||||
if (abbr == "ACN47") return ambisonicACN47;
|
||||
if (abbr == "ACN48") return ambisonicACN48;
|
||||
if (abbr == "ACN49") return ambisonicACN49;
|
||||
if (abbr == "ACN50") return ambisonicACN50;
|
||||
if (abbr == "ACN51") return ambisonicACN51;
|
||||
if (abbr == "ACN52") return ambisonicACN52;
|
||||
if (abbr == "ACN53") return ambisonicACN53;
|
||||
if (abbr == "ACN54") return ambisonicACN54;
|
||||
if (abbr == "ACN55") return ambisonicACN55;
|
||||
if (abbr == "ACN56") return ambisonicACN56;
|
||||
if (abbr == "ACN57") return ambisonicACN57;
|
||||
if (abbr == "ACN58") return ambisonicACN58;
|
||||
if (abbr == "ACN59") return ambisonicACN59;
|
||||
if (abbr == "ACN60") return ambisonicACN60;
|
||||
if (abbr == "ACN61") return ambisonicACN61;
|
||||
if (abbr == "ACN62") return ambisonicACN62;
|
||||
if (abbr == "ACN63") return ambisonicACN63;
|
||||
if (abbr == "Tsl") return topSideLeft;
|
||||
if (abbr == "Tsr") return topSideRight;
|
||||
if (abbr == "Bfl") return bottomFrontLeft;
|
||||
if (abbr == "Bfc") return bottomFrontCentre;
|
||||
if (abbr == "Bfr") return bottomFrontRight;
|
||||
if (abbr == "Bsl") return bottomSideLeft;
|
||||
if (abbr == "Bsr") return bottomSideRight;
|
||||
if (abbr == "Brl") return bottomRearLeft;
|
||||
if (abbr == "Brc") return bottomRearCentre;
|
||||
if (abbr == "Brr") return bottomRearRight;
|
||||
return unknown;
|
||||
}
|
||||
|
||||
String AudioChannelSet::getSpeakerArrangementAsString() const
|
||||
{
|
||||
StringArray speakerTypes;
|
||||
|
||||
for (auto& speaker : getChannelTypes())
|
||||
{
|
||||
auto name = getAbbreviatedChannelTypeName (speaker);
|
||||
|
||||
if (name.isNotEmpty())
|
||||
speakerTypes.add (name);
|
||||
}
|
||||
|
||||
return speakerTypes.joinIntoString (" ");
|
||||
}
|
||||
|
||||
AudioChannelSet AudioChannelSet::fromAbbreviatedString (const String& str)
|
||||
{
|
||||
AudioChannelSet set;
|
||||
|
||||
for (auto& abbr : StringArray::fromTokens (str, true))
|
||||
{
|
||||
auto type = getChannelTypeFromAbbreviation (abbr);
|
||||
|
||||
if (type != unknown)
|
||||
set.addChannel (type);
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
String AudioChannelSet::getDescription() const
|
||||
{
|
||||
if (isDiscreteLayout()) return "Discrete #" + String (size());
|
||||
if (*this == disabled()) return "Disabled";
|
||||
if (*this == mono()) return "Mono";
|
||||
if (*this == stereo()) return "Stereo";
|
||||
|
||||
if (*this == createLCR()) return "LCR";
|
||||
if (*this == createLRS()) return "LRS";
|
||||
if (*this == createLCRS()) return "LCRS";
|
||||
|
||||
if (*this == create5point0()) return "5.0 Surround";
|
||||
if (*this == create5point0point2()) return "5.0.2 Surround";
|
||||
if (*this == create5point0point4()) return "5.0.4 Surround";
|
||||
if (*this == create5point1()) return "5.1 Surround";
|
||||
if (*this == create5point1point2()) return "5.1.2 Surround";
|
||||
if (*this == create5point1point4()) return "5.1.4 Surround";
|
||||
if (*this == create6point0()) return "6.0 Surround";
|
||||
if (*this == create6point1()) return "6.1 Surround";
|
||||
if (*this == create6point0Music()) return "6.0 (Music) Surround";
|
||||
if (*this == create6point1Music()) return "6.1 (Music) Surround";
|
||||
if (*this == create7point0()) return "7.0 Surround";
|
||||
if (*this == create7point1()) return "7.1 Surround";
|
||||
if (*this == create7point0SDDS()) return "7.0 Surround SDDS";
|
||||
if (*this == create7point1SDDS()) return "7.1 Surround SDDS";
|
||||
if (*this == create7point0point2()) return "7.0.2 Surround";
|
||||
if (*this == create7point0point4()) return "7.0.4 Surround";
|
||||
if (*this == create7point0point6()) return "7.0.6 Surround";
|
||||
if (*this == create7point1point2()) return "7.1.2 Surround";
|
||||
if (*this == create7point1point4()) return "7.1.4 Surround";
|
||||
if (*this == create7point1point6()) return "7.1.6 Surround";
|
||||
if (*this == create9point0point4()) return "9.0.4 Surround (Atmos)";
|
||||
if (*this == create9point1point4()) return "9.1.4 Surround (Atmos)";
|
||||
if (*this == create9point0point6()) return "9.0.6 Surround (Atmos)";
|
||||
if (*this == create9point1point6()) return "9.1.6 Surround (Atmos)";
|
||||
if (*this == create9point0point4ITU()) return "9.0.4 Surround (ITU)";
|
||||
if (*this == create9point1point4ITU()) return "9.1.4 Surround (ITU)";
|
||||
if (*this == create9point0point6ITU()) return "9.0.6 Surround (ITU)";
|
||||
if (*this == create9point1point6ITU()) return "9.1.6 Surround (ITU)";
|
||||
|
||||
if (*this == quadraphonic()) return "Quadraphonic";
|
||||
if (*this == pentagonal()) return "Pentagonal";
|
||||
if (*this == hexagonal()) return "Hexagonal";
|
||||
if (*this == octagonal()) return "Octagonal";
|
||||
|
||||
// ambisonics
|
||||
{
|
||||
auto order = getAmbisonicOrder();
|
||||
|
||||
if (order >= 0)
|
||||
{
|
||||
String suffix;
|
||||
|
||||
switch (order)
|
||||
{
|
||||
case 1: suffix = "st"; break;
|
||||
case 2: suffix = "nd"; break;
|
||||
case 3: suffix = "rd"; break;
|
||||
default: suffix = "th"; break;
|
||||
}
|
||||
|
||||
return String (order) + suffix + " Order Ambisonics";
|
||||
}
|
||||
}
|
||||
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
bool AudioChannelSet::isDiscreteLayout() const noexcept
|
||||
{
|
||||
const auto channelTypes = getChannelTypes();
|
||||
|
||||
return std::none_of (std::begin (channelTypes),
|
||||
std::end (channelTypes),
|
||||
[] (const auto& t) { return t < discreteChannel0; });
|
||||
}
|
||||
|
||||
int AudioChannelSet::size() const noexcept
|
||||
{
|
||||
return channels.countNumberOfSetBits();
|
||||
}
|
||||
|
||||
AudioChannelSet::ChannelType AudioChannelSet::getTypeOfChannel (int index) const noexcept
|
||||
{
|
||||
int bit = channels.findNextSetBit (0);
|
||||
|
||||
for (int i = 0; i < index && bit >= 0; ++i)
|
||||
bit = channels.findNextSetBit (bit + 1);
|
||||
|
||||
return static_cast<ChannelType> (bit);
|
||||
}
|
||||
|
||||
int AudioChannelSet::getChannelIndexForType (AudioChannelSet::ChannelType type) const noexcept
|
||||
{
|
||||
int idx = 0;
|
||||
|
||||
for (int bit = channels.findNextSetBit (0); bit >= 0; bit = channels.findNextSetBit (bit + 1))
|
||||
{
|
||||
if (static_cast<ChannelType> (bit) == type)
|
||||
return idx;
|
||||
|
||||
idx++;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
Array<AudioChannelSet::ChannelType> AudioChannelSet::getChannelTypes() const
|
||||
{
|
||||
Array<ChannelType> result;
|
||||
|
||||
for (int bit = channels.findNextSetBit (0); bit >= 0; bit = channels.findNextSetBit (bit + 1))
|
||||
result.add (static_cast<ChannelType> (bit));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void AudioChannelSet::addChannel (ChannelType newChannel)
|
||||
{
|
||||
const int bit = static_cast<int> (newChannel);
|
||||
jassert (bit >= 0 && bit < 1024);
|
||||
channels.setBit (bit);
|
||||
}
|
||||
|
||||
void AudioChannelSet::removeChannel (ChannelType newChannel)
|
||||
{
|
||||
const int bit = static_cast<int> (newChannel);
|
||||
jassert (bit >= 0 && bit < 1024);
|
||||
channels.clearBit (bit);
|
||||
}
|
||||
|
||||
AudioChannelSet AudioChannelSet::disabled() { return {}; }
|
||||
AudioChannelSet AudioChannelSet::mono() { return AudioChannelSet ({ centre }); }
|
||||
AudioChannelSet AudioChannelSet::stereo() { return AudioChannelSet ({ left, right }); }
|
||||
AudioChannelSet AudioChannelSet::createLCR() { return AudioChannelSet ({ left, right, centre }); }
|
||||
AudioChannelSet AudioChannelSet::createLRS() { return AudioChannelSet ({ left, right, surround }); }
|
||||
AudioChannelSet AudioChannelSet::createLCRS() { return AudioChannelSet ({ left, right, centre, surround }); }
|
||||
AudioChannelSet AudioChannelSet::create5point0() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround }); }
|
||||
AudioChannelSet AudioChannelSet::create5point1() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround }); }
|
||||
AudioChannelSet AudioChannelSet::create6point0() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, centreSurround }); }
|
||||
AudioChannelSet AudioChannelSet::create6point1() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, centreSurround }); }
|
||||
AudioChannelSet AudioChannelSet::create6point0Music() { return AudioChannelSet ({ left, right, leftSurround, rightSurround, leftSurroundSide, rightSurroundSide }); }
|
||||
AudioChannelSet AudioChannelSet::create6point1Music() { return AudioChannelSet ({ left, right, LFE, leftSurround, rightSurround, leftSurroundSide, rightSurroundSide }); }
|
||||
AudioChannelSet AudioChannelSet::create7point0() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear }); }
|
||||
AudioChannelSet AudioChannelSet::create7point0SDDS() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre }); }
|
||||
AudioChannelSet AudioChannelSet::create7point1() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear }); }
|
||||
AudioChannelSet AudioChannelSet::create7point1SDDS() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, leftCentre, rightCentre }); }
|
||||
AudioChannelSet AudioChannelSet::quadraphonic() { return AudioChannelSet ({ left, right, leftSurround, rightSurround }); }
|
||||
AudioChannelSet AudioChannelSet::pentagonal() { return AudioChannelSet ({ left, right, centre, leftSurroundRear, rightSurroundRear }); }
|
||||
AudioChannelSet AudioChannelSet::hexagonal() { return AudioChannelSet ({ left, right, centre, centreSurround, leftSurroundRear, rightSurroundRear }); }
|
||||
AudioChannelSet AudioChannelSet::octagonal() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, centreSurround, wideLeft, wideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create5point0point2() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, topSideLeft, topSideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create5point1point2() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, topSideLeft, topSideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create5point0point4() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create5point1point4() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point0point2() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topSideLeft, topSideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point1point2() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topSideLeft, topSideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point0point4() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point1point4() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point0point6() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create7point1point6() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point0point4() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point1point4() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point0point6() { return AudioChannelSet ({ left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point1point6() { return AudioChannelSet ({ left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point0point4ITU() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point1point4ITU() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point0point6ITU() { return AudioChannelSet ({ left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight, topSideLeft, topSideRight }); }
|
||||
AudioChannelSet AudioChannelSet::create9point1point6ITU() { return AudioChannelSet ({ left, right, centre, LFE, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight, topSideLeft, topSideRight }); }
|
||||
|
||||
AudioChannelSet AudioChannelSet::ambisonic (int order)
|
||||
{
|
||||
jassert (isPositiveAndBelow (order, 8));
|
||||
|
||||
static constexpr std::pair<int, int> continuousRanges[] { { ambisonicACN0, ambisonicACN3 },
|
||||
{ ambisonicACN4, ambisonicACN35 },
|
||||
{ ambisonicACN36, ambisonicACN63 } };
|
||||
|
||||
AudioChannelSet set;
|
||||
|
||||
const auto setBits = [&set] (auto range, auto maxNumToSet)
|
||||
{
|
||||
const auto numToSet = std::min (maxNumToSet, range.second - range.first + 1);
|
||||
set.channels.setRange (range.first, numToSet, true);
|
||||
return numToSet;
|
||||
};
|
||||
|
||||
const auto numAmbisonicChannels = square (order + 1);
|
||||
|
||||
for (int rangeIdx = 0, bitsSet = 0; bitsSet < numAmbisonicChannels; ++rangeIdx)
|
||||
{
|
||||
bitsSet += setBits (continuousRanges[rangeIdx], numAmbisonicChannels - bitsSet);
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
int AudioChannelSet::getAmbisonicOrder() const
|
||||
{
|
||||
auto ambisonicOrder = getAmbisonicOrderForNumChannels (size());
|
||||
|
||||
if (ambisonicOrder >= 0)
|
||||
return (*this == ambisonic (ambisonicOrder) ? ambisonicOrder : -1);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
AudioChannelSet AudioChannelSet::discreteChannels (int numChannels)
|
||||
{
|
||||
AudioChannelSet s;
|
||||
s.channels.setRange (discreteChannel0, numChannels, true);
|
||||
return s;
|
||||
}
|
||||
|
||||
AudioChannelSet AudioChannelSet::canonicalChannelSet (int numChannels)
|
||||
{
|
||||
if (numChannels == 1) return AudioChannelSet::mono();
|
||||
if (numChannels == 2) return AudioChannelSet::stereo();
|
||||
if (numChannels == 3) return AudioChannelSet::createLCR();
|
||||
if (numChannels == 4) return AudioChannelSet::quadraphonic();
|
||||
if (numChannels == 5) return AudioChannelSet::create5point0();
|
||||
if (numChannels == 6) return AudioChannelSet::create5point1();
|
||||
if (numChannels == 7) return AudioChannelSet::create7point0();
|
||||
if (numChannels == 8) return AudioChannelSet::create7point1();
|
||||
|
||||
return discreteChannels (numChannels);
|
||||
}
|
||||
|
||||
AudioChannelSet AudioChannelSet::namedChannelSet (int numChannels)
|
||||
{
|
||||
if (numChannels == 1) return AudioChannelSet::mono();
|
||||
if (numChannels == 2) return AudioChannelSet::stereo();
|
||||
if (numChannels == 3) return AudioChannelSet::createLCR();
|
||||
if (numChannels == 4) return AudioChannelSet::quadraphonic();
|
||||
if (numChannels == 5) return AudioChannelSet::create5point0();
|
||||
if (numChannels == 6) return AudioChannelSet::create5point1();
|
||||
if (numChannels == 7) return AudioChannelSet::create7point0();
|
||||
if (numChannels == 8) return AudioChannelSet::create7point1();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Array<AudioChannelSet> AudioChannelSet::channelSetsWithNumberOfChannels (int numChannels)
|
||||
{
|
||||
Array<AudioChannelSet> retval;
|
||||
|
||||
if (numChannels != 0)
|
||||
{
|
||||
retval.add (AudioChannelSet::discreteChannels (numChannels));
|
||||
|
||||
retval.addArray ([numChannels]() -> Array<AudioChannelSet>
|
||||
{
|
||||
switch (numChannels)
|
||||
{
|
||||
case 1:
|
||||
return { AudioChannelSet::mono() };
|
||||
case 2:
|
||||
return { AudioChannelSet::stereo() };
|
||||
case 3:
|
||||
return { AudioChannelSet::createLCR(),
|
||||
AudioChannelSet::createLRS() };
|
||||
case 4:
|
||||
return { AudioChannelSet::quadraphonic(),
|
||||
AudioChannelSet::createLCRS() };
|
||||
case 5:
|
||||
return { AudioChannelSet::create5point0(),
|
||||
AudioChannelSet::pentagonal() };
|
||||
case 6:
|
||||
return { AudioChannelSet::create5point1(),
|
||||
AudioChannelSet::create6point0(),
|
||||
AudioChannelSet::create6point0Music(),
|
||||
AudioChannelSet::hexagonal() };
|
||||
case 7:
|
||||
return { AudioChannelSet::create7point0(),
|
||||
AudioChannelSet::create7point0SDDS(),
|
||||
AudioChannelSet::create6point1(),
|
||||
AudioChannelSet::create6point1Music() };
|
||||
case 8:
|
||||
return { AudioChannelSet::create7point1(),
|
||||
AudioChannelSet::create7point1SDDS(),
|
||||
AudioChannelSet::octagonal(),
|
||||
AudioChannelSet::create5point1point2() };
|
||||
case 9:
|
||||
return { AudioChannelSet::create7point0point2() };
|
||||
case 10:
|
||||
return { AudioChannelSet::create5point1point4(),
|
||||
AudioChannelSet::create7point1point2() };
|
||||
case 11:
|
||||
return { AudioChannelSet::create7point0point4() };
|
||||
case 12:
|
||||
return { AudioChannelSet::create7point1point4() };
|
||||
case 13:
|
||||
return { AudioChannelSet::create7point0point6(),
|
||||
AudioChannelSet::create9point0point4(),
|
||||
AudioChannelSet::create9point0point4ITU() };
|
||||
case 14:
|
||||
return { AudioChannelSet::create7point1point6(),
|
||||
AudioChannelSet::create9point1point4(),
|
||||
AudioChannelSet::create9point1point4ITU() };
|
||||
case 15:
|
||||
return {
|
||||
AudioChannelSet::create9point0point6(),
|
||||
AudioChannelSet::create9point0point6ITU() };
|
||||
case 16:
|
||||
return { AudioChannelSet::create9point1point6(),
|
||||
AudioChannelSet::create9point1point6ITU() };
|
||||
}
|
||||
|
||||
return {};
|
||||
}());
|
||||
|
||||
auto order = getAmbisonicOrderForNumChannels (numChannels);
|
||||
if (order >= 0)
|
||||
retval.add (AudioChannelSet::ambisonic (order));
|
||||
}
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
AudioChannelSet JUCE_CALLTYPE AudioChannelSet::channelSetWithChannels (const Array<ChannelType>& channelArray)
|
||||
{
|
||||
AudioChannelSet set;
|
||||
|
||||
for (auto ch : channelArray)
|
||||
{
|
||||
jassert (! set.channels[static_cast<int> (ch)]);
|
||||
|
||||
set.addChannel (ch);
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
AudioChannelSet JUCE_CALLTYPE AudioChannelSet::fromWaveChannelMask (int32 dwChannelMask)
|
||||
{
|
||||
return AudioChannelSet (static_cast<uint32> ((dwChannelMask & ((1 << 18) - 1)) << 1));
|
||||
}
|
||||
|
||||
int32 AudioChannelSet::getWaveChannelMask() const noexcept
|
||||
{
|
||||
if (channels.getHighestBit() > topRearRight)
|
||||
return -1;
|
||||
|
||||
return (channels.toInteger() >> 1);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
int AudioChannelSet::getAmbisonicOrderForNumChannels (int numChannels, int maxOrderToCheck)
|
||||
{
|
||||
for (auto i = 0; i <= maxOrderToCheck; ++i)
|
||||
if (numChannels == square (i + 1))
|
||||
return i;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class AudioChannelSetUnitTest final : public UnitTest
|
||||
{
|
||||
public:
|
||||
AudioChannelSetUnitTest()
|
||||
: UnitTest ("AudioChannelSetUnitTest", UnitTestCategories::audio)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
auto max = AudioChannelSet::maxChannelsOfNamedLayout;
|
||||
|
||||
beginTest ("maxChannelsOfNamedLayout is non-discrete");
|
||||
expect (AudioChannelSet::channelSetsWithNumberOfChannels (max).size() >= 2);
|
||||
|
||||
beginTest ("channelSetsWithNumberOfChannels returns correct speaker count");
|
||||
{
|
||||
for (auto ch = 1; ch <= max; ++ch)
|
||||
{
|
||||
auto channelSets = AudioChannelSet::channelSetsWithNumberOfChannels (ch);
|
||||
|
||||
for (auto set : channelSets)
|
||||
expect (set.size() == ch);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Ambisonics");
|
||||
{
|
||||
uint64 mask = 0;
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN0);
|
||||
checkAmbisonic (mask, 0, "0th Order Ambisonics");
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN1) | (1ull << AudioChannelSet::ambisonicACN2) | (1ull << AudioChannelSet::ambisonicACN3);
|
||||
checkAmbisonic (mask, 1, "1st Order Ambisonics");
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN4) | (1ull << AudioChannelSet::ambisonicACN5) | (1ull << AudioChannelSet::ambisonicACN6)
|
||||
| (1ull << AudioChannelSet::ambisonicACN7) | (1ull << AudioChannelSet::ambisonicACN8);
|
||||
checkAmbisonic (mask, 2, "2nd Order Ambisonics");
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN9) | (1ull << AudioChannelSet::ambisonicACN10) | (1ull << AudioChannelSet::ambisonicACN11)
|
||||
| (1ull << AudioChannelSet::ambisonicACN12) | (1ull << AudioChannelSet::ambisonicACN13) | (1ull << AudioChannelSet::ambisonicACN14)
|
||||
| (1ull << AudioChannelSet::ambisonicACN15);
|
||||
checkAmbisonic (mask, 3, "3rd Order Ambisonics");
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN16) | (1ull << AudioChannelSet::ambisonicACN17) | (1ull << AudioChannelSet::ambisonicACN18)
|
||||
| (1ull << AudioChannelSet::ambisonicACN19) | (1ull << AudioChannelSet::ambisonicACN20) | (1ull << AudioChannelSet::ambisonicACN21)
|
||||
| (1ull << AudioChannelSet::ambisonicACN22) | (1ull << AudioChannelSet::ambisonicACN23) | (1ull << AudioChannelSet::ambisonicACN24);
|
||||
checkAmbisonic (mask, 4, "4th Order Ambisonics");
|
||||
|
||||
mask |= (1ull << AudioChannelSet::ambisonicACN25) | (1ull << AudioChannelSet::ambisonicACN26) | (1ull << AudioChannelSet::ambisonicACN27)
|
||||
| (1ull << AudioChannelSet::ambisonicACN28) | (1ull << AudioChannelSet::ambisonicACN29) | (1ull << AudioChannelSet::ambisonicACN30)
|
||||
| (1ull << AudioChannelSet::ambisonicACN31) | (1ull << AudioChannelSet::ambisonicACN32) | (1ull << AudioChannelSet::ambisonicACN33)
|
||||
| (1ull << AudioChannelSet::ambisonicACN34) | (1ull << AudioChannelSet::ambisonicACN35);
|
||||
checkAmbisonic (mask, 5, "5th Order Ambisonics");
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void checkAmbisonic (uint64 mask, int order, const char* layoutName)
|
||||
{
|
||||
auto expected = AudioChannelSet::ambisonic (order);
|
||||
auto numChannels = expected.size();
|
||||
|
||||
expect (numChannels == BigInteger ((int64) mask).countNumberOfSetBits());
|
||||
expect (channelSetFromMask (mask) == expected);
|
||||
|
||||
expect (order == expected.getAmbisonicOrder());
|
||||
expect (expected.getDescription() == layoutName);
|
||||
|
||||
auto layouts = AudioChannelSet::channelSetsWithNumberOfChannels (numChannels);
|
||||
expect (layouts.contains (expected));
|
||||
|
||||
for (auto layout : layouts)
|
||||
expect (layout.getAmbisonicOrder() == (layout == expected ? order : -1));
|
||||
}
|
||||
|
||||
static AudioChannelSet channelSetFromMask (uint64 mask)
|
||||
{
|
||||
Array<AudioChannelSet::ChannelType> channels;
|
||||
for (int bit = 0; bit <= 62; ++bit)
|
||||
if ((mask & (1ull << bit)) != 0)
|
||||
channels.add (static_cast<AudioChannelSet::ChannelType> (bit));
|
||||
|
||||
return AudioChannelSet::channelSetWithChannels (channels);
|
||||
}
|
||||
};
|
||||
|
||||
static AudioChannelSetUnitTest audioChannelSetUnitTest;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,649 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a set of audio channel types.
|
||||
|
||||
For example, you might have a set of left + right channels, which is a stereo
|
||||
channel set. It is a collection of values from the AudioChannelSet::ChannelType
|
||||
enum, where each type may only occur once within the set.
|
||||
|
||||
The documentation below lists which AudioChannelSet corresponds to which native
|
||||
layouts used by AAX, VST2/VST3 and CoreAudio/AU. The layout tags in CoreAudio
|
||||
are particularly confusing. For example, the layout which is labeled as "7.1 SDDS"
|
||||
in Logic Pro, corresponds to CoreAudio/AU's kAudioChannelLayoutTag_DTS_7_0 tag, whereas
|
||||
AAX's DTS 7.1 Layout corresponds to CoreAudio/AU's
|
||||
kAudioChannelLayoutTag_MPEG_7_1_A format, etc. Please do not use the CoreAudio tag
|
||||
as an indication to the actual layout of the speakers.
|
||||
|
||||
@see Bus
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioChannelSet
|
||||
{
|
||||
public:
|
||||
/** Creates an empty channel set.
|
||||
You can call addChannel to add channels to the set.
|
||||
*/
|
||||
AudioChannelSet() = default;
|
||||
|
||||
/** Creates a zero-channel set which can be used to indicate that a
|
||||
bus is disabled. */
|
||||
static AudioChannelSet JUCE_CALLTYPE disabled();
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a one-channel mono set (centre).
|
||||
|
||||
Is equivalent to: kMonoAAX (VST), AAX_eStemFormat_Mono (AAX), kAudioChannelLayoutTag_Mono (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE mono();
|
||||
|
||||
|
||||
/** Creates a set containing a stereo set (left, right).
|
||||
|
||||
Is equivalent to: kStereo (VST), AAX_eStemFormat_Stereo (AAX), kAudioChannelLayoutTag_Stereo (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE stereo();
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a set containing an LCR set (left, right, centre).
|
||||
|
||||
Is equivalent to: k30Cine (VST), AAX_eStemFormat_LCR (AAX), kAudioChannelLayoutTag_MPEG_3_0_A (CoreAudio)
|
||||
|
||||
This format is referred to as "LRC" in Cubase.
|
||||
This format is referred to as "LCR" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE createLCR();
|
||||
|
||||
|
||||
/** Creates a set containing an LRS set (left, right, surround).
|
||||
|
||||
Is equivalent to: k30Music (VST), n/a (AAX), kAudioChannelLayoutTag_ITU_2_1 (CoreAudio)
|
||||
|
||||
This format is referred to as "LRS" in Cubase.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE createLRS();
|
||||
|
||||
|
||||
/** Creates a set containing an LCRS set (left, right, centre, surround).
|
||||
|
||||
Is equivalent to: k40Cine (VST), AAX_eStemFormat_LCRS (AAX), kAudioChannelLayoutTag_MPEG_4_0_A (CoreAudio)
|
||||
|
||||
This format is referred to as "LCRS (Pro Logic)" in Logic Pro.
|
||||
This format is referred to as "LRCS" in Cubase.
|
||||
This format is referred to as "LCRS" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE createLCRS();
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a set for a 5.0 surround setup (left, right, centre, leftSurround, rightSurround).
|
||||
|
||||
Is equivalent to: k50 (VST), AAX_eStemFormat_5_0 (AAX), kAudioChannelLayoutTag_MPEG_5_0_A (CoreAudio)
|
||||
|
||||
This format is referred to as "5.0" in Cubase.
|
||||
This format is referred to as "5.0" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point0();
|
||||
|
||||
|
||||
/** Creates a set for a 5.1 surround setup (left, right, centre, leftSurround, rightSurround, LFE).
|
||||
|
||||
Is equivalent to: k51 (VST), AAX_eStemFormat_5_1 (AAX), kAudioChannelLayoutTag_MPEG_5_1_A (CoreAudio)
|
||||
|
||||
This format is referred to as "5.1 (ITU 775)" in Logic Pro.
|
||||
This format is referred to as "5.1" in Cubase.
|
||||
This format is referred to as "5.1" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point1();
|
||||
|
||||
|
||||
/** Creates a set for a 6.0 Cine surround setup (left, right, centre, leftSurround, rightSurround, centreSurround).
|
||||
|
||||
Is equivalent to: k60Cine (VST), AAX_eStemFormat_6_0 (AAX), kAudioChannelLayoutTag_AudioUnit_6_0 (CoreAudio)
|
||||
|
||||
Logic Pro incorrectly uses this for the surround format labeled "6.1 (ES/EX)".
|
||||
This format is referred to as "6.0 Cine" in Cubase.
|
||||
This format is referred to as "6.0" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create6point0();
|
||||
|
||||
|
||||
/** Creates a set for a 6.1 Cine surround setup (left, right, centre, leftSurround, rightSurround, centreSurround, LFE).
|
||||
|
||||
Is equivalent to: k61Cine (VST), AAX_eStemFormat_6_1 (AAX), kAudioChannelLayoutTag_MPEG_6_1_A (CoreAudio)
|
||||
|
||||
This format is referred to as "6.1" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create6point1();
|
||||
|
||||
|
||||
/** Creates a set for a 6.0 Music surround setup (left, right, leftSurround, rightSurround, leftSurroundSide, rightSurroundSide).
|
||||
|
||||
Is equivalent to: k60Music (VST), n/a (AAX), kAudioChannelLayoutTag_DTS_6_0_A (CoreAudio)
|
||||
|
||||
This format is referred to as "6.0 Music" in Cubase.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create6point0Music();
|
||||
|
||||
|
||||
/** Creates a set for a 6.0 Music surround setup (left, right, leftSurround, rightSurround, leftSurroundSide, rightSurroundSide, LFE).
|
||||
|
||||
Is equivalent to: k61Music (VST), n/a (AAX), kAudioChannelLayoutTag_DTS_6_1_A (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create6point1Music();
|
||||
|
||||
|
||||
/** Creates a set for a DTS 7.0 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear).
|
||||
|
||||
Is equivalent to: k70Music (VST), AAX_eStemFormat_7_0_DTS (AAX), kAudioChannelLayoutTag_AudioUnit_7_0 (CoreAudio)
|
||||
|
||||
This format is referred to as "7.0" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point0();
|
||||
|
||||
|
||||
/** Creates a set for a SDDS 7.0 surround setup (left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre).
|
||||
|
||||
Is equivalent to: k70Cine (VST), AAX_eStemFormat_7_0_SDDS (AAX), kAudioChannelLayoutTag_AudioUnit_7_0_Front (CoreAudio)
|
||||
|
||||
This format is referred to as "7.0 SDDS" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point0SDDS();
|
||||
|
||||
|
||||
/** Creates a set for a DTS 7.1 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, LFE).
|
||||
|
||||
Is equivalent to: k71CineSideFill (VST), AAX_eStemFormat_7_1_DTS (AAX), kAudioChannelLayoutTag_MPEG_7_1_C/kAudioChannelLayoutTag_ITU_3_4_1 (CoreAudio)
|
||||
|
||||
This format is referred to as "7.1 (3/4.1)" in Logic Pro.
|
||||
This format is referred to as "7.1" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point1();
|
||||
|
||||
|
||||
/** Creates a set for a 7.1 surround setup (left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre, LFE).
|
||||
|
||||
Is equivalent to: k71Cine (VST), AAX_eStemFormat_7_1_SDDS (AAX), kAudioChannelLayoutTag_MPEG_7_1_A (CoreAudio)
|
||||
|
||||
This format is referred to as "7.1 (SDDS)" in Logic Pro.
|
||||
This format is referred to as "7.1 SDDS" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point1SDDS();
|
||||
|
||||
/** Creates a set for a 5.0.2 surround setup (left, right, centre, leftSurround, rightSurround, topSideLeft, topSideRight).
|
||||
|
||||
Is equivalent to: AAX_eStemFormat_5_0_2 (AAX).
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point0point2();
|
||||
|
||||
/** Creates a set for a 5.1.2 surround setup (left, right, centre, LFE, leftSurround, rightSurround, topSideLeft, topSideRight).
|
||||
|
||||
Is equivalent to: kAudioChannelLayoutTag_Atmos_5_1_2 (CoreAudio).
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point1point2();
|
||||
|
||||
/** Creates a set for a 5.0.4 surround setup (left, right, centre, leftSurround, rightSurround, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: AAX_eStemFormat_5_0_4 (AAX).
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point0point4();
|
||||
|
||||
/** Creates a set for a 5.1.4 surround setup (left, right, centre, LFE, leftSurround, rightSurround, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: kAudioChannelLayoutTag_Atmos_5_1_4 (CoreAudio).
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create5point1point4();
|
||||
|
||||
/** Creates a set for Dolby Atmos 7.0.2 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topSideLeft, topSideRight).
|
||||
|
||||
Is equivalent to: n/a (VST), AAX_eStemFormat_7_0_2 (AAX), n/a (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point0point2();
|
||||
|
||||
/** Creates a set for Dolby Atmos 7.1.2 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, LFE, topSideLeft, topSideRight).
|
||||
|
||||
Is equivalent to: k71_2 (VST), AAX_eStemFormat_7_1_2 (AAX), kAudioChannelLayoutTag_Atmos_7_1_2 (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point1point2();
|
||||
|
||||
/** Creates a set for Dolby Atmos 7.0.4 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: n/a (VST), n/a (AAX), n/a (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point0point4();
|
||||
|
||||
/** Creates a set for Dolby Atmos 7.1.4 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, LFE, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: k71_4 (VST), n/a (AAX), kAudioChannelLayoutTag_Atmos_7_1_4 (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point1point4();
|
||||
|
||||
/** Creates a set for 7.0.6 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: AAX_eStemFormat_7_0_6 (AAX).
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point0point6();
|
||||
|
||||
/** Creates a set for Dolby Atmos 7.1.6 surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, LFE, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: k71_6 (VST), n/a (AAX), n/a (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create7point1point6();
|
||||
|
||||
/** Creates a set for a 9.0.4 Atmos surround setup (left, right, centre, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: k90_4_W (VST3), AAX_eStemFormat_9_0_4 (AAX).
|
||||
|
||||
@see create9point0point4ITU()
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point0point4();
|
||||
|
||||
/** Creates a set for a 9.1.4 Atmos surround setup (left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: k91_4_W (VST3), AAX_eStemFormat_9_1_4 (AAX).
|
||||
|
||||
@see create9point1point4ITU()
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point1point4();
|
||||
|
||||
/** Creates a set for a 9.0.6 Atmos surround setup (left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight).
|
||||
|
||||
Is equivalent to: k90_6_W (VST3), AAX_eStemFormat_9_0_6 (AAX).
|
||||
|
||||
@see create9point0point6ITU()
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point0point6();
|
||||
|
||||
/** Creates a set for a 9.1.6 Atmos surround setup (left, right, centre, LFE, leftSurroundSide, rightSurroundSide, leftSurroundRear, rightSurroundRear, wideLeft, wideRight, topFrontLeft, topFrontRight, topSideLeft, topSideRight, topRearLeft, topRearRight).
|
||||
|
||||
Older versions of the VST3 SDK only supported ITU versions of the 9.0.4, 9.1.4, 9.0.6, and
|
||||
9.1.6 layouts, which have the front-channel ordering "L Lc C Rc R".
|
||||
To maintain the correct relative channel ordering, JUCE would perform the following mapping:
|
||||
L -> wideLeft, Lc -> left, Rc -> right, R -> wideRight
|
||||
|
||||
The version of the VST3 SDK bundled with JUCE now supports Atmos versions of the above
|
||||
layouts, which have the front-channel ordering "Lw L C R Rw". This order matches the
|
||||
JUCE ordering, so no remapping is required.
|
||||
|
||||
create9point0point4(), create9point1point4(), create9point0point6(), and
|
||||
create9point1point6() now correspond to the VST3 k90_4_W, k91_4_W, k90_6_W, and k91_6_W
|
||||
Atmos layouts respectively.
|
||||
|
||||
If you need to support the old ITU layouts, use create9point0point4ITU(),
|
||||
create9point1point4ITU(), create9point0point6ITU(), and create9point1point6ITU() instead.
|
||||
|
||||
Is equivalent to: k91_6_W (VST3), kAudioChannelLayoutTag_Atmos_9_1_6 (CoreAudio).
|
||||
|
||||
@see create9point1point6ITU()
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point1point6();
|
||||
|
||||
/** Creates a set for a 9.0.4 ITU surround setup:
|
||||
left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point0point4ITU();
|
||||
|
||||
/** Creates a set for a 9.1.4 ITU surround setup.
|
||||
left, right, centre, LFE, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point1point4ITU();
|
||||
|
||||
/** Creates a set for a 9.0.6 ITU surround setup.
|
||||
left, right, centre, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight, topSideLeft, topSideRight
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point0point6ITU();
|
||||
|
||||
/** Creates a set for a 9.1.6 ITU surround setup.
|
||||
left, right, centre, LFE, leftSurround, rightSurround, leftCentre, rightCentre, leftSurroundSide, rightSurroundSide, topFrontLeft, topFrontRight, topRearLeft, topRearRight, topSideLeft, topSideRight
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE create9point1point6ITU();
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a set for quadraphonic surround setup (left, right, leftSurround, rightSurround)
|
||||
|
||||
Is equivalent to: k40Music (VST), AAX_eStemFormat_Quad (AAX), kAudioChannelLayoutTag_Quadraphonic (CoreAudio)
|
||||
|
||||
This format is referred to as "Quadraphonic" in Logic Pro.
|
||||
This format is referred to as "Quadro" in Cubase.
|
||||
This format is referred to as "Quad" in Pro Tools.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE quadraphonic();
|
||||
|
||||
|
||||
/** Creates a set for pentagonal surround setup (left, right, centre, leftSurroundRear, rightSurroundRear).
|
||||
|
||||
Is equivalent to: n/a (VST), n/a (AAX), kAudioChannelLayoutTag_Pentagonal (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE pentagonal();
|
||||
|
||||
|
||||
/** Creates a set for hexagonal surround setup (left, right, leftSurroundRear, rightSurroundRear, centre, surroundCentre).
|
||||
|
||||
Is equivalent to: n/a (VST), n/a (AAX), kAudioChannelLayoutTag_Hexagonal (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE hexagonal();
|
||||
|
||||
|
||||
/** Creates a set for octagonal surround setup (left, right, leftSurround, rightSurround, centre, centreSurround, wideLeft, wideRight).
|
||||
|
||||
Is equivalent to: n/a (VST), n/a (AAX), kAudioChannelLayoutTag_Octagonal (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE octagonal();
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a set for ACN, SN3D normalised ambisonic surround setups with a given order.
|
||||
|
||||
Is equivalent to: kAmbiXXXOrderACN (VST), AAX_eStemFormat_Ambi_XXX_ACN (AAX), kAudioChannelLayoutTag_HOA_ACN_SN3D (CoreAudio)
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE ambisonic (int order = 1);
|
||||
|
||||
/** Returns the order of the ambisonic layout represented by this AudioChannelSet. If the
|
||||
AudioChannelSet is not an ambisonic layout, then this method will return -1.
|
||||
*/
|
||||
int getAmbisonicOrder() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a set of untyped discrete channels. */
|
||||
static AudioChannelSet JUCE_CALLTYPE discreteChannels (int numChannels);
|
||||
|
||||
/** Create a canonical channel set for a given number of channels.
|
||||
For example, numChannels = 1 will return mono, numChannels = 2 will return stereo, etc. */
|
||||
static AudioChannelSet JUCE_CALLTYPE canonicalChannelSet (int numChannels);
|
||||
|
||||
/** Create a channel set for a given number of channels which is non-discrete.
|
||||
If numChannels is larger than the number of channels of the surround format
|
||||
with the maximum amount of channels (currently 7.1 Surround), then this
|
||||
function returns an empty set.*/
|
||||
static AudioChannelSet JUCE_CALLTYPE namedChannelSet (int numChannels);
|
||||
|
||||
/** Return an array of channel sets which have a given number of channels */
|
||||
static Array<AudioChannelSet> JUCE_CALLTYPE channelSetsWithNumberOfChannels (int numChannels);
|
||||
|
||||
//==============================================================================
|
||||
/** Represents different audio channel types. */
|
||||
enum ChannelType
|
||||
{
|
||||
unknown = 0, /**< Unknown channel type. */
|
||||
|
||||
//==============================================================================
|
||||
left = 1, /**< L channel. */
|
||||
right = 2, /**< R channel. */
|
||||
centre = 3, /**< C channel. (Sometimes M for mono) */
|
||||
|
||||
//==============================================================================
|
||||
LFE = 4, /**< LFE channel. */
|
||||
leftSurround = 5, /**< Ls channel. */
|
||||
rightSurround = 6, /**< Rs channel. */
|
||||
leftCentre = 7, /**< Lc (AAX/VST), Lc used as Lss in AU for most layouts. */
|
||||
rightCentre = 8, /**< Rc (AAX/VST), Rc used as Rss in AU for most layouts. */
|
||||
centreSurround = 9, /**< Cs/S channel. */
|
||||
surround = centreSurround, /**< Same as Centre Surround channel. */
|
||||
leftSurroundSide = 10, /**< Lss (AXX), Side Left "Sl" (VST), Left Centre "LC" (AU) channel. */
|
||||
rightSurroundSide = 11, /**< Rss (AXX), Side right "Sr" (VST), Right Centre "Rc" (AU) channel. */
|
||||
topMiddle = 12, /**< Top Middle channel. */
|
||||
topFrontLeft = 13, /**< Top Front Left channel. */
|
||||
topFrontCentre = 14, /**< Top Front Centre channel. */
|
||||
topFrontRight = 15, /**< Top Front Right channel. */
|
||||
topRearLeft = 16, /**< Top Rear Left channel. */
|
||||
topRearCentre = 17, /**< Top Rear Centre channel. */
|
||||
topRearRight = 18, /**< Top Rear Right channel. */
|
||||
LFE2 = 19, /**< Second LFE channel. */
|
||||
leftSurroundRear = 20, /**< Lsr (AAX), Lcs (VST), Rls (AU) channel. */
|
||||
rightSurroundRear = 21, /**< Rsr (AAX), Rcs (VST), Rrs (AU) channel. */
|
||||
wideLeft = 22, /**< Wide Left channel. */
|
||||
wideRight = 23, /**< Wide Right channel. */
|
||||
|
||||
//==============================================================================
|
||||
// Used by Dolby Atmos 7.0.2 and 7.1.2
|
||||
topSideLeft = 28, /**< Lts (AAX), Tsl (VST), Ltm (AU) channel for Dolby Atmos. */
|
||||
topSideRight = 29, /**< Rts (AAX), Tsr (VST), Rtm (AU) channel for Dolby Atmos. */
|
||||
|
||||
//==============================================================================
|
||||
// Ambisonic ACN formats - all channels are SN3D normalised
|
||||
|
||||
// zero-th and first-order ambisonic ACN
|
||||
ambisonicACN0 = 24, /**< Zero-th ambisonic channel number 0. */
|
||||
ambisonicACN1 = 25, /**< First-order ambisonic channel number 1. */
|
||||
ambisonicACN2 = 26, /**< First-order ambisonic channel number 2. */
|
||||
ambisonicACN3 = 27, /**< First-order ambisonic channel number 3. */
|
||||
|
||||
// second-order ambisonic
|
||||
ambisonicACN4 = 30, /**< Second-order ambisonic channel number 4. */
|
||||
ambisonicACN5 = 31, /**< Second-order ambisonic channel number 5. */
|
||||
ambisonicACN6 = 32, /**< Second-order ambisonic channel number 6. */
|
||||
ambisonicACN7 = 33, /**< Second-order ambisonic channel number 7. */
|
||||
ambisonicACN8 = 34, /**< Second-order ambisonic channel number 8. */
|
||||
|
||||
// third-order ambisonic
|
||||
ambisonicACN9 = 35, /**< Third-order ambisonic channel number 9. */
|
||||
ambisonicACN10 = 36, /**< Third-order ambisonic channel number 10. */
|
||||
ambisonicACN11 = 37, /**< Third-order ambisonic channel number 11. */
|
||||
ambisonicACN12 = 38, /**< Third-order ambisonic channel number 12. */
|
||||
ambisonicACN13 = 39, /**< Third-order ambisonic channel number 13. */
|
||||
ambisonicACN14 = 40, /**< Third-order ambisonic channel number 14. */
|
||||
ambisonicACN15 = 41, /**< Third-order ambisonic channel number 15. */
|
||||
|
||||
// fourth-order ambisonic
|
||||
ambisonicACN16 = 42, /**< Fourth-order ambisonic channel number 16. */
|
||||
ambisonicACN17 = 43, /**< Fourth-order ambisonic channel number 17. */
|
||||
ambisonicACN18 = 44, /**< Fourth-order ambisonic channel number 18. */
|
||||
ambisonicACN19 = 45, /**< Fourth-order ambisonic channel number 19. */
|
||||
ambisonicACN20 = 46, /**< Fourth-order ambisonic channel number 20. */
|
||||
ambisonicACN21 = 47, /**< Fourth-order ambisonic channel number 21. */
|
||||
ambisonicACN22 = 48, /**< Fourth-order ambisonic channel number 22. */
|
||||
ambisonicACN23 = 49, /**< Fourth-order ambisonic channel number 23. */
|
||||
ambisonicACN24 = 50, /**< Fourth-order ambisonic channel number 24. */
|
||||
|
||||
// fifth-order ambisonic
|
||||
ambisonicACN25 = 51, /**< Fifth-order ambisonic channel number 25. */
|
||||
ambisonicACN26 = 52, /**< Fifth-order ambisonic channel number 26. */
|
||||
ambisonicACN27 = 53, /**< Fifth-order ambisonic channel number 27. */
|
||||
ambisonicACN28 = 54, /**< Fifth-order ambisonic channel number 28. */
|
||||
ambisonicACN29 = 55, /**< Fifth-order ambisonic channel number 29. */
|
||||
ambisonicACN30 = 56, /**< Fifth-order ambisonic channel number 30. */
|
||||
ambisonicACN31 = 57, /**< Fifth-order ambisonic channel number 31. */
|
||||
ambisonicACN32 = 58, /**< Fifth-order ambisonic channel number 32. */
|
||||
ambisonicACN33 = 59, /**< Fifth-order ambisonic channel number 33. */
|
||||
ambisonicACN34 = 60, /**< Fifth-order ambisonic channel number 34. */
|
||||
ambisonicACN35 = 61, /**< Fifth-order ambisonic channel number 35. */
|
||||
|
||||
//==============================================================================
|
||||
ambisonicW = ambisonicACN0, /**< Same as zero-th ambisonic channel number 0. */
|
||||
ambisonicX = ambisonicACN3, /**< Same as first-order ambisonic channel number 3. */
|
||||
ambisonicY = ambisonicACN1, /**< Same as first-order ambisonic channel number 1. */
|
||||
ambisonicZ = ambisonicACN2, /**< Same as first-order ambisonic channel number 2. */
|
||||
|
||||
//==============================================================================
|
||||
bottomFrontLeft = 62, /**< Bottom Front Left (Bfl) */
|
||||
bottomFrontCentre = 63, /**< Bottom Front Centre (Bfc) */
|
||||
bottomFrontRight = 64, /**< Bottom Front Right (Bfr) */
|
||||
|
||||
proximityLeft = 65, /**< Proximity Left (Pl) */
|
||||
proximityRight = 66, /**< Proximity Right (Pr) */
|
||||
|
||||
bottomSideLeft = 67, /**< Bottom Side Left (Bsl) */
|
||||
bottomSideRight = 68, /**< Bottom Side Right (Bsr) */
|
||||
bottomRearLeft = 69, /**< Bottom Rear Left (Brl) */
|
||||
bottomRearCentre = 70, /**< Bottom Rear Center (Brc) */
|
||||
bottomRearRight = 71, /**< Bottom Rear Right (Brr) */
|
||||
|
||||
//==============================================================================
|
||||
|
||||
// sixth-order ambisonic
|
||||
ambisonicACN36 = 72, /**< Sixth-order ambisonic channel number 36. */
|
||||
ambisonicACN37 = 73, /**< Sixth-order ambisonic channel number 37. */
|
||||
ambisonicACN38 = 74, /**< Sixth-order ambisonic channel number 38. */
|
||||
ambisonicACN39 = 75, /**< Sixth-order ambisonic channel number 39. */
|
||||
ambisonicACN40 = 76, /**< Sixth-order ambisonic channel number 40. */
|
||||
ambisonicACN41 = 77, /**< Sixth-order ambisonic channel number 41. */
|
||||
ambisonicACN42 = 78, /**< Sixth-order ambisonic channel number 42. */
|
||||
ambisonicACN43 = 79, /**< Sixth-order ambisonic channel number 43. */
|
||||
ambisonicACN44 = 80, /**< Sixth-order ambisonic channel number 44. */
|
||||
ambisonicACN45 = 81, /**< Sixth-order ambisonic channel number 45. */
|
||||
ambisonicACN46 = 82, /**< Sixth-order ambisonic channel number 46. */
|
||||
ambisonicACN47 = 83, /**< Sixth-order ambisonic channel number 47. */
|
||||
ambisonicACN48 = 84, /**< Sixth-order ambisonic channel number 48. */
|
||||
|
||||
// seventh-order ambisonic
|
||||
ambisonicACN49 = 85, /**< Seventh-order ambisonic channel number 49. */
|
||||
ambisonicACN50 = 86, /**< Seventh-order ambisonic channel number 50. */
|
||||
ambisonicACN51 = 87, /**< Seventh-order ambisonic channel number 51. */
|
||||
ambisonicACN52 = 88, /**< Seventh-order ambisonic channel number 52. */
|
||||
ambisonicACN53 = 89, /**< Seventh-order ambisonic channel number 53. */
|
||||
ambisonicACN54 = 90, /**< Seventh-order ambisonic channel number 54. */
|
||||
ambisonicACN55 = 91, /**< Seventh-order ambisonic channel number 55. */
|
||||
ambisonicACN56 = 92, /**< Seventh-order ambisonic channel number 56. */
|
||||
ambisonicACN57 = 93, /**< Seventh-order ambisonic channel number 57. */
|
||||
ambisonicACN58 = 94, /**< Seventh-order ambisonic channel number 58. */
|
||||
ambisonicACN59 = 95, /**< Seventh-order ambisonic channel number 59. */
|
||||
ambisonicACN60 = 96, /**< Seventh-order ambisonic channel number 60. */
|
||||
ambisonicACN61 = 97, /**< Seventh-order ambisonic channel number 61. */
|
||||
ambisonicACN62 = 98, /**< Seventh-order ambisonic channel number 62. */
|
||||
ambisonicACN63 = 99, /**< Seventh-order ambisonic channel number 63. */
|
||||
|
||||
//==============================================================================
|
||||
discreteChannel0 = 128 /**< Non-typed individual channels are indexed upwards from this value. */
|
||||
};
|
||||
|
||||
/** Returns the name of a given channel type. For example, this method may return "Surround Left". */
|
||||
static String JUCE_CALLTYPE getChannelTypeName (ChannelType);
|
||||
|
||||
/** Returns the abbreviated name of a channel type. For example, this method may return "Ls". */
|
||||
static String JUCE_CALLTYPE getAbbreviatedChannelTypeName (ChannelType);
|
||||
|
||||
/** Returns the channel type from an abbreviated name. */
|
||||
static ChannelType JUCE_CALLTYPE getChannelTypeFromAbbreviation (const String& abbreviation);
|
||||
|
||||
//==============================================================================
|
||||
enum
|
||||
{
|
||||
maxChannelsOfNamedLayout = 64
|
||||
};
|
||||
|
||||
/** Adds a channel to the set. */
|
||||
void addChannel (ChannelType newChannelType);
|
||||
|
||||
/** Removes a channel from the set. */
|
||||
void removeChannel (ChannelType newChannelType);
|
||||
|
||||
/** Returns the number of channels in the set. */
|
||||
int size() const noexcept;
|
||||
|
||||
/** Returns true if there are no channels in the set. */
|
||||
bool isDisabled() const noexcept { return size() == 0; }
|
||||
|
||||
/** Returns an array of all the types in this channel set. */
|
||||
Array<ChannelType> getChannelTypes() const;
|
||||
|
||||
/** Returns the type of one of the channels in the set, by index. */
|
||||
ChannelType getTypeOfChannel (int channelIndex) const noexcept;
|
||||
|
||||
/** Returns the index for a particular channel-type.
|
||||
Will return -1 if the this set does not contain a channel of this type. */
|
||||
int getChannelIndexForType (ChannelType type) const noexcept;
|
||||
|
||||
/** Returns a string containing a whitespace-separated list of speaker types
|
||||
corresponding to each channel. For example in a 5.1 arrangement,
|
||||
the string may be "L R C Lfe Ls Rs". If the speaker arrangement is unknown,
|
||||
the returned string will be empty.*/
|
||||
String getSpeakerArrangementAsString() const;
|
||||
|
||||
/** Returns an AudioChannelSet from a string returned by getSpeakerArrangementAsString
|
||||
|
||||
@see getSpeakerArrangementAsString */
|
||||
static AudioChannelSet fromAbbreviatedString (const String& set);
|
||||
|
||||
/** Returns the description of the current layout. For example, this method may return
|
||||
"Quadraphonic". Note that the returned string may not be unique. */
|
||||
String getDescription() const;
|
||||
|
||||
/** Returns if this is a channel layout made-up of discrete channels. */
|
||||
bool isDiscreteLayout() const noexcept;
|
||||
|
||||
/** Intersect two channel layouts. */
|
||||
void intersect (const AudioChannelSet& other) { channels &= other.channels; }
|
||||
|
||||
/** Creates a channel set for a list of channel types. This function will assert
|
||||
if you supply a duplicate channel.
|
||||
|
||||
Note that this method ignores the order in which the channels are given, i.e.
|
||||
two arrays with the same elements but in a different order will still result
|
||||
in the same channel set.
|
||||
*/
|
||||
static AudioChannelSet JUCE_CALLTYPE channelSetWithChannels (const Array<ChannelType>&);
|
||||
|
||||
//==============================================================================
|
||||
// Conversion between wave and juce channel layout identifiers
|
||||
|
||||
/** Create an AudioChannelSet from a WAVEFORMATEXTENSIBLE channelMask (typically used
|
||||
in .wav files). */
|
||||
static AudioChannelSet JUCE_CALLTYPE fromWaveChannelMask (int32 dwChannelMask);
|
||||
|
||||
/** Returns a WAVEFORMATEXTENSIBLE channelMask representation (typically used in .wav
|
||||
files) of the receiver.
|
||||
|
||||
Returns -1 if the receiver cannot be represented in a WAVEFORMATEXTENSIBLE channelMask
|
||||
representation.
|
||||
*/
|
||||
int32 getWaveChannelMask() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the ambisonic order that includes exactly numChannels, or -1 if no
|
||||
supported ambisonic order contains exactly numChannels.
|
||||
*/
|
||||
static int getAmbisonicOrderForNumChannels (int numChannels, int maxOrderToCheck = 7);
|
||||
|
||||
//==============================================================================
|
||||
bool operator== (const AudioChannelSet&) const noexcept;
|
||||
bool operator!= (const AudioChannelSet&) const noexcept;
|
||||
bool operator< (const AudioChannelSet&) const noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
BigInteger channels;
|
||||
|
||||
//==============================================================================
|
||||
explicit AudioChannelSet (uint32);
|
||||
explicit AudioChannelSet (const std::initializer_list<ChannelType>&);
|
||||
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,645 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<uint16*> (intData) = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
*unalignedPointerCast<uint16*> (intData) = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<uint16*> (intData) = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
*unalignedPointerCast<uint16*> (intData) = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fffff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
ByteOrder::littleEndian24BitToChars (roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
ByteOrder::littleEndian24BitToChars (roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fffff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
ByteOrder::bigEndian24BitToChars (roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
ByteOrder::bigEndian24BitToChars (roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fffffff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<uint32*> (intData) = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
*unalignedPointerCast<uint32*> (intData) = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
auto maxVal = (double) 0x7fffffff;
|
||||
auto intData = static_cast<char*> (dest);
|
||||
|
||||
if (dest != (void*) source || destBytesPerSample <= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<uint32*> (intData) = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
intData += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += destBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= destBytesPerSample;
|
||||
*unalignedPointerCast<uint32*> (intData) = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
|
||||
|
||||
char* d = static_cast<char*> (dest);
|
||||
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<float*> (d) = source[i];
|
||||
|
||||
#if JUCE_BIG_ENDIAN
|
||||
*unalignedPointerCast<uint32*> (d) = ByteOrder::swap (*unalignedPointerCast<uint32*> (d));
|
||||
#endif
|
||||
|
||||
d += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample)
|
||||
{
|
||||
jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
|
||||
|
||||
auto d = static_cast<char*> (dest);
|
||||
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
*unalignedPointerCast<float*> (d) = source[i];
|
||||
|
||||
#if JUCE_LITTLE_ENDIAN
|
||||
*unalignedPointerCast<uint32*> (d) = ByteOrder::swap (*unalignedPointerCast<uint32*> (d));
|
||||
#endif
|
||||
|
||||
d += destBytesPerSample;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void AudioDataConverters::convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / 0x7fff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*unalignedPointerCast<const uint16*> (intData));
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*unalignedPointerCast<const uint16*> (intData));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / 0x7fff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*unalignedPointerCast<const uint16*> (intData));
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*unalignedPointerCast<const uint16*> (intData));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / 0x7fffff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / 0x7fffff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / (float) 0x7fffffff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (float) ByteOrder::swapIfBigEndian (*unalignedPointerCast<const uint32*> (intData));
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (float) ByteOrder::swapIfBigEndian (*unalignedPointerCast<const uint32*> (intData));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
const float scale = 1.0f / (float) 0x7fffffff;
|
||||
auto intData = static_cast<const char*> (source);
|
||||
|
||||
if (source != (void*) dest || srcBytesPerSample >= 4)
|
||||
{
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = scale * (float) ByteOrder::swapIfLittleEndian (*unalignedPointerCast<const uint32*> (intData));
|
||||
intData += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
intData += srcBytesPerSample * numSamples;
|
||||
|
||||
for (int i = numSamples; --i >= 0;)
|
||||
{
|
||||
intData -= srcBytesPerSample;
|
||||
dest[i] = scale * (float) ByteOrder::swapIfLittleEndian (*unalignedPointerCast<const uint32*> (intData));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
auto s = static_cast<const char*> (source);
|
||||
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = *unalignedPointerCast<const float*> (s);
|
||||
|
||||
#if JUCE_BIG_ENDIAN
|
||||
auto d = unalignedPointerCast<uint32*> (dest + i);
|
||||
*d = ByteOrder::swap (*d);
|
||||
#endif
|
||||
|
||||
s += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample)
|
||||
{
|
||||
auto s = static_cast<const char*> (source);
|
||||
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
dest[i] = *unalignedPointerCast<const float*> (s);
|
||||
|
||||
#if JUCE_LITTLE_ENDIAN
|
||||
auto d = unalignedPointerCast<uint32*> (dest + i);
|
||||
*d = ByteOrder::swap (*d);
|
||||
#endif
|
||||
|
||||
s += srcBytesPerSample;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
void AudioDataConverters::convertFloatToFormat (DataFormat destFormat, const float* source, void* dest, int numSamples)
|
||||
{
|
||||
switch (destFormat)
|
||||
{
|
||||
case int16LE: convertFloatToInt16LE (source, dest, numSamples); break;
|
||||
case int16BE: convertFloatToInt16BE (source, dest, numSamples); break;
|
||||
case int24LE: convertFloatToInt24LE (source, dest, numSamples); break;
|
||||
case int24BE: convertFloatToInt24BE (source, dest, numSamples); break;
|
||||
case int32LE: convertFloatToInt32LE (source, dest, numSamples); break;
|
||||
case int32BE: convertFloatToInt32BE (source, dest, numSamples); break;
|
||||
case float32LE: convertFloatToFloat32LE (source, dest, numSamples); break;
|
||||
case float32BE: convertFloatToFloat32BE (source, dest, numSamples); break;
|
||||
default: jassertfalse; break;
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDataConverters::convertFormatToFloat (DataFormat sourceFormat, const void* source, float* dest, int numSamples)
|
||||
{
|
||||
switch (sourceFormat)
|
||||
{
|
||||
case int16LE: convertInt16LEToFloat (source, dest, numSamples); break;
|
||||
case int16BE: convertInt16BEToFloat (source, dest, numSamples); break;
|
||||
case int24LE: convertInt24LEToFloat (source, dest, numSamples); break;
|
||||
case int24BE: convertInt24BEToFloat (source, dest, numSamples); break;
|
||||
case int32LE: convertInt32LEToFloat (source, dest, numSamples); break;
|
||||
case int32BE: convertInt32BEToFloat (source, dest, numSamples); break;
|
||||
case float32LE: convertFloat32LEToFloat (source, dest, numSamples); break;
|
||||
case float32BE: convertFloat32BEToFloat (source, dest, numSamples); break;
|
||||
default: jassertfalse; break;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void AudioDataConverters::interleaveSamples (const float** source, float* dest, int numSamples, int numChannels)
|
||||
{
|
||||
using Format = AudioData::Format<AudioData::Float32, AudioData::NativeEndian>;
|
||||
|
||||
AudioData::interleaveSamples (AudioData::NonInterleavedSource<Format> { source, numChannels },
|
||||
AudioData::InterleavedDest<Format> { dest, numChannels },
|
||||
numSamples);
|
||||
}
|
||||
|
||||
void AudioDataConverters::deinterleaveSamples (const float* source, float** dest, int numSamples, int numChannels)
|
||||
{
|
||||
using Format = AudioData::Format<AudioData::Float32, AudioData::NativeEndian>;
|
||||
|
||||
AudioData::deinterleaveSamples (AudioData::InterleavedSource<Format> { source, numChannels },
|
||||
AudioData::NonInterleavedDest<Format> { dest, numChannels },
|
||||
numSamples);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class AudioConversionTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
AudioConversionTests()
|
||||
: UnitTest ("Audio data conversion", UnitTestCategories::audio)
|
||||
{}
|
||||
|
||||
template <class F1, class E1, class F2, class E2>
|
||||
struct Test5
|
||||
{
|
||||
static void test (UnitTest& unitTest, Random& r)
|
||||
{
|
||||
test (unitTest, false, r);
|
||||
test (unitTest, true, r);
|
||||
}
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6262)
|
||||
static void test (UnitTest& unitTest, bool inPlace, Random& r)
|
||||
{
|
||||
const int numSamples = 2048;
|
||||
int32 original [(size_t) numSamples],
|
||||
converted[(size_t) numSamples],
|
||||
reversed [(size_t) numSamples];
|
||||
|
||||
{
|
||||
AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
|
||||
bool clippingFailed = false;
|
||||
|
||||
for (int i = 0; i < numSamples / 2; ++i)
|
||||
{
|
||||
d.setAsFloat (r.nextFloat() * 2.2f - 1.1f);
|
||||
|
||||
if (! d.isFloatingPoint())
|
||||
clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
|
||||
|
||||
++d;
|
||||
d.setAsInt32 (r.nextInt());
|
||||
++d;
|
||||
}
|
||||
|
||||
unitTest.expect (! clippingFailed);
|
||||
}
|
||||
|
||||
// convert data from the source to dest format...
|
||||
std::unique_ptr<AudioData::Converter> conv (new AudioData::ConverterInstance<AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
|
||||
AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst>>());
|
||||
conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
|
||||
|
||||
// ...and back again
|
||||
conv.reset (new AudioData::ConverterInstance<AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
|
||||
AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst>>());
|
||||
if (! inPlace)
|
||||
zeromem (reversed, sizeof (reversed));
|
||||
|
||||
conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
|
||||
|
||||
{
|
||||
int biggestDiff = 0;
|
||||
AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
|
||||
AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
|
||||
|
||||
const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
|
||||
+ AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
|
||||
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
{
|
||||
biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
|
||||
++d1;
|
||||
++d2;
|
||||
}
|
||||
|
||||
unitTest.expect (biggestDiff <= errorMargin);
|
||||
}
|
||||
}
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
};
|
||||
|
||||
template <class F1, class E1, class FormatType>
|
||||
struct Test3
|
||||
{
|
||||
static void test (UnitTest& unitTest, Random& r)
|
||||
{
|
||||
Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest, r);
|
||||
Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest, r);
|
||||
}
|
||||
};
|
||||
|
||||
template <class FormatType, class Endianness>
|
||||
struct Test2
|
||||
{
|
||||
static void test (UnitTest& unitTest, Random& r)
|
||||
{
|
||||
Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest, r);
|
||||
Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest, r);
|
||||
Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest, r);
|
||||
Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest, r);
|
||||
Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest, r);
|
||||
Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest, r);
|
||||
}
|
||||
};
|
||||
|
||||
template <class FormatType>
|
||||
struct Test1
|
||||
{
|
||||
static void test (UnitTest& unitTest, Random& r)
|
||||
{
|
||||
Test2 <FormatType, AudioData::BigEndian>::test (unitTest, r);
|
||||
Test2 <FormatType, AudioData::LittleEndian>::test (unitTest, r);
|
||||
}
|
||||
};
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
auto r = getRandom();
|
||||
beginTest ("Round-trip conversion: Int8");
|
||||
Test1 <AudioData::Int8>::test (*this, r);
|
||||
beginTest ("Round-trip conversion: Int16");
|
||||
Test1 <AudioData::Int16>::test (*this, r);
|
||||
beginTest ("Round-trip conversion: Int24");
|
||||
Test1 <AudioData::Int24>::test (*this, r);
|
||||
beginTest ("Round-trip conversion: Int32");
|
||||
Test1 <AudioData::Int32>::test (*this, r);
|
||||
beginTest ("Round-trip conversion: Float32");
|
||||
Test1 <AudioData::Float32>::test (*this, r);
|
||||
|
||||
using Format = AudioData::Format<AudioData::Float32, AudioData::NativeEndian>;
|
||||
|
||||
beginTest ("Interleaving");
|
||||
{
|
||||
constexpr auto numChannels = 4;
|
||||
constexpr auto numSamples = 512;
|
||||
|
||||
AudioBuffer<float> sourceBuffer { numChannels, numSamples },
|
||||
destBuffer { 1, numChannels * numSamples };
|
||||
|
||||
for (int ch = 0; ch < numChannels; ++ch)
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
sourceBuffer.setSample (ch, i, r.nextFloat());
|
||||
|
||||
AudioData::interleaveSamples (AudioData::NonInterleavedSource<Format> { sourceBuffer.getArrayOfReadPointers(), numChannels },
|
||||
AudioData::InterleavedDest<Format> { destBuffer.getWritePointer (0), numChannels },
|
||||
numSamples);
|
||||
|
||||
for (int ch = 0; ch < numChannels; ++ch)
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
expectEquals (destBuffer.getSample (0, ch + (i * numChannels)), sourceBuffer.getSample (ch, i));
|
||||
}
|
||||
|
||||
beginTest ("Deinterleaving");
|
||||
{
|
||||
constexpr auto numChannels = 4;
|
||||
constexpr auto numSamples = 512;
|
||||
|
||||
AudioBuffer<float> sourceBuffer { 1, numChannels * numSamples },
|
||||
destBuffer { numChannels, numSamples };
|
||||
|
||||
for (int ch = 0; ch < numChannels; ++ch)
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
sourceBuffer.setSample (0, ch + (i * numChannels), r.nextFloat());
|
||||
|
||||
AudioData::deinterleaveSamples (AudioData::InterleavedSource<Format> { sourceBuffer.getReadPointer (0), numChannels },
|
||||
AudioData::NonInterleavedDest<Format> { destBuffer.getArrayOfWritePointers(), numChannels },
|
||||
numSamples);
|
||||
|
||||
for (int ch = 0; ch < numChannels; ++ch)
|
||||
for (int i = 0; i < numSamples; ++i)
|
||||
expectEquals (sourceBuffer.getSample (0, ch + (i * numChannels)), destBuffer.getSample (ch, i));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static AudioConversionTests audioConversionUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,873 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class a container which holds all the classes pertaining to the AudioData::Pointer
|
||||
audio sample format class.
|
||||
|
||||
@see AudioData::Pointer.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioData
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
// These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
|
||||
|
||||
class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
|
||||
class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
|
||||
class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
|
||||
class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
|
||||
class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
|
||||
class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
|
||||
|
||||
//==============================================================================
|
||||
// These types can be used as the Endianness template parameter for the AudioData::Pointer class.
|
||||
|
||||
class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
|
||||
class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
|
||||
class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
|
||||
|
||||
//==============================================================================
|
||||
// These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
|
||||
|
||||
class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
|
||||
class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
|
||||
|
||||
//==============================================================================
|
||||
// These types can be used as the Constness template parameter for the AudioData::Pointer class.
|
||||
|
||||
class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
|
||||
class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data. */
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
class BigEndian
|
||||
{
|
||||
public:
|
||||
template <class SampleFormatType> static float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
|
||||
template <class SampleFormatType> static void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
|
||||
template <class SampleFormatType> static int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
|
||||
template <class SampleFormatType> static void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
|
||||
template <class SourceType, class DestType> static void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
|
||||
enum { isBigEndian = 1 };
|
||||
};
|
||||
|
||||
class LittleEndian
|
||||
{
|
||||
public:
|
||||
template <class SampleFormatType> static float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
|
||||
template <class SampleFormatType> static void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
|
||||
template <class SampleFormatType> static int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
|
||||
template <class SampleFormatType> static void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
|
||||
template <class SourceType, class DestType> static void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
|
||||
enum { isBigEndian = 0 };
|
||||
};
|
||||
|
||||
#if JUCE_BIG_ENDIAN
|
||||
class NativeEndian : public BigEndian {};
|
||||
#else
|
||||
class NativeEndian : public LittleEndian {};
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
class Int8
|
||||
{
|
||||
public:
|
||||
inline Int8 (void* d) noexcept : data (static_cast<int8*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { ++data; }
|
||||
inline void skip (int numSamples) noexcept { data += numSamples; }
|
||||
inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + (double) maxValue))); }
|
||||
inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + (double) maxValue))); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int) (*((uint8*) data) << 24); }
|
||||
inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
|
||||
inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
|
||||
inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
|
||||
inline void clear() noexcept { *data = 0; }
|
||||
inline void clearMultiple (int num) noexcept { zeromem (data, (size_t) (num * bytesPerSample)) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
|
||||
|
||||
int8* data;
|
||||
enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
|
||||
};
|
||||
|
||||
class UInt8
|
||||
{
|
||||
public:
|
||||
inline UInt8 (void* d) noexcept : data (static_cast<uint8*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { ++data; }
|
||||
inline void skip (int numSamples) noexcept { data += numSamples; }
|
||||
inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + (double) maxValue))); }
|
||||
inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + (double) maxValue))); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int) (((uint8) (*data - 128)) << 24); }
|
||||
inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
|
||||
inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
|
||||
inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
|
||||
inline void clear() noexcept { *data = 128; }
|
||||
inline void clearMultiple (int num) noexcept { memset (data, 128, (size_t) num) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
|
||||
|
||||
uint8* data;
|
||||
enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
|
||||
};
|
||||
|
||||
class Int16
|
||||
{
|
||||
public:
|
||||
inline Int16 (void* d) noexcept : data (static_cast<uint16*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { ++data; }
|
||||
inline void skip (int numSamples) noexcept { data += numSamples; }
|
||||
inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
|
||||
inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + (double) maxValue)))); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + (double) maxValue)))); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
|
||||
inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
|
||||
inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
|
||||
inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
|
||||
inline void clear() noexcept { *data = 0; }
|
||||
inline void clearMultiple (int num) noexcept { zeromem (data, (size_t) (num * bytesPerSample)) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
|
||||
|
||||
uint16* data;
|
||||
enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
|
||||
};
|
||||
|
||||
class Int24
|
||||
{
|
||||
public:
|
||||
inline Int24 (void* d) noexcept : data (static_cast<char*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { data += 3; }
|
||||
inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
|
||||
inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + (double) maxValue))); }
|
||||
inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + (double) maxValue))); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + (double) maxValue))), data); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + (double) maxValue))), data); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int32) (((unsigned int) ByteOrder::littleEndian24Bit (data)) << 8); }
|
||||
inline int32 getAsInt32BE() const noexcept { return (int32) (((unsigned int) ByteOrder::bigEndian24Bit (data)) << 8); }
|
||||
inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
|
||||
inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
|
||||
inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
|
||||
inline void clearMultiple (int num) noexcept { zeromem (data, (size_t) (num * bytesPerSample)) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
|
||||
|
||||
char* data;
|
||||
enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
|
||||
};
|
||||
|
||||
class Int32
|
||||
{
|
||||
public:
|
||||
inline Int32 (void* d) noexcept : data (static_cast<uint32*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { ++data; }
|
||||
inline void skip (int numSamples) noexcept { data += numSamples; }
|
||||
inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
|
||||
inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (int32) ((double) maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (int32) ((double) maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
|
||||
inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
|
||||
inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
|
||||
inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
|
||||
inline void clear() noexcept { *data = 0; }
|
||||
inline void clearMultiple (int num) noexcept { zeromem (data, (size_t) (num * bytesPerSample)) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
|
||||
|
||||
uint32* data;
|
||||
enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
|
||||
};
|
||||
|
||||
/** A 32-bit integer type, of which only the bottom 24 bits are used. */
|
||||
class Int24in32 : public Int32
|
||||
{
|
||||
public:
|
||||
inline Int24in32 (void* d) noexcept : Int32 (d) {}
|
||||
|
||||
inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
|
||||
inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + (double) maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) ((double) maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
|
||||
inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) ((double) maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
|
||||
inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data) << 8; }
|
||||
inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data) << 8; }
|
||||
inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue >> 8); }
|
||||
inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue >> 8); }
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
|
||||
inline void copyFromSameType (Int24in32& source) noexcept { *data = *source.data; }
|
||||
|
||||
enum { bytesPerSample = 4, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
|
||||
};
|
||||
|
||||
class Float32
|
||||
{
|
||||
public:
|
||||
inline Float32 (void* d) noexcept : data (static_cast<float*> (d)) {}
|
||||
|
||||
inline void advance() noexcept { ++data; }
|
||||
inline void skip (int numSamples) noexcept { data += numSamples; }
|
||||
#if JUCE_BIG_ENDIAN
|
||||
inline float getAsFloatBE() const noexcept { return *data; }
|
||||
inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
|
||||
inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
|
||||
inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
|
||||
#else
|
||||
inline float getAsFloatLE() const noexcept { return *data; }
|
||||
inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
|
||||
inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
|
||||
inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
|
||||
#endif
|
||||
inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
|
||||
inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
|
||||
inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + (double) maxValue)))); }
|
||||
inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + (double) maxValue)))); }
|
||||
inline void clear() noexcept { *data = 0; }
|
||||
inline void clearMultiple (int num) noexcept { zeromem (data, (size_t) (num * bytesPerSample)) ;}
|
||||
template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
|
||||
template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
|
||||
inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
|
||||
|
||||
float* data;
|
||||
enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class NonInterleaved
|
||||
{
|
||||
public:
|
||||
inline NonInterleaved() = default;
|
||||
inline NonInterleaved (const NonInterleaved&) = default;
|
||||
inline NonInterleaved (int) noexcept {}
|
||||
inline void copyFrom (const NonInterleaved&) noexcept {}
|
||||
template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
|
||||
template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
|
||||
template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
|
||||
template <class SampleFormatType> static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
|
||||
|
||||
enum { isInterleavedType = 0, numInterleavedChannels = 1 };
|
||||
};
|
||||
|
||||
class Interleaved
|
||||
{
|
||||
public:
|
||||
inline Interleaved() noexcept {}
|
||||
inline Interleaved (const Interleaved& other) = default;
|
||||
inline Interleaved (const int numInterleavedChans) noexcept : numInterleavedChannels (numInterleavedChans) {}
|
||||
inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
|
||||
template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
|
||||
template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
|
||||
template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
|
||||
template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
|
||||
int numInterleavedChannels = 1;
|
||||
enum { isInterleavedType = 1 };
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class NonConst
|
||||
{
|
||||
public:
|
||||
using VoidType = void;
|
||||
static void* toVoidPtr (VoidType* v) noexcept { return v; }
|
||||
enum { isConst = 0 };
|
||||
};
|
||||
|
||||
class Const
|
||||
{
|
||||
public:
|
||||
using VoidType = const void;
|
||||
static void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
|
||||
enum { isConst = 1 };
|
||||
};
|
||||
/** @endcond */
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A pointer to a block of audio data with a particular encoding.
|
||||
|
||||
This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
|
||||
the audio format as a series of template parameters, e.g.
|
||||
@code
|
||||
// this creates a pointer for reading from a const array of 16-bit little-endian packed samples
|
||||
AudioData::Pointer <AudioData::Int16,
|
||||
AudioData::LittleEndian,
|
||||
AudioData::NonInterleaved,
|
||||
AudioData::Const> pointer (someRawAudioData);
|
||||
|
||||
// these methods read the sample that is being pointed to
|
||||
float firstSampleAsFloat = pointer.getAsFloat();
|
||||
int32 firstSampleAsInt = pointer.getAsInt32();
|
||||
++pointer; // moves the pointer to the next sample
|
||||
pointer += 3; // skips the next 3 samples
|
||||
@endcode
|
||||
|
||||
The convertSamples() method lets you copy a range of samples from one format to another, automatically
|
||||
converting its format.
|
||||
|
||||
@see AudioData::Converter
|
||||
*/
|
||||
template <typename SampleFormat,
|
||||
typename Endianness,
|
||||
typename InterleavingType,
|
||||
typename Constness>
|
||||
class Pointer : private InterleavingType // (inherited for EBCO)
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a non-interleaved pointer from some raw data in the appropriate format.
|
||||
This constructor is only used if you've specified the AudioData::NonInterleaved option -
|
||||
for interleaved formats, use the constructor that also takes a number of channels.
|
||||
*/
|
||||
Pointer (typename Constness::VoidType* sourceData) noexcept
|
||||
: data (Constness::toVoidPtr (sourceData))
|
||||
{
|
||||
// If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
|
||||
// you should pass NonInterleaved as the template parameter for the interleaving type!
|
||||
static_assert (InterleavingType::isInterleavedType == 0, "Incorrect constructor for interleaved data");
|
||||
}
|
||||
|
||||
/** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
|
||||
For non-interleaved data, use the other constructor.
|
||||
*/
|
||||
Pointer (typename Constness::VoidType* sourceData, int numInterleaved) noexcept
|
||||
: InterleavingType (numInterleaved), data (Constness::toVoidPtr (sourceData))
|
||||
{
|
||||
}
|
||||
|
||||
/** Creates a copy of another pointer. */
|
||||
Pointer (const Pointer& other) noexcept
|
||||
: InterleavingType (other), data (other.data)
|
||||
{
|
||||
}
|
||||
|
||||
Pointer& operator= (const Pointer& other) noexcept
|
||||
{
|
||||
InterleavingType::operator= (other);
|
||||
data = other.data;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the value of the first sample as a floating point value.
|
||||
The value will be in the range -1.0 to 1.0 for integer formats. For floating point
|
||||
formats, the value could be outside that range, although -1 to 1 is the standard range.
|
||||
*/
|
||||
inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
|
||||
|
||||
/** Sets the value of the first sample as a floating point value.
|
||||
|
||||
(This method can only be used if the AudioData::NonConst option was used).
|
||||
The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
|
||||
range will be clipped. For floating point formats, any value passed in here will be
|
||||
written directly, although -1 to 1 is the standard range.
|
||||
*/
|
||||
inline void setAsFloat (float newValue) noexcept
|
||||
{
|
||||
// trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
|
||||
static_assert (Constness::isConst == 0, "Attempt to write to a const pointer");
|
||||
Endianness::setAsFloat (data, newValue);
|
||||
}
|
||||
|
||||
/** Returns the value of the first sample as a 32-bit integer.
|
||||
The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
|
||||
shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
|
||||
by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
|
||||
be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
|
||||
*/
|
||||
inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
|
||||
|
||||
/** Sets the value of the first sample as a 32-bit integer.
|
||||
This will be mapped to the range of the format that is being written - see getAsInt32().
|
||||
*/
|
||||
inline void setAsInt32 (int32 newValue) noexcept
|
||||
{
|
||||
// trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
|
||||
static_assert (Constness::isConst == 0, "Attempt to write to a const pointer");
|
||||
Endianness::setAsInt32 (data, newValue);
|
||||
}
|
||||
|
||||
/** Moves the pointer along to the next sample. */
|
||||
inline Pointer& operator++() noexcept { advance(); return *this; }
|
||||
|
||||
/** Moves the pointer back to the previous sample. */
|
||||
inline Pointer& operator--() noexcept { this->advanceDataBy (data, -1); return *this; }
|
||||
|
||||
/** Adds a number of samples to the pointer's position. */
|
||||
Pointer& operator+= (int samplesToJump) noexcept { this->advanceDataBy (data, samplesToJump); return *this; }
|
||||
|
||||
/** Returns a new pointer with the specified offset from this pointer's position. */
|
||||
Pointer operator+ (int samplesToJump) const { return Pointer { *this } += samplesToJump; }
|
||||
|
||||
/** Writes a stream of samples into this pointer from another pointer.
|
||||
This will copy the specified number of samples, converting between formats appropriately.
|
||||
*/
|
||||
void convertSamples (Pointer source, int numSamples) const noexcept
|
||||
{
|
||||
// trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
|
||||
static_assert (Constness::isConst == 0, "Attempt to write to a const pointer");
|
||||
|
||||
for (Pointer dest (*this); --numSamples >= 0;)
|
||||
{
|
||||
dest.data.copyFromSameType (source.data);
|
||||
dest.advance();
|
||||
source.advance();
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a stream of samples into this pointer from another pointer.
|
||||
This will copy the specified number of samples, converting between formats appropriately.
|
||||
*/
|
||||
template <class OtherPointerType>
|
||||
void convertSamples (OtherPointerType source, int numSamples) const noexcept
|
||||
{
|
||||
// trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
|
||||
static_assert (Constness::isConst == 0, "Attempt to write to a const pointer");
|
||||
|
||||
Pointer dest (*this);
|
||||
|
||||
if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
|
||||
{
|
||||
while (--numSamples >= 0)
|
||||
{
|
||||
Endianness::copyFrom (dest.data, source);
|
||||
dest.advance();
|
||||
++source;
|
||||
}
|
||||
}
|
||||
else // copy backwards if we're increasing the sample width
|
||||
{
|
||||
dest += numSamples;
|
||||
source += numSamples;
|
||||
|
||||
while (--numSamples >= 0)
|
||||
Endianness::copyFrom ((--dest).data, --source);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets a number of samples to zero. */
|
||||
void clearSamples (int numSamples) const noexcept
|
||||
{
|
||||
Pointer dest (*this);
|
||||
dest.clear (dest.data, numSamples);
|
||||
}
|
||||
|
||||
/** Scans a block of data, returning the lowest and highest levels as floats */
|
||||
Range<float> findMinAndMax (size_t numSamples) const noexcept
|
||||
{
|
||||
if (numSamples == 0)
|
||||
return Range<float>();
|
||||
|
||||
Pointer dest (*this);
|
||||
|
||||
if (isFloatingPoint())
|
||||
{
|
||||
float mn = dest.getAsFloat();
|
||||
dest.advance();
|
||||
float mx = mn;
|
||||
|
||||
while (--numSamples > 0)
|
||||
{
|
||||
const float v = dest.getAsFloat();
|
||||
dest.advance();
|
||||
|
||||
if (mx < v) mx = v;
|
||||
if (v < mn) mn = v;
|
||||
}
|
||||
|
||||
return Range<float> (mn, mx);
|
||||
}
|
||||
|
||||
int32 mn = dest.getAsInt32();
|
||||
dest.advance();
|
||||
int32 mx = mn;
|
||||
|
||||
while (--numSamples > 0)
|
||||
{
|
||||
const int v = dest.getAsInt32();
|
||||
dest.advance();
|
||||
|
||||
if (mx < v) mx = v;
|
||||
if (v < mn) mn = v;
|
||||
}
|
||||
|
||||
return Range<float> ((float) mn * (float) (1.0 / (1.0 + (double) Int32::maxValue)),
|
||||
(float) mx * (float) (1.0 / (1.0 + (double) Int32::maxValue)));
|
||||
}
|
||||
|
||||
/** Scans a block of data, returning the lowest and highest levels as floats */
|
||||
void findMinAndMax (size_t numSamples, float& minValue, float& maxValue) const noexcept
|
||||
{
|
||||
Range<float> r (findMinAndMax (numSamples));
|
||||
minValue = r.getStart();
|
||||
maxValue = r.getEnd();
|
||||
}
|
||||
|
||||
/** Returns true if the pointer is using a floating-point format. */
|
||||
static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
|
||||
|
||||
/** Returns true if the format is big-endian. */
|
||||
static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
|
||||
|
||||
/** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
|
||||
static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
|
||||
|
||||
/** Returns the number of interleaved channels in the format. */
|
||||
int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
|
||||
|
||||
/** Returns the number of bytes between the start address of each sample. */
|
||||
int getNumBytesBetweenSamples() const noexcept { return InterleavingType::getNumBytesBetweenSamples (data); }
|
||||
|
||||
/** Returns the accuracy of this format when represented as a 32-bit integer.
|
||||
This is the smallest number above 0 that can be represented in the sample format, converted to
|
||||
a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
|
||||
its resolution is 0x100.
|
||||
*/
|
||||
static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
|
||||
|
||||
/** Returns a pointer to the underlying data. */
|
||||
const void* getRawData() const noexcept { return data.data; }
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
SampleFormat data;
|
||||
|
||||
inline void advance() noexcept { this->advanceData (data); }
|
||||
|
||||
Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
|
||||
Pointer operator-- (int);
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** A base class for objects that are used to convert between two different sample formats.
|
||||
|
||||
The AudioData::ConverterInstance implements this base class and can be templated, so
|
||||
you can create an instance that converts between two particular formats, and then
|
||||
store this in the abstract base class.
|
||||
|
||||
@see AudioData::ConverterInstance
|
||||
*/
|
||||
class Converter
|
||||
{
|
||||
public:
|
||||
virtual ~Converter() = default;
|
||||
|
||||
/** Converts a sequence of samples from the converter's source format into the dest format. */
|
||||
virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
|
||||
|
||||
/** Converts a sequence of samples from the converter's source format into the dest format.
|
||||
This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
|
||||
particular sub-channel of the data to be used.
|
||||
*/
|
||||
virtual void convertSamples (void* destSamples, int destSubChannel,
|
||||
const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A class that converts between two templated AudioData::Pointer types, and which
|
||||
implements the AudioData::Converter interface.
|
||||
|
||||
This can be used as a concrete instance of the AudioData::Converter abstract class.
|
||||
|
||||
@see AudioData::Converter
|
||||
*/
|
||||
template <class SourceSampleType, class DestSampleType>
|
||||
class ConverterInstance : public Converter
|
||||
{
|
||||
public:
|
||||
ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
|
||||
: sourceChannels (numSourceChannels), destChannels (numDestChannels)
|
||||
{}
|
||||
|
||||
void convertSamples (void* dest, const void* source, int numSamples) const override
|
||||
{
|
||||
SourceSampleType s (source, sourceChannels);
|
||||
DestSampleType d (dest, destChannels);
|
||||
d.convertSamples (s, numSamples);
|
||||
}
|
||||
|
||||
void convertSamples (void* dest, int destSubChannel,
|
||||
const void* source, int sourceSubChannel, int numSamples) const override
|
||||
{
|
||||
jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
|
||||
|
||||
SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
|
||||
DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
|
||||
d.convertSamples (s, numSamples);
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE (ConverterInstance)
|
||||
|
||||
const int sourceChannels, destChannels;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** A struct that contains a SampleFormat and Endianness to be used with the source and
|
||||
destination types when calling the interleaveSamples() and deinterleaveSamples() helpers.
|
||||
|
||||
@see interleaveSamples, deinterleaveSamples
|
||||
*/
|
||||
template <typename DataFormatIn, typename EndiannessIn>
|
||||
struct Format
|
||||
{
|
||||
using DataFormat = DataFormatIn;
|
||||
using Endianness = EndiannessIn;
|
||||
};
|
||||
|
||||
private:
|
||||
template <bool IsInterleaved, bool IsConst, typename...>
|
||||
struct ChannelDataSubtypes;
|
||||
|
||||
template <bool IsInterleaved, bool IsConst, typename DataFormat, typename Endianness>
|
||||
struct ChannelDataSubtypes<IsInterleaved, IsConst, DataFormat, Endianness>
|
||||
{
|
||||
using ElementType = std::remove_pointer_t<decltype (DataFormat::data)>;
|
||||
using ChannelType = std::conditional_t<IsConst, const ElementType*, ElementType*>;
|
||||
using DataType = std::conditional_t<IsInterleaved, ChannelType, ChannelType const*>;
|
||||
using PointerType = Pointer<DataFormat,
|
||||
Endianness,
|
||||
std::conditional_t<IsInterleaved, Interleaved, NonInterleaved>,
|
||||
std::conditional_t<IsConst, Const, NonConst>>;
|
||||
};
|
||||
|
||||
template <bool IsInterleaved, bool IsConst, typename DataFormat, typename Endianness>
|
||||
struct ChannelDataSubtypes<IsInterleaved, IsConst, Format<DataFormat, Endianness>>
|
||||
{
|
||||
using Subtypes = ChannelDataSubtypes<IsInterleaved, IsConst, DataFormat, Endianness>;
|
||||
using DataType = typename Subtypes::DataType;
|
||||
using PointerType = typename Subtypes::PointerType;
|
||||
};
|
||||
|
||||
template <bool IsInterleaved, bool IsConst, typename... Format>
|
||||
struct ChannelData
|
||||
{
|
||||
using Subtypes = ChannelDataSubtypes<IsInterleaved, IsConst, Format...>;
|
||||
using DataType = typename Subtypes::DataType;
|
||||
using PointerType = typename Subtypes::PointerType;
|
||||
|
||||
DataType data;
|
||||
int channels;
|
||||
};
|
||||
|
||||
public:
|
||||
//==============================================================================
|
||||
/** A sequence of interleaved samples used as the source for the deinterleaveSamples() method. */
|
||||
template <typename... Format> using InterleavedSource = ChannelData<true, true, Format...>;
|
||||
/** A sequence of interleaved samples used as the destination for the interleaveSamples() method. */
|
||||
template <typename... Format> using InterleavedDest = ChannelData<true, false, Format...>;
|
||||
/** A sequence of non-interleaved samples used as the source for the interleaveSamples() method. */
|
||||
template <typename... Format> using NonInterleavedSource = ChannelData<false, true, Format...>;
|
||||
/** A sequence of non-interleaved samples used as the destination for the deinterleaveSamples() method. */
|
||||
template <typename... Format> using NonInterleavedDest = ChannelData<false, false, Format...>;
|
||||
|
||||
/** A helper function for converting a sequence of samples from a non-interleaved source
|
||||
to an interleaved destination.
|
||||
|
||||
When calling this method you need to specify the source and destination data format and endianness
|
||||
from the AudioData SampleFormat and Endianness types and provide the data and number of channels
|
||||
for each. For example, to convert a floating-point stream of big endian samples to an interleaved,
|
||||
native endian stream of 16-bit integer samples you would do the following:
|
||||
|
||||
@code
|
||||
using SourceFormat = AudioData::Format<AudioData::Float32, AudioData::BigEndian>;
|
||||
using DestFormat = AudioData::Format<AudioData::Int16, AudioData::NativeEndian>;
|
||||
|
||||
AudioData::interleaveSamples (AudioData::NonInterleavedSource<SourceFormat> { sourceData, numSourceChannels },
|
||||
AudioData::InterleavedDest<DestFormat> { destData, numDestChannels },
|
||||
numSamples);
|
||||
@endcode
|
||||
*/
|
||||
template <typename... SourceFormat, typename... DestFormat>
|
||||
static void interleaveSamples (NonInterleavedSource<SourceFormat...> source,
|
||||
InterleavedDest<DestFormat...> dest,
|
||||
int numSamples)
|
||||
{
|
||||
using SourceType = typename decltype (source)::PointerType;
|
||||
using DestType = typename decltype (dest) ::PointerType;
|
||||
|
||||
for (int i = 0; i < dest.channels; ++i)
|
||||
{
|
||||
const DestType destType (addBytesToPointer (dest.data, i * DestType::getBytesPerSample()), dest.channels);
|
||||
|
||||
if (i < source.channels)
|
||||
{
|
||||
if (*source.data != nullptr)
|
||||
{
|
||||
destType.convertSamples (SourceType { *source.data }, numSamples);
|
||||
++source.data;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
destType.clearSamples (numSamples);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A helper function for converting a sequence of samples from an interleaved source
|
||||
to a non-interleaved destination.
|
||||
|
||||
When calling this method you need to specify the source and destination data format and endianness
|
||||
from the AudioData SampleFormat and Endianness types and provide the data and number of channels
|
||||
for each. For example, to convert a floating-point stream of big endian samples to an non-interleaved,
|
||||
native endian stream of 16-bit integer samples you would do the following:
|
||||
|
||||
@code
|
||||
using SourceFormat = AudioData::Format<AudioData::Float32, AudioData::BigEndian>;
|
||||
using DestFormat = AudioData::Format<AudioData::Int16, AudioData::NativeEndian>;
|
||||
|
||||
AudioData::deinterleaveSamples (AudioData::InterleavedSource<SourceFormat> { sourceData, numSourceChannels },
|
||||
AudioData::NonInterleavedDest<DestFormat> { destData, numDestChannels },
|
||||
numSamples);
|
||||
@endcode
|
||||
*/
|
||||
template <typename... SourceFormat, typename... DestFormat>
|
||||
static void deinterleaveSamples (InterleavedSource<SourceFormat...> source,
|
||||
NonInterleavedDest<DestFormat...> dest,
|
||||
int numSamples)
|
||||
{
|
||||
using SourceType = typename decltype (source)::PointerType;
|
||||
using DestType = typename decltype (dest) ::PointerType;
|
||||
|
||||
for (int i = 0; i < dest.channels; ++i)
|
||||
{
|
||||
if (auto* targetChan = dest.data[i])
|
||||
{
|
||||
const DestType destType (targetChan);
|
||||
|
||||
if (i < source.channels)
|
||||
destType.convertSamples (SourceType (addBytesToPointer (source.data, i * SourceType::getBytesPerSample()), source.channels), numSamples);
|
||||
else
|
||||
destType.clearSamples (numSamples);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
/**
|
||||
A set of routines to convert buffers of 32-bit floating point data to and from
|
||||
various integer formats.
|
||||
|
||||
Note that these functions are deprecated - the AudioData class provides a much more
|
||||
flexible set of conversion classes now.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class [[deprecated]] JUCE_API AudioDataConverters
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
|
||||
static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
|
||||
|
||||
static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
|
||||
static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
|
||||
|
||||
static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
|
||||
static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
|
||||
|
||||
static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
|
||||
static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
|
||||
|
||||
//==============================================================================
|
||||
static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
|
||||
static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
|
||||
|
||||
static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
|
||||
static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
|
||||
|
||||
static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
|
||||
static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
|
||||
|
||||
static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
|
||||
static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
|
||||
|
||||
//==============================================================================
|
||||
enum DataFormat
|
||||
{
|
||||
int16LE,
|
||||
int16BE,
|
||||
int24LE,
|
||||
int24BE,
|
||||
int32LE,
|
||||
int32BE,
|
||||
float32LE,
|
||||
float32BE,
|
||||
};
|
||||
|
||||
static void convertFloatToFormat (DataFormat destFormat,
|
||||
const float* source, void* dest, int numSamples);
|
||||
|
||||
static void convertFormatToFloat (DataFormat sourceFormat,
|
||||
const void* source, float* dest, int numSamples);
|
||||
|
||||
//==============================================================================
|
||||
static void interleaveSamples (const float** source, float* dest,
|
||||
int numSamples, int numChannels);
|
||||
|
||||
static void deinterleaveSamples (const float* source, float** dest,
|
||||
int numSamples, int numChannels);
|
||||
|
||||
private:
|
||||
AudioDataConverters();
|
||||
};
|
||||
/** @endcond */
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
AudioProcessLoadMeasurer::AudioProcessLoadMeasurer() = default;
|
||||
AudioProcessLoadMeasurer::~AudioProcessLoadMeasurer() = default;
|
||||
|
||||
void AudioProcessLoadMeasurer::reset()
|
||||
{
|
||||
reset (0, 0);
|
||||
}
|
||||
|
||||
void AudioProcessLoadMeasurer::reset (double sampleRate, int blockSize)
|
||||
{
|
||||
const SpinLock::ScopedLockType lock (mutex);
|
||||
|
||||
cpuUsageProportion = 0;
|
||||
xruns = 0;
|
||||
|
||||
samplesPerBlock = blockSize;
|
||||
msPerSample = (sampleRate > 0.0 && blockSize > 0) ? 1000.0 / sampleRate : 0;
|
||||
}
|
||||
|
||||
void AudioProcessLoadMeasurer::registerBlockRenderTime (double milliseconds)
|
||||
{
|
||||
const SpinLock::ScopedTryLockType lock (mutex);
|
||||
|
||||
if (lock.isLocked())
|
||||
registerRenderTimeLocked (milliseconds, samplesPerBlock);
|
||||
}
|
||||
|
||||
void AudioProcessLoadMeasurer::registerRenderTime (double milliseconds, int numSamples)
|
||||
{
|
||||
const SpinLock::ScopedTryLockType lock (mutex);
|
||||
|
||||
if (lock.isLocked())
|
||||
registerRenderTimeLocked (milliseconds, numSamples);
|
||||
}
|
||||
|
||||
void AudioProcessLoadMeasurer::registerRenderTimeLocked (double milliseconds, int numSamples)
|
||||
{
|
||||
if (approximatelyEqual (msPerSample, 0.0))
|
||||
return;
|
||||
|
||||
const auto maxMilliseconds = numSamples * msPerSample;
|
||||
const auto usedProportion = milliseconds / maxMilliseconds;
|
||||
const auto filterAmount = 0.2;
|
||||
const auto proportion = cpuUsageProportion.load();
|
||||
cpuUsageProportion = proportion + filterAmount * (usedProportion - proportion);
|
||||
|
||||
if (milliseconds > maxMilliseconds)
|
||||
++xruns;
|
||||
}
|
||||
|
||||
double AudioProcessLoadMeasurer::getLoadAsProportion() const { return jlimit (0.0, 1.0, cpuUsageProportion.load()); }
|
||||
double AudioProcessLoadMeasurer::getLoadAsPercentage() const { return 100.0 * getLoadAsProportion(); }
|
||||
|
||||
int AudioProcessLoadMeasurer::getXRunCount() const { return xruns; }
|
||||
|
||||
AudioProcessLoadMeasurer::ScopedTimer::ScopedTimer (AudioProcessLoadMeasurer& p)
|
||||
: ScopedTimer (p, p.samplesPerBlock)
|
||||
{
|
||||
}
|
||||
|
||||
AudioProcessLoadMeasurer::ScopedTimer::ScopedTimer (AudioProcessLoadMeasurer& p, int numSamplesInBlock)
|
||||
: owner (p), startTime (Time::getMillisecondCounterHiRes()), samplesInBlock (numSamplesInBlock)
|
||||
{
|
||||
// numSamplesInBlock should never be zero. Did you remember to call AudioProcessLoadMeasurer::reset(),
|
||||
// passing the expected samples per block?
|
||||
jassert (numSamplesInBlock);
|
||||
}
|
||||
|
||||
AudioProcessLoadMeasurer::ScopedTimer::~ScopedTimer()
|
||||
{
|
||||
owner.registerRenderTime (Time::getMillisecondCounterHiRes() - startTime, samplesInBlock);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Maintains an ongoing measurement of the proportion of time which is being
|
||||
spent inside an audio callback.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API AudioProcessLoadMeasurer
|
||||
{
|
||||
public:
|
||||
/** */
|
||||
AudioProcessLoadMeasurer();
|
||||
|
||||
/** Destructor. */
|
||||
~AudioProcessLoadMeasurer();
|
||||
|
||||
//==============================================================================
|
||||
/** Resets the state. */
|
||||
void reset();
|
||||
|
||||
/** Resets the counter, in preparation for use with the given sample rate and block size. */
|
||||
void reset (double sampleRate, int blockSize);
|
||||
|
||||
/** Returns the current load as a proportion 0 to 1.0 */
|
||||
double getLoadAsProportion() const;
|
||||
|
||||
/** Returns the current load as a percentage 0 to 100.0 */
|
||||
double getLoadAsPercentage() const;
|
||||
|
||||
/** Returns the number of over- (or under-) runs recorded since the state was reset. */
|
||||
int getXRunCount() const;
|
||||
|
||||
//==============================================================================
|
||||
/** This class measures the time between its construction and destruction and
|
||||
adds it to an AudioProcessLoadMeasurer.
|
||||
|
||||
e.g.
|
||||
@code
|
||||
{
|
||||
AudioProcessLoadMeasurer::ScopedTimer timer (myProcessLoadMeasurer);
|
||||
myCallback->doTheCallback();
|
||||
}
|
||||
@endcode
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct JUCE_API ScopedTimer
|
||||
{
|
||||
ScopedTimer (AudioProcessLoadMeasurer&);
|
||||
ScopedTimer (AudioProcessLoadMeasurer&, int numSamplesInBlock);
|
||||
~ScopedTimer();
|
||||
|
||||
private:
|
||||
AudioProcessLoadMeasurer& owner;
|
||||
double startTime;
|
||||
int samplesInBlock;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (ScopedTimer)
|
||||
};
|
||||
|
||||
/** Can be called manually to add the time of a callback to the stats.
|
||||
Normally you probably would never call this - it's simpler and more robust to
|
||||
use a ScopedTimer to measure the time using an RAII pattern.
|
||||
*/
|
||||
void registerBlockRenderTime (double millisecondsTaken);
|
||||
|
||||
/** Can be called manually to add the time of a callback to the stats.
|
||||
Normally you probably would never call this - it's simpler and more robust to
|
||||
use a ScopedTimer to measure the time using an RAII pattern.
|
||||
*/
|
||||
void registerRenderTime (double millisecondsTaken, int numSamples);
|
||||
|
||||
private:
|
||||
void registerRenderTimeLocked (double, int);
|
||||
|
||||
SpinLock mutex;
|
||||
int samplesPerBlock = 0;
|
||||
double msPerSample = 0;
|
||||
std::atomic<double> cpuUsageProportion { 0 };
|
||||
std::atomic<int> xruns { 0 };
|
||||
};
|
||||
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
#ifndef JUCE_SNAP_TO_ZERO
|
||||
#if JUCE_INTEL
|
||||
#define JUCE_SNAP_TO_ZERO(n) if (! (n < -1.0e-8f || n > 1.0e-8f)) n = 0;
|
||||
#else
|
||||
#define JUCE_SNAP_TO_ZERO(n) ignoreUnused (n)
|
||||
#endif
|
||||
#endif
|
||||
class ScopedNoDenormals;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A collection of simple vector operations on arrays of floating point numbers,
|
||||
accelerated with SIMD instructions where possible, usually accessed from
|
||||
the FloatVectorOperations class.
|
||||
|
||||
@code
|
||||
float data[64];
|
||||
|
||||
// The following two function calls are equivalent:
|
||||
FloatVectorOperationsBase<float, int>::clear (data, 64);
|
||||
FloatVectorOperations::clear (data, 64);
|
||||
@endcode
|
||||
|
||||
@see FloatVectorOperations
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
template <typename FloatType, typename CountType>
|
||||
struct JUCE_API FloatVectorOperationsBase
|
||||
{
|
||||
/** Clears a vector of floating point numbers. */
|
||||
static void JUCE_CALLTYPE clear (FloatType* dest, CountType numValues) noexcept;
|
||||
|
||||
/** Copies a repeated value into a vector of floating point numbers. */
|
||||
static void JUCE_CALLTYPE fill (FloatType* dest, FloatType valueToFill, CountType numValues) noexcept;
|
||||
|
||||
/** Copies a vector of floating point numbers. */
|
||||
static void JUCE_CALLTYPE copy (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Copies a vector of floating point numbers, multiplying each value by a given multiplier */
|
||||
static void JUCE_CALLTYPE copyWithMultiply (FloatType* dest, const FloatType* src, FloatType multiplier, CountType numValues) noexcept;
|
||||
|
||||
/** Adds a fixed value to the dest values. */
|
||||
static void JUCE_CALLTYPE add (FloatType* dest, FloatType amountToAdd, CountType numValues) noexcept;
|
||||
|
||||
/** Adds a fixed value to each src value and stores it in the dest array. */
|
||||
static void JUCE_CALLTYPE add (FloatType* dest, const FloatType* src, FloatType amount, CountType numValues) noexcept;
|
||||
|
||||
/** Adds each src value to the corresponding dest value. */
|
||||
static void JUCE_CALLTYPE add (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Adds each src1 value to the corresponding src2 value and stores the result in the dest array. */
|
||||
static void JUCE_CALLTYPE add (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Subtracts the src values from the dest values. */
|
||||
static void JUCE_CALLTYPE subtract (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Subtracts each src2 value from the corresponding src1 value and stores the result in the dest array. */
|
||||
static void JUCE_CALLTYPE subtract (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Multiplies each src value by the given multiplier, then adds it to the dest value. */
|
||||
static void JUCE_CALLTYPE addWithMultiply (FloatType* dest, const FloatType* src, FloatType multiplier, CountType numValues) noexcept;
|
||||
|
||||
/** Multiplies each src1 value by the corresponding src2 value, then adds it to the dest value. */
|
||||
static void JUCE_CALLTYPE addWithMultiply (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Multiplies each src value by the given multiplier, then subtracts it from the dest value. */
|
||||
static void JUCE_CALLTYPE subtractWithMultiply (FloatType* dest, const FloatType* src, FloatType multiplier, CountType numValues) noexcept;
|
||||
|
||||
/** Multiplies each src1 value by the corresponding src2 value, then subtracts it from the dest value. */
|
||||
static void JUCE_CALLTYPE subtractWithMultiply (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Multiplies the dest values by the src values. */
|
||||
static void JUCE_CALLTYPE multiply (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Multiplies each src1 value by the corresponding src2 value, then stores it in the dest array. */
|
||||
static void JUCE_CALLTYPE multiply (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType numValues) noexcept;
|
||||
|
||||
/** Multiplies each of the dest values by a fixed multiplier. */
|
||||
static void JUCE_CALLTYPE multiply (FloatType* dest, FloatType multiplier, CountType numValues) noexcept;
|
||||
|
||||
/** Multiplies each of the src values by a fixed multiplier and stores the result in the dest array. */
|
||||
static void JUCE_CALLTYPE multiply (FloatType* dest, const FloatType* src, FloatType multiplier, CountType num) noexcept;
|
||||
|
||||
/** Copies the src vector to dest, negating each value. */
|
||||
static void JUCE_CALLTYPE negate (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Copies the src vector to dest, taking the absolute of each value. */
|
||||
static void JUCE_CALLTYPE abs (FloatType* dest, const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Each element of dest will be the minimum of the corresponding element of the src array and the given comp value. */
|
||||
static void JUCE_CALLTYPE min (FloatType* dest, const FloatType* src, FloatType comp, CountType num) noexcept;
|
||||
|
||||
/** Each element of dest will be the minimum of the corresponding src1 and src2 values. */
|
||||
static void JUCE_CALLTYPE min (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Each element of dest will be the maximum of the corresponding element of the src array and the given comp value. */
|
||||
static void JUCE_CALLTYPE max (FloatType* dest, const FloatType* src, FloatType comp, CountType num) noexcept;
|
||||
|
||||
/** Each element of dest will be the maximum of the corresponding src1 and src2 values. */
|
||||
static void JUCE_CALLTYPE max (FloatType* dest, const FloatType* src1, const FloatType* src2, CountType num) noexcept;
|
||||
|
||||
/** Each element of dest is calculated by hard clipping the corresponding src element so that it is in the range specified by the arguments low and high. */
|
||||
static void JUCE_CALLTYPE clip (FloatType* dest, const FloatType* src, FloatType low, FloatType high, CountType num) noexcept;
|
||||
|
||||
/** Finds the minimum and maximum values in the given array. */
|
||||
static Range<FloatType> JUCE_CALLTYPE findMinAndMax (const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Finds the minimum value in the given array. */
|
||||
static FloatType JUCE_CALLTYPE findMinimum (const FloatType* src, CountType numValues) noexcept;
|
||||
|
||||
/** Finds the maximum value in the given array. */
|
||||
static FloatType JUCE_CALLTYPE findMaximum (const FloatType* src, CountType numValues) noexcept;
|
||||
};
|
||||
|
||||
/** @cond */
|
||||
namespace detail
|
||||
{
|
||||
|
||||
template <typename... Bases>
|
||||
struct NameForwarder : public Bases...
|
||||
{
|
||||
using Bases::clear...,
|
||||
Bases::fill...,
|
||||
Bases::copy...,
|
||||
Bases::copyWithMultiply...,
|
||||
Bases::add...,
|
||||
Bases::subtract...,
|
||||
Bases::addWithMultiply...,
|
||||
Bases::subtractWithMultiply...,
|
||||
Bases::multiply...,
|
||||
Bases::negate...,
|
||||
Bases::abs...,
|
||||
Bases::min...,
|
||||
Bases::max...,
|
||||
Bases::clip...,
|
||||
Bases::findMinAndMax...,
|
||||
Bases::findMinimum...,
|
||||
Bases::findMaximum...;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
/** @endcond */
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A collection of simple vector operations on arrays of floating point numbers,
|
||||
accelerated with SIMD instructions where possible and providing all methods
|
||||
from FloatVectorOperationsBase.
|
||||
|
||||
@see FloatVectorOperationsBase
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API FloatVectorOperations : public detail::NameForwarder<FloatVectorOperationsBase<float, int>,
|
||||
FloatVectorOperationsBase<float, size_t>,
|
||||
FloatVectorOperationsBase<double, int>,
|
||||
FloatVectorOperationsBase<double, size_t>>
|
||||
{
|
||||
public:
|
||||
static void JUCE_CALLTYPE convertFixedToFloat (float* dest, const int* src, float multiplier, int num) noexcept;
|
||||
|
||||
static void JUCE_CALLTYPE convertFixedToFloat (float* dest, const int* src, float multiplier, size_t num) noexcept;
|
||||
|
||||
/** This method enables or disables the SSE/NEON flush-to-zero mode. */
|
||||
static void JUCE_CALLTYPE enableFlushToZeroMode (bool shouldEnable) noexcept;
|
||||
|
||||
/** On Intel CPUs, this method enables the SSE flush-to-zero and denormalised-are-zero modes.
|
||||
This effectively sets the DAZ and FZ bits of the MXCSR register. On arm CPUs this will
|
||||
enable flush to zero mode.
|
||||
It's a convenient thing to call before audio processing code where you really want to
|
||||
avoid denormalisation performance hits.
|
||||
*/
|
||||
static void JUCE_CALLTYPE disableDenormalisedNumberSupport (bool shouldDisable = true) noexcept;
|
||||
|
||||
/** This method returns true if denormals are currently disabled. */
|
||||
static bool JUCE_CALLTYPE areDenormalsDisabled() noexcept;
|
||||
|
||||
private:
|
||||
friend ScopedNoDenormals;
|
||||
|
||||
static intptr_t JUCE_CALLTYPE getFpStatusRegister() noexcept;
|
||||
static void JUCE_CALLTYPE setFpStatusRegister (intptr_t) noexcept;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helper class providing an RAII-based mechanism for temporarily disabling
|
||||
denormals on your CPU.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class ScopedNoDenormals
|
||||
{
|
||||
public:
|
||||
ScopedNoDenormals() noexcept;
|
||||
~ScopedNoDenormals() noexcept;
|
||||
|
||||
private:
|
||||
#if JUCE_USE_SSE_INTRINSICS || (JUCE_USE_ARM_NEON || (JUCE_64BIT && JUCE_ARM))
|
||||
intptr_t fpsr;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#ifdef JUCE_AUDIO_BASICS_H_INCLUDED
|
||||
/* When you add this cpp file to your project, you mustn't include it in a file where you've
|
||||
already included any other headers - just put it inside a file on its own, possibly with your config
|
||||
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
|
||||
header files that the compiler may be using.
|
||||
*/
|
||||
#error "Incorrect use of JUCE cpp file"
|
||||
#endif
|
||||
|
||||
#include "juce_audio_basics.h"
|
||||
|
||||
#if JUCE_USE_SSE_INTRINSICS
|
||||
#include <emmintrin.h>
|
||||
#endif
|
||||
|
||||
#if JUCE_MAC || JUCE_IOS
|
||||
#ifndef JUCE_USE_VDSP_FRAMEWORK
|
||||
#define JUCE_USE_VDSP_FRAMEWORK 1
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_VDSP_FRAMEWORK
|
||||
#include <Accelerate/Accelerate.h>
|
||||
#endif
|
||||
|
||||
#include "native/juce_AudioWorkgroup_mac.h"
|
||||
|
||||
#elif JUCE_USE_VDSP_FRAMEWORK
|
||||
#undef JUCE_USE_VDSP_FRAMEWORK
|
||||
#endif
|
||||
|
||||
#if JUCE_USE_ARM_NEON
|
||||
#include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
#include "buffers/juce_AudioDataConverters.cpp"
|
||||
#include "buffers/juce_FloatVectorOperations.cpp"
|
||||
#include "buffers/juce_AudioChannelSet.cpp"
|
||||
#include "buffers/juce_AudioProcessLoadMeasurer.cpp"
|
||||
#include "utilities/juce_IIRFilter.cpp"
|
||||
#include "utilities/juce_LagrangeInterpolator.cpp"
|
||||
#include "utilities/juce_WindowedSincInterpolator.cpp"
|
||||
#include "utilities/juce_Interpolators.cpp"
|
||||
#include "utilities/juce_SmoothedValue.cpp"
|
||||
#include "midi/juce_MidiBuffer.cpp"
|
||||
#include "midi/juce_MidiFile.cpp"
|
||||
#include "midi/juce_MidiKeyboardState.cpp"
|
||||
#include "midi/juce_MidiMessage.cpp"
|
||||
#include "midi/juce_MidiMessageSequence.cpp"
|
||||
#include "midi/juce_MidiRPN.cpp"
|
||||
#include "mpe/juce_MPEValue.cpp"
|
||||
#include "mpe/juce_MPENote.cpp"
|
||||
#include "mpe/juce_MPEZoneLayout.cpp"
|
||||
#include "mpe/juce_MPEInstrument.cpp"
|
||||
#include "mpe/juce_MPEMessages.cpp"
|
||||
#include "mpe/juce_MPESynthesiserBase.cpp"
|
||||
#include "mpe/juce_MPESynthesiserVoice.cpp"
|
||||
#include "mpe/juce_MPESynthesiser.cpp"
|
||||
#include "mpe/juce_MPEUtils.cpp"
|
||||
#include "sources/juce_BufferingAudioSource.cpp"
|
||||
#include "sources/juce_ChannelRemappingAudioSource.cpp"
|
||||
#include "sources/juce_IIRFilterAudioSource.cpp"
|
||||
#include "sources/juce_MemoryAudioSource.cpp"
|
||||
#include "sources/juce_MixerAudioSource.cpp"
|
||||
#include "sources/juce_ResamplingAudioSource.cpp"
|
||||
#include "sources/juce_ReverbAudioSource.cpp"
|
||||
#include "sources/juce_ToneGeneratorAudioSource.cpp"
|
||||
#include "sources/juce_PositionableAudioSource.cpp"
|
||||
#include "synthesisers/juce_Synthesiser.cpp"
|
||||
#include "audio_play_head/juce_AudioPlayHead.cpp"
|
||||
#include "utilities/juce_AudioWorkgroup.cpp"
|
||||
|
||||
#include "midi/ump/juce_UMPDeviceInfo.cpp"
|
||||
#include "midi/ump/juce_UMPFactory.cpp"
|
||||
#include "midi/ump/juce_UMPUtils.cpp"
|
||||
#include "midi/ump/juce_UMPView.cpp"
|
||||
#include "midi/ump/juce_UMPSysEx7.cpp"
|
||||
#include "midi/ump/juce_UMPMidi1ToMidi2DefaultTranslator.cpp"
|
||||
#include "midi/ump/juce_UMPIterator.cpp"
|
||||
#include "midi/ump/juce_UMPStringUtils.cpp"
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
#include "utilities/juce_ADSR_test.cpp"
|
||||
#include "midi/juce_MidiDataConcatenator_test.cpp"
|
||||
#include "midi/ump/juce_UMP_test.cpp"
|
||||
#endif
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
The block below describes the properties of this module, and is read by
|
||||
the Projucer to automatically generate project code that uses it.
|
||||
For details about the syntax and how to create or use a module, see the
|
||||
JUCE Module Format.md file.
|
||||
|
||||
|
||||
BEGIN_JUCE_MODULE_DECLARATION
|
||||
|
||||
ID: juce_audio_basics
|
||||
vendor: juce
|
||||
version: 9.0.5
|
||||
name: JUCE audio and MIDI data classes
|
||||
description: Classes for audio buffer manipulation, midi message handling, synthesis, etc.
|
||||
website: http://www.juce.com/juce
|
||||
license: AGPLv3/Commercial
|
||||
minimumCppStandard: 17
|
||||
|
||||
dependencies: juce_core
|
||||
OSXFrameworks: Accelerate
|
||||
iOSFrameworks: Accelerate
|
||||
|
||||
END_JUCE_MODULE_DECLARATION
|
||||
|
||||
*******************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
#define JUCE_AUDIO_BASICS_H_INCLUDED
|
||||
|
||||
#include <juce_core/juce_core.h>
|
||||
|
||||
//==============================================================================
|
||||
#undef Complex // apparently some C libraries actually define these symbols (!)
|
||||
#undef Factor
|
||||
|
||||
//==============================================================================
|
||||
#include "buffers/juce_AudioDataConverters.h"
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4661)
|
||||
#include "buffers/juce_FloatVectorOperations.h"
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
#include "buffers/juce_AudioSampleBuffer.h"
|
||||
#include "buffers/juce_AudioChannelSet.h"
|
||||
#include "buffers/juce_AudioProcessLoadMeasurer.h"
|
||||
#include "utilities/juce_Decibels.h"
|
||||
#include "utilities/juce_IIRFilter.h"
|
||||
#include "utilities/juce_GenericInterpolator.h"
|
||||
#include "utilities/juce_Interpolators.h"
|
||||
#include "utilities/juce_SmoothedValue.h"
|
||||
#include "utilities/juce_Reverb.h"
|
||||
#include "utilities/juce_ADSR.h"
|
||||
#include "midi/juce_MidiMessage.h"
|
||||
#include "midi/juce_MidiBuffer.h"
|
||||
#include "midi/juce_MidiMessageSequence.h"
|
||||
#include "midi/juce_MidiFile.h"
|
||||
#include "midi/juce_MidiKeyboardState.h"
|
||||
#include "midi/juce_MidiRPN.h"
|
||||
#include "midi/juce_MidiDataConcatenator.h"
|
||||
#include "mpe/juce_MPEValue.h"
|
||||
#include "mpe/juce_MPENote.h"
|
||||
#include "mpe/juce_MPEZoneLayout.h"
|
||||
#include "mpe/juce_MPEInstrument.h"
|
||||
#include "mpe/juce_MPEMessages.h"
|
||||
#include "mpe/juce_MPESynthesiserBase.h"
|
||||
#include "mpe/juce_MPESynthesiserVoice.h"
|
||||
#include "mpe/juce_MPESynthesiser.h"
|
||||
#include "mpe/juce_MPEUtils.h"
|
||||
#include "sources/juce_AudioSource.h"
|
||||
#include "sources/juce_PositionableAudioSource.h"
|
||||
#include "sources/juce_BufferingAudioSource.h"
|
||||
#include "sources/juce_ChannelRemappingAudioSource.h"
|
||||
#include "sources/juce_IIRFilterAudioSource.h"
|
||||
#include "sources/juce_MemoryAudioSource.h"
|
||||
#include "sources/juce_MixerAudioSource.h"
|
||||
#include "sources/juce_ResamplingAudioSource.h"
|
||||
#include "sources/juce_ReverbAudioSource.h"
|
||||
#include "sources/juce_ToneGeneratorAudioSource.h"
|
||||
#include "synthesisers/juce_Synthesiser.h"
|
||||
#include "audio_play_head/juce_AudioPlayHead.h"
|
||||
#include "utilities/juce_AudioWorkgroup.h"
|
||||
#include "midi/ump/juce_UMPBytesOnGroup.h"
|
||||
#include "midi/ump/juce_UMPDeviceInfo.h"
|
||||
#include "midi/ump/juce_UMP.h"
|
||||
|
||||
namespace juce
|
||||
{
|
||||
namespace ump = universal_midi_packets;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#include "juce_audio_basics.cpp"
|
||||
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
namespace MidiBufferHelpers
|
||||
{
|
||||
inline int getEventTime (const void* d) noexcept
|
||||
{
|
||||
return readUnaligned<int32> (d);
|
||||
}
|
||||
|
||||
inline uint16 getEventDataSize (const void* d) noexcept
|
||||
{
|
||||
return readUnaligned<uint16> (static_cast<const char*> (d) + sizeof (int32));
|
||||
}
|
||||
|
||||
inline uint16 getEventTotalSize (const void* d) noexcept
|
||||
{
|
||||
return (uint16) (getEventDataSize (d) + sizeof (int32) + sizeof (uint16));
|
||||
}
|
||||
|
||||
static int findActualEventLength (const uint8* data, int maxBytes) noexcept
|
||||
{
|
||||
auto byte = (unsigned int) *data;
|
||||
|
||||
if (byte == 0xf0 || byte == 0xf7)
|
||||
{
|
||||
int i = 1;
|
||||
|
||||
while (i < maxBytes)
|
||||
if (data[i++] == 0xf7)
|
||||
break;
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
if (byte == 0xff)
|
||||
{
|
||||
if (maxBytes == 1)
|
||||
return 1;
|
||||
|
||||
const auto var = MidiMessage::readVariableLengthValue (data + 1, maxBytes - 1);
|
||||
return jmin (maxBytes, var.value + 2 + var.bytesUsed);
|
||||
}
|
||||
|
||||
if (byte >= 0x80)
|
||||
return jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint8* findEventAfter (uint8* d, uint8* endData, int samplePosition) noexcept
|
||||
{
|
||||
while (d < endData && getEventTime (d) <= samplePosition)
|
||||
d += getEventTotalSize (d);
|
||||
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiBufferIterator& MidiBufferIterator::operator++() noexcept
|
||||
{
|
||||
data += sizeof (int32) + sizeof (uint16) + size_t (MidiBufferHelpers::getEventDataSize (data));
|
||||
return *this;
|
||||
}
|
||||
|
||||
MidiBufferIterator MidiBufferIterator::operator++ (int) noexcept
|
||||
{
|
||||
auto copy = *this;
|
||||
++(*this);
|
||||
return copy;
|
||||
}
|
||||
|
||||
MidiBufferIterator::reference MidiBufferIterator::operator*() const noexcept
|
||||
{
|
||||
return { data + sizeof (int32) + sizeof (uint16),
|
||||
MidiBufferHelpers::getEventDataSize (data),
|
||||
MidiBufferHelpers::getEventTime (data) };
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiBuffer::MidiBuffer (const MidiMessage& message) noexcept
|
||||
{
|
||||
addEvent (message, 0);
|
||||
}
|
||||
|
||||
void MidiBuffer::swapWith (MidiBuffer& other) noexcept { data.swapWith (other.data); }
|
||||
void MidiBuffer::clear() noexcept { data.clearQuick(); }
|
||||
void MidiBuffer::ensureSize (size_t minimumNumBytes) { data.ensureStorageAllocated ((int) minimumNumBytes); }
|
||||
bool MidiBuffer::isEmpty() const noexcept { return data.size() == 0; }
|
||||
|
||||
void MidiBuffer::clear (int startSample, int numSamples)
|
||||
{
|
||||
auto start = MidiBufferHelpers::findEventAfter (data.begin(), data.end(), startSample - 1);
|
||||
auto end = MidiBufferHelpers::findEventAfter (start, data.end(), startSample + numSamples - 1);
|
||||
|
||||
data.removeRange ((int) (start - data.begin()), (int) (end - start));
|
||||
}
|
||||
|
||||
bool MidiBuffer::addEvent (const MidiMessage& m, int sampleNumber)
|
||||
{
|
||||
return addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
|
||||
}
|
||||
|
||||
bool MidiBuffer::addEvent (const void* newData, int maxBytes, int sampleNumber)
|
||||
{
|
||||
auto numBytes = MidiBufferHelpers::findActualEventLength (static_cast<const uint8*> (newData), maxBytes);
|
||||
|
||||
if (numBytes <= 0)
|
||||
return true;
|
||||
|
||||
if (std::numeric_limits<uint16>::max() < numBytes)
|
||||
{
|
||||
// This method only supports messages smaller than (1 << 16) bytes
|
||||
return false;
|
||||
}
|
||||
|
||||
auto newItemSize = (size_t) numBytes + sizeof (int32) + sizeof (uint16);
|
||||
auto offset = (int) (MidiBufferHelpers::findEventAfter (data.begin(), data.end(), sampleNumber) - data.begin());
|
||||
|
||||
data.insertMultiple (offset, 0, (int) newItemSize);
|
||||
|
||||
auto* d = data.begin() + offset;
|
||||
writeUnaligned<int32> (d, sampleNumber);
|
||||
d += sizeof (int32);
|
||||
writeUnaligned<uint16> (d, static_cast<uint16> (numBytes));
|
||||
d += sizeof (uint16);
|
||||
memcpy (d, newData, (size_t) numBytes);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
|
||||
int startSample, int numSamples, int sampleDeltaToAdd)
|
||||
{
|
||||
for (auto i = otherBuffer.findNextSamplePosition (startSample); i != otherBuffer.cend(); ++i)
|
||||
{
|
||||
const auto metadata = *i;
|
||||
|
||||
if (metadata.samplePosition >= startSample + numSamples && numSamples >= 0)
|
||||
break;
|
||||
|
||||
addEvent (metadata.data, metadata.numBytes, metadata.samplePosition + sampleDeltaToAdd);
|
||||
}
|
||||
}
|
||||
|
||||
int MidiBuffer::getNumEvents() const noexcept
|
||||
{
|
||||
int n = 0;
|
||||
auto end = data.end();
|
||||
|
||||
for (auto d = data.begin(); d < end; ++n)
|
||||
d += MidiBufferHelpers::getEventTotalSize (d);
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
int MidiBuffer::getFirstEventTime() const noexcept
|
||||
{
|
||||
return data.size() > 0 ? MidiBufferHelpers::getEventTime (data.begin()) : 0;
|
||||
}
|
||||
|
||||
int MidiBuffer::getLastEventTime() const noexcept
|
||||
{
|
||||
if (data.size() == 0)
|
||||
return 0;
|
||||
|
||||
auto endData = data.end();
|
||||
|
||||
for (auto d = data.begin();;)
|
||||
{
|
||||
auto nextOne = d + MidiBufferHelpers::getEventTotalSize (d);
|
||||
|
||||
if (nextOne >= endData)
|
||||
return MidiBufferHelpers::getEventTime (d);
|
||||
|
||||
d = nextOne;
|
||||
}
|
||||
}
|
||||
|
||||
MidiBufferIterator MidiBuffer::findNextSamplePosition (int samplePosition) const noexcept
|
||||
{
|
||||
return std::find_if (cbegin(), cend(), [&] (const MidiMessageMetadata& metadata) noexcept
|
||||
{
|
||||
return metadata.samplePosition >= samplePosition;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
MidiBuffer::Iterator::Iterator (const MidiBuffer& b) noexcept
|
||||
: buffer (b), iterator (b.data.begin())
|
||||
{
|
||||
}
|
||||
|
||||
void MidiBuffer::Iterator::setNextSamplePosition (int samplePosition) noexcept
|
||||
{
|
||||
iterator = buffer.findNextSamplePosition (samplePosition);
|
||||
}
|
||||
|
||||
bool MidiBuffer::Iterator::getNextEvent (const uint8*& midiData, int& numBytes, int& samplePosition) noexcept
|
||||
{
|
||||
if (iterator == buffer.cend())
|
||||
return false;
|
||||
|
||||
const auto metadata = *iterator++;
|
||||
midiData = metadata.data;
|
||||
numBytes = metadata.numBytes;
|
||||
samplePosition = metadata.samplePosition;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) noexcept
|
||||
{
|
||||
if (iterator == buffer.cend())
|
||||
return false;
|
||||
|
||||
const auto metadata = *iterator++;
|
||||
result = metadata.getMessage();
|
||||
samplePosition = metadata.samplePosition;
|
||||
return true;
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
struct MidiBufferTest final : public UnitTest
|
||||
{
|
||||
MidiBufferTest()
|
||||
: UnitTest ("MidiBuffer", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("Clear messages");
|
||||
{
|
||||
const auto message = MidiMessage::noteOn (1, 64, 0.5f);
|
||||
|
||||
const auto testBuffer = [&]
|
||||
{
|
||||
MidiBuffer buffer;
|
||||
buffer.addEvent (message, 0);
|
||||
buffer.addEvent (message, 10);
|
||||
buffer.addEvent (message, 20);
|
||||
buffer.addEvent (message, 30);
|
||||
return buffer;
|
||||
}();
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 0);
|
||||
expectEquals (buffer.getNumEvents(), 4);
|
||||
}
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 1);
|
||||
expectEquals (buffer.getNumEvents(), 3);
|
||||
}
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 10);
|
||||
expectEquals (buffer.getNumEvents(), 3);
|
||||
}
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 20);
|
||||
expectEquals (buffer.getNumEvents(), 2);
|
||||
}
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 30);
|
||||
expectEquals (buffer.getNumEvents(), 1);
|
||||
}
|
||||
|
||||
{
|
||||
auto buffer = testBuffer;
|
||||
buffer.clear (10, 300);
|
||||
expectEquals (buffer.getNumEvents(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MidiBufferTest midiBufferTest;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A view of MIDI message data stored in a contiguous buffer.
|
||||
|
||||
Instances of this class do *not* own the midi data bytes that they point to.
|
||||
Instead, they expect the midi data to live in a separate buffer that outlives
|
||||
the MidiMessageMetadata instance.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct MidiMessageMetadata
|
||||
{
|
||||
MidiMessageMetadata() noexcept = default;
|
||||
|
||||
MidiMessageMetadata (const uint8* dataIn, int numBytesIn, int positionIn) noexcept
|
||||
: data (dataIn), numBytes (numBytesIn), samplePosition (positionIn)
|
||||
{
|
||||
}
|
||||
|
||||
/** Constructs a new MidiMessage instance from the data that this object is viewing.
|
||||
|
||||
Note that MidiMessage owns its data storage, whereas MidiMessageMetadata does not.
|
||||
*/
|
||||
MidiMessage getMessage() const { return MidiMessage (data, numBytes, samplePosition); }
|
||||
|
||||
Span<const std::byte> asSpan() const&
|
||||
{
|
||||
return { reinterpret_cast<const std::byte*> (data), (size_t) numBytes };
|
||||
}
|
||||
|
||||
Span<const std::byte> asSpan() const&& = delete;
|
||||
|
||||
/** Pointer to the first byte of a MIDI message. */
|
||||
const uint8* data = nullptr;
|
||||
|
||||
/** The number of bytes in the MIDI message. */
|
||||
int numBytes = 0;
|
||||
|
||||
/** The MIDI message's timestamp. */
|
||||
int samplePosition = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An iterator to move over contiguous raw MIDI data, which Allows iterating
|
||||
over a MidiBuffer using C++11 range-for syntax.
|
||||
|
||||
In the following example, we log all three-byte messages in a midi buffer.
|
||||
@code
|
||||
void processBlock (AudioBuffer<float>&, MidiBuffer& midiBuffer) override
|
||||
{
|
||||
for (const MidiMessageMetadata metadata : midiBuffer)
|
||||
if (metadata.numBytes == 3)
|
||||
Logger::writeToLog (metadata.getMessage().getDescription());
|
||||
}
|
||||
@endcode
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiBufferIterator
|
||||
{
|
||||
using Ptr = const uint8*;
|
||||
|
||||
public:
|
||||
MidiBufferIterator() = default;
|
||||
|
||||
/** Constructs an iterator pointing at the message starting at the byte `dataIn`.
|
||||
`dataIn` must point to the start of a valid MIDI message. If it does not,
|
||||
calling other member functions on the iterator will result in undefined
|
||||
behaviour.
|
||||
*/
|
||||
explicit MidiBufferIterator (const uint8* dataIn) noexcept
|
||||
: data (dataIn)
|
||||
{
|
||||
}
|
||||
|
||||
using difference_type = std::iterator_traits<Ptr>::difference_type;
|
||||
using value_type = MidiMessageMetadata;
|
||||
using reference = MidiMessageMetadata;
|
||||
using pointer = void;
|
||||
using iterator_category = std::input_iterator_tag;
|
||||
|
||||
/** Make this iterator point to the next message in the buffer. */
|
||||
MidiBufferIterator& operator++() noexcept;
|
||||
|
||||
/** Create a copy of this object, make this iterator point to the next message in
|
||||
the buffer, then return the copy.
|
||||
*/
|
||||
MidiBufferIterator operator++ (int) noexcept;
|
||||
|
||||
/** Return true if this iterator points to the same message as another
|
||||
iterator instance, otherwise return false.
|
||||
*/
|
||||
bool operator== (const MidiBufferIterator& other) const noexcept { return data == other.data; }
|
||||
|
||||
/** Return false if this iterator points to the same message as another
|
||||
iterator instance, otherwise returns true.
|
||||
*/
|
||||
bool operator!= (const MidiBufferIterator& other) const noexcept { return ! operator== (other); }
|
||||
|
||||
/** Return an instance of MidiMessageMetadata which describes the message to which
|
||||
the iterator is currently pointing.
|
||||
*/
|
||||
reference operator*() const noexcept;
|
||||
|
||||
private:
|
||||
Ptr data = nullptr;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a sequence of time-stamped midi events.
|
||||
|
||||
Analogous to the AudioBuffer, this holds a set of midi events with
|
||||
integer time-stamps. The buffer is kept sorted in order of the time-stamps.
|
||||
|
||||
If you're working with a sequence of midi events that may need to be manipulated
|
||||
or read/written to a midi file, then MidiMessageSequence is probably a more
|
||||
appropriate container. MidiBuffer is designed for lower-level streams of raw
|
||||
midi data.
|
||||
|
||||
@see MidiMessage
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiBuffer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty MidiBuffer. */
|
||||
MidiBuffer() noexcept = default;
|
||||
|
||||
/** Creates a MidiBuffer containing a single midi message. */
|
||||
explicit MidiBuffer (const MidiMessage& message) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Removes all events from the buffer. */
|
||||
void clear() noexcept;
|
||||
|
||||
/** Removes all events between two times from the buffer.
|
||||
|
||||
All events for which (start <= event position < start + numSamples) will
|
||||
be removed.
|
||||
*/
|
||||
void clear (int start, int numSamples);
|
||||
|
||||
/** Returns true if the buffer is empty.
|
||||
To actually retrieve the events, use a MidiBufferIterator object
|
||||
*/
|
||||
bool isEmpty() const noexcept;
|
||||
|
||||
/** Counts the number of events in the buffer.
|
||||
|
||||
This is actually quite a slow operation, as it has to iterate through all
|
||||
the events, so you might prefer to call isEmpty() if that's all you need
|
||||
to know.
|
||||
*/
|
||||
int getNumEvents() const noexcept;
|
||||
|
||||
/** Adds an event to the buffer.
|
||||
|
||||
The sample number will be used to determine the position of the event in
|
||||
the buffer, which is always kept sorted. The MidiMessage's timestamp is
|
||||
ignored.
|
||||
|
||||
If an event is added whose sample position is the same as one or more events
|
||||
already in the buffer, the new event will be placed after the existing ones.
|
||||
|
||||
To retrieve events, use a MidiBufferIterator object.
|
||||
|
||||
Returns true on success, or false on failure.
|
||||
*/
|
||||
bool addEvent (const MidiMessage& midiMessage, int sampleNumber);
|
||||
|
||||
/** Adds an event to the buffer from raw midi data.
|
||||
|
||||
The sample number will be used to determine the position of the event in
|
||||
the buffer, which is always kept sorted.
|
||||
|
||||
If an event is added whose sample position is the same as one or more events
|
||||
already in the buffer, the new event will be placed after the existing ones.
|
||||
|
||||
The event data will be inspected to calculate the number of bytes in length that
|
||||
the midi event really takes up, so maxBytesOfMidiData may be longer than the data
|
||||
that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
|
||||
it'll actually only store 3 bytes. If the midi data is invalid, it might not
|
||||
add an event at all.
|
||||
|
||||
To retrieve events, use a MidiBufferIterator object.
|
||||
|
||||
Returns true on success, or false on failure.
|
||||
*/
|
||||
bool addEvent (const void* rawMidiData,
|
||||
int maxBytesOfMidiData,
|
||||
int sampleNumber);
|
||||
|
||||
/** Adds some events from another buffer to this one.
|
||||
|
||||
@param otherBuffer the buffer containing the events you want to add
|
||||
@param startSample the lowest sample number in the source buffer for which
|
||||
events should be added. Any source events whose timestamp is
|
||||
less than this will be ignored
|
||||
@param numSamples the valid range of samples from the source buffer for which
|
||||
events should be added - i.e. events in the source buffer whose
|
||||
timestamp is greater than or equal to (startSample + numSamples)
|
||||
will be ignored. If this value is less than 0, all events after
|
||||
startSample will be taken.
|
||||
@param sampleDeltaToAdd a value which will be added to the source timestamps of the events
|
||||
that are added to this buffer
|
||||
*/
|
||||
void addEvents (const MidiBuffer& otherBuffer,
|
||||
int startSample,
|
||||
int numSamples,
|
||||
int sampleDeltaToAdd);
|
||||
|
||||
/** Returns the sample number of the first event in the buffer.
|
||||
If the buffer's empty, this will just return 0.
|
||||
*/
|
||||
int getFirstEventTime() const noexcept;
|
||||
|
||||
/** Returns the sample number of the last event in the buffer.
|
||||
If the buffer's empty, this will just return 0.
|
||||
*/
|
||||
int getLastEventTime() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Exchanges the contents of this buffer with another one.
|
||||
|
||||
This is a quick operation, because no memory allocating or copying is done, it
|
||||
just swaps the internal state of the two buffers.
|
||||
*/
|
||||
void swapWith (MidiBuffer&) noexcept;
|
||||
|
||||
/** Preallocates some memory for the buffer to use.
|
||||
This helps to avoid needing to reallocate space when the buffer has messages
|
||||
added to it.
|
||||
*/
|
||||
void ensureSize (size_t minimumNumBytes);
|
||||
|
||||
/** Get a read-only iterator pointing to the beginning of this buffer. */
|
||||
MidiBufferIterator begin() const noexcept { return cbegin(); }
|
||||
|
||||
/** Get a read-only iterator pointing one past the end of this buffer. */
|
||||
MidiBufferIterator end() const noexcept { return cend(); }
|
||||
|
||||
/** Get a read-only iterator pointing to the beginning of this buffer. */
|
||||
MidiBufferIterator cbegin() const noexcept { return MidiBufferIterator (data.begin()); }
|
||||
|
||||
/** Get a read-only iterator pointing one past the end of this buffer. */
|
||||
MidiBufferIterator cend() const noexcept { return MidiBufferIterator (data.end()); }
|
||||
|
||||
/** Get an iterator pointing to the first event with a timestamp greater-than or
|
||||
equal-to `samplePosition`.
|
||||
*/
|
||||
MidiBufferIterator findNextSamplePosition (int samplePosition) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
/** This class is now deprecated in favour of MidiBufferIterator.
|
||||
|
||||
Used to iterate through the events in a MidiBuffer.
|
||||
|
||||
Note that altering the buffer while an iterator is using it will produce
|
||||
undefined behaviour.
|
||||
|
||||
@see MidiBuffer
|
||||
*/
|
||||
class [[deprecated]] JUCE_API Iterator
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an Iterator for this MidiBuffer. */
|
||||
Iterator (const MidiBuffer& b) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Repositions the iterator so that the next event retrieved will be the first
|
||||
one whose sample position is at greater than or equal to the given position.
|
||||
*/
|
||||
void setNextSamplePosition (int samplePosition) noexcept;
|
||||
|
||||
/** Retrieves a copy of the next event from the buffer.
|
||||
|
||||
@param result on return, this will be the message. The MidiMessage's timestamp
|
||||
is set to the same value as samplePosition.
|
||||
@param samplePosition on return, this will be the position of the event, as a
|
||||
sample index in the buffer
|
||||
@returns true if an event was found, or false if the iterator has reached
|
||||
the end of the buffer
|
||||
*/
|
||||
bool getNextEvent (MidiMessage& result,
|
||||
int& samplePosition) noexcept;
|
||||
|
||||
/** Retrieves the next event from the buffer.
|
||||
|
||||
@param midiData on return, this pointer will be set to a block of data containing
|
||||
the midi message. Note that to make it fast, this is a pointer
|
||||
directly into the MidiBuffer's internal data, so is only valid
|
||||
temporarily until the MidiBuffer is altered.
|
||||
@param numBytesOfMidiData on return, this is the number of bytes of data used by the
|
||||
midi message
|
||||
@param samplePosition on return, this will be the position of the event, as a
|
||||
sample index in the buffer
|
||||
@returns true if an event was found, or false if the iterator has reached
|
||||
the end of the buffer
|
||||
*/
|
||||
bool getNextEvent (const uint8* &midiData,
|
||||
int& numBytesOfMidiData,
|
||||
int& samplePosition) noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
const MidiBuffer& buffer;
|
||||
MidiBufferIterator iterator;
|
||||
};
|
||||
/** @endcond */
|
||||
|
||||
/** The raw data holding this buffer.
|
||||
Obviously access to this data is provided at your own risk. Its internal format could
|
||||
change in future, so don't write code that relies on it!
|
||||
*/
|
||||
Array<uint8> data;
|
||||
|
||||
private:
|
||||
JUCE_LEAK_DETECTOR (MidiBuffer)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,303 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
enum class SysexExtractorCallbackKind
|
||||
{
|
||||
notSysex,
|
||||
ongoingSysex,
|
||||
lastSysex,
|
||||
};
|
||||
|
||||
class BytestreamSysexExtractor
|
||||
{
|
||||
public:
|
||||
void reset()
|
||||
{
|
||||
state = RunningStatus{};
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
void push (Span<const std::byte> bytes, Callback&& callback)
|
||||
{
|
||||
for (const auto pair : enumerate (bytes, size_t{}))
|
||||
{
|
||||
const auto index = pair.index;
|
||||
const auto byte = pair.value;
|
||||
|
||||
state = std::invoke ([&]() -> State
|
||||
{
|
||||
if (auto* inSysex = std::get_if<InSysex> (&state))
|
||||
{
|
||||
const auto offset = jmin (index, inSysex->numBytes);
|
||||
|
||||
if (byte == std::byte { 0xf0 })
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::lastSysex,
|
||||
Span { bytes.data() + index - offset, offset });
|
||||
return InSysex { 1 };
|
||||
}
|
||||
|
||||
if (byte == std::byte { 0xf7 })
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::lastSysex,
|
||||
Span { bytes.data() + index - offset, offset + 1 });
|
||||
return RunningStatus{};
|
||||
}
|
||||
|
||||
if (isRealtimeMessage (byte))
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::ongoingSysex,
|
||||
Span { bytes.data() + index - offset, offset });
|
||||
callback (SysexExtractorCallbackKind::notSysex,
|
||||
Span { bytes.data() + index, 1 });
|
||||
return InSysex{};
|
||||
}
|
||||
|
||||
if (isStatusByte (byte))
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::lastSysex,
|
||||
Span { bytes.data() + index - offset, offset });
|
||||
return RunningStatus { 1, { byte } };
|
||||
}
|
||||
|
||||
return InSysex { inSysex->numBytes + 1 };
|
||||
}
|
||||
|
||||
if (auto* runningStatus = std::get_if<RunningStatus> (&state))
|
||||
{
|
||||
if (byte == std::byte { 0xf0 })
|
||||
return InSysex { 1 };
|
||||
|
||||
if (isRealtimeMessage (byte))
|
||||
{
|
||||
// Realtime messages don't affect the running status, so return directly
|
||||
// to avoid emitting a stored single-byte message for a second time
|
||||
callback (SysexExtractorCallbackKind::notSysex,
|
||||
Span { bytes.data() + index, 1 });
|
||||
return *runningStatus;
|
||||
}
|
||||
|
||||
const auto nextRunningStatus = std::invoke ([&]
|
||||
{
|
||||
if (isInitialByte (byte))
|
||||
return RunningStatus{}.withAppendedByte (byte);
|
||||
|
||||
if (0 < runningStatus->size && runningStatus->size < runningStatus->data.size())
|
||||
return runningStatus->withAppendedByte (byte);
|
||||
|
||||
// If we get to this branch, we're trying to process a non-status byte
|
||||
// without having seen any previous status byte, so ignore the current byte
|
||||
return RunningStatus{};
|
||||
});
|
||||
|
||||
if (const auto completeMessage = nextRunningStatus.getCompleteMessage(); ! completeMessage.empty())
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::notSysex, completeMessage);
|
||||
return isCommon (nextRunningStatus.data[0])
|
||||
? RunningStatus{}
|
||||
: RunningStatus{}.withAppendedByte (nextRunningStatus.data[0]);
|
||||
}
|
||||
|
||||
return nextRunningStatus;
|
||||
}
|
||||
|
||||
// Can only happen if the variant is valueless by exception, which indicates a much
|
||||
// more severe problem!
|
||||
std::terminate();
|
||||
});
|
||||
}
|
||||
|
||||
if (auto* inSysex = std::get_if<InSysex> (&state))
|
||||
{
|
||||
callback (SysexExtractorCallbackKind::ongoingSysex,
|
||||
Span { bytes.data() + bytes.size() - inSysex->numBytes, inSysex->numBytes });
|
||||
state = InSysex{};
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static bool isRealtimeMessage (std::byte byte) { return std::byte (0xf8) <= byte && byte <= std::byte (0xfe); }
|
||||
static bool isCommon (std::byte byte) { return std::byte (0xf1) <= byte && byte <= std::byte (0xf7); }
|
||||
static bool isStatusByte (std::byte byte) { return std::byte (0x80) <= byte; }
|
||||
static bool isInitialByte (std::byte byte) { return isStatusByte (byte) && byte != std::byte (0xf7); }
|
||||
|
||||
struct InSysex
|
||||
{
|
||||
size_t numBytes{};
|
||||
};
|
||||
|
||||
struct RunningStatus
|
||||
{
|
||||
// These constructors are required to work around a bug in GCC 7
|
||||
RunningStatus() {}
|
||||
|
||||
RunningStatus (uint8_t sizeIn, std::array<std::byte, 3> dataIn)
|
||||
: size (sizeIn), data (dataIn) {}
|
||||
|
||||
uint8_t size{};
|
||||
std::array<std::byte, 3> data{};
|
||||
|
||||
Span<const std::byte> getCompleteMessage() const
|
||||
{
|
||||
if (size == 0)
|
||||
return {};
|
||||
|
||||
const auto expectedSize = MidiMessage::getMessageLengthFromFirstByte ((uint8_t) data[0]);
|
||||
return Span { data.data(), size == expectedSize ? size : (size_t) 0 };
|
||||
}
|
||||
|
||||
void appendByte (std::byte x)
|
||||
{
|
||||
jassert (size < data.size());
|
||||
data[size++] = x;
|
||||
}
|
||||
|
||||
RunningStatus withAppendedByte (std::byte x) const
|
||||
{
|
||||
auto result = *this;
|
||||
result.appendByte (x);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
using State = std::variant<RunningStatus, InSysex>;
|
||||
State state;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helper class that takes chunks of incoming midi bytes, packages them into
|
||||
messages, and dispatches them to a midi callback.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class MidiDataConcatenator
|
||||
{
|
||||
public:
|
||||
MidiDataConcatenator (int initialBufferSize)
|
||||
{
|
||||
pendingSysexData.reserve ((size_t) initialBufferSize);
|
||||
}
|
||||
|
||||
MidiDataConcatenator (MidiDataConcatenator&&) noexcept = default;
|
||||
MidiDataConcatenator& operator= (MidiDataConcatenator&&) noexcept = default;
|
||||
|
||||
void reset()
|
||||
{
|
||||
extractor.reset();
|
||||
pendingSysexData.clear();
|
||||
pendingSysexTime = 0;
|
||||
}
|
||||
|
||||
template <typename UserDataType, typename CallbackType>
|
||||
void pushMidiData (Span<const std::byte> bytes,
|
||||
double time,
|
||||
UserDataType* input,
|
||||
CallbackType& callback)
|
||||
{
|
||||
extractor.push (bytes, [&] (SysexExtractorCallbackKind kind, Span<const std::byte> bytesThisTime)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case SysexExtractorCallbackKind::notSysex:
|
||||
callback.handleIncomingMidiMessage (input,
|
||||
MidiMessage (bytesThisTime.data(),
|
||||
(int) bytesThisTime.size(),
|
||||
time));
|
||||
return;
|
||||
|
||||
case SysexExtractorCallbackKind::ongoingSysex:
|
||||
{
|
||||
if (pendingSysexData.empty())
|
||||
pendingSysexTime = time;
|
||||
|
||||
pendingSysexData.insert (pendingSysexData.end(), bytesThisTime.begin(), bytesThisTime.end());
|
||||
return;
|
||||
}
|
||||
|
||||
case SysexExtractorCallbackKind::lastSysex:
|
||||
{
|
||||
pendingSysexData.insert (pendingSysexData.end(), bytesThisTime.begin(), bytesThisTime.end());
|
||||
|
||||
if (pendingSysexData.empty())
|
||||
{
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
if (pendingSysexData.back() == std::byte { 0xf7 })
|
||||
{
|
||||
callback.handleIncomingMidiMessage (input,
|
||||
MidiMessage (pendingSysexData.data(),
|
||||
(int) pendingSysexData.size(),
|
||||
pendingSysexTime));
|
||||
}
|
||||
else
|
||||
{
|
||||
callback.handlePartialSysexMessage (input,
|
||||
unalignedPointerCast<const uint8*> (pendingSysexData.data()),
|
||||
(int) pendingSysexData.size(),
|
||||
pendingSysexTime);
|
||||
}
|
||||
|
||||
pendingSysexData.clear();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
template <typename UserDataType, typename CallbackType>
|
||||
void pushMidiData (const void* inputData,
|
||||
int numBytes,
|
||||
double time,
|
||||
UserDataType* input,
|
||||
CallbackType& callback)
|
||||
{
|
||||
pushMidiData ({ static_cast<const std::byte*> (inputData), (size_t) numBytes }, time, input, callback);
|
||||
}
|
||||
|
||||
private:
|
||||
BytestreamSysexExtractor extractor;
|
||||
std::vector<std::byte> pendingSysexData;
|
||||
double pendingSysexTime = 0;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,314 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 BytestreamSysexExtractorTest : public UnitTest
|
||||
{
|
||||
public:
|
||||
BytestreamSysexExtractorTest()
|
||||
: UnitTest ("BytestreamSysexExtractor", UnitTestCategories::midi)
|
||||
{
|
||||
}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
testCase ("Passing empty buffer while no message is in progress does nothing", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
bool called = false;
|
||||
extractor.push ({}, [&] (auto&&...) { called = true; });
|
||||
|
||||
expect (! called);
|
||||
});
|
||||
|
||||
testCase ("Passing sysex with no payload reports an empty message", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
bool called = false;
|
||||
const std::byte message[] { std::byte (0xf0), std::byte (0xf7) };
|
||||
extractor.push (message, [&] (auto status, auto bytes)
|
||||
{
|
||||
called = true;
|
||||
expect (status == SysexExtractorCallbackKind::lastSysex);
|
||||
expect (bytes.size() == 2 && bytes[0] == std::byte (0xf0) && bytes[1] == std::byte (0xf7));
|
||||
});
|
||||
|
||||
expect (called);
|
||||
});
|
||||
|
||||
testCase ("Sending only the sysex starting byte reports an ongoing message", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
int numCalls = 0;
|
||||
const std::byte message[] { std::byte (0xf0) };
|
||||
extractor.push (message, [&] (auto status, auto bytes)
|
||||
{
|
||||
++numCalls;
|
||||
expect (status == SysexExtractorCallbackKind::ongoingSysex);
|
||||
expect (bytes.size() == 1 && bytes[0] == std::byte (0xf0));
|
||||
});
|
||||
|
||||
expect (numCalls == 1);
|
||||
|
||||
// Sending a subsequent empty span should report an ongoing message
|
||||
extractor.push (Span<const std::byte>{}, [&] (auto status, auto bytes)
|
||||
{
|
||||
++numCalls;
|
||||
expect (status == SysexExtractorCallbackKind::ongoingSysex);
|
||||
expect (bytes.empty());
|
||||
});
|
||||
|
||||
expect (numCalls == 2);
|
||||
});
|
||||
|
||||
testCase ("Sending sysex interspersed with realtime messages filters out the realtime messages", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xf0),
|
||||
std::byte (0x50), // first data byte
|
||||
std::byte (0xfe), // active sensing
|
||||
std::byte (0x60), // second data byte
|
||||
std::byte (0x70), // third data byte
|
||||
std::byte (0xf7) };
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes) { vectors.emplace_back (bytes.begin(), bytes.end()); });
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xf0), std::byte (0x50) },
|
||||
std::vector { std::byte (0xfe) },
|
||||
std::vector { std::byte (0x60), std::byte (0x70), std::byte (0xf7) } });
|
||||
});
|
||||
|
||||
testCase ("Sending a second f0 byte during an ongoing sysex terminates the previous sysex", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xf0), // start of first sysex
|
||||
std::byte (0x00),
|
||||
std::byte (0x01),
|
||||
std::byte (0xf0), // start of second sysex
|
||||
std::byte (0x02),
|
||||
std::byte (0x03) };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes) { vectors.emplace_back (bytes.begin(), bytes.end()); });
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xf0), std::byte (0x00), std::byte (0x01) },
|
||||
std::vector { std::byte (0xf0), std::byte (0x02), std::byte (0x03) } });
|
||||
});
|
||||
|
||||
testCase ("Status bytes truncate ongoing sysex", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xf0), // start of first sysex
|
||||
std::byte (0x10),
|
||||
std::byte (0x20),
|
||||
std::byte (0x30),
|
||||
std::byte (0x80), // status byte
|
||||
std::byte (0x00),
|
||||
std::byte (0x00) };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes) { vectors.emplace_back (bytes.begin(), bytes.end()); });
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xf0), std::byte (0x10), std::byte (0x20), std::byte (0x30) },
|
||||
std::vector { std::byte (0x80), std::byte (0x00), std::byte (0x00) } });
|
||||
});
|
||||
|
||||
testCase ("Running status is preserved between calls", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0x90), // note on
|
||||
std::byte (0x10),
|
||||
std::byte (0x20),
|
||||
std::byte (0x30),
|
||||
std::byte (0x40),
|
||||
std::byte (0x50) };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
const auto callback = [&] (auto status, auto bytes)
|
||||
{
|
||||
expect (status == SysexExtractorCallbackKind::notSysex);
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
};
|
||||
extractor.push (message, callback);
|
||||
extractor.push (std::array { std::byte (0x60) }, callback);
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0x90), std::byte (0x10), std::byte (0x20) },
|
||||
std::vector { std::byte (0x90), std::byte (0x30), std::byte (0x40) },
|
||||
std::vector { std::byte (0x90), std::byte (0x50), std::byte (0x60) } });
|
||||
});
|
||||
|
||||
testCase ("Realtime messages can intersperse bytes of non-sysex messages", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xd0), // channel pressure
|
||||
std::byte (0xfe), // active sensing
|
||||
std::byte (0x70), // pressure cont.
|
||||
std::byte (0xfe), // active sensing
|
||||
std::byte (0x60), // second pressure message
|
||||
std::byte (0xfe), // active sensing
|
||||
std::byte (0x50) }; // third pressure message
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xfe) },
|
||||
std::vector { std::byte (0xd0), std::byte (0x70) },
|
||||
std::vector { std::byte (0xfe) },
|
||||
std::vector { std::byte (0xd0), std::byte (0x60) },
|
||||
std::vector { std::byte (0xfe) },
|
||||
std::vector { std::byte (0xd0), std::byte (0x50) } });
|
||||
});
|
||||
|
||||
testCase ("Non-status bytes with no associated running status are ignored", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0x10),
|
||||
std::byte (0x2e),
|
||||
std::byte (0x30),
|
||||
std::byte (0x4e),
|
||||
std::byte (0x80), // note off
|
||||
std::byte (0x0e),
|
||||
std::byte (0x00),
|
||||
std::byte (0xf0), // sysex
|
||||
std::byte (0xf7), // end sysex
|
||||
std::byte (0x00), // sysex resets running status
|
||||
std::byte (0x10), };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0x80), std::byte (0x0e), std::byte (0x00) },
|
||||
std::vector { std::byte (0xf0), std::byte (0xf7) } });
|
||||
});
|
||||
|
||||
testCase ("Realtime messages after a single-byte system common message do not repeat it", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xf6),
|
||||
std::byte (0xf8),
|
||||
std::byte (0xfa),
|
||||
std::byte (0xfe) };
|
||||
|
||||
{
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xf6) },
|
||||
std::vector { std::byte (0xf8) },
|
||||
std::vector { std::byte (0xfa) },
|
||||
std::vector { std::byte (0xfe) } });
|
||||
}
|
||||
|
||||
{
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
|
||||
for (const auto byte : message)
|
||||
{
|
||||
const std::byte singleByte[] { byte };
|
||||
extractor.push (singleByte, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
}
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xf6) },
|
||||
std::vector { std::byte (0xf8) },
|
||||
std::vector { std::byte (0xfa) },
|
||||
std::vector { std::byte (0xfe) } });
|
||||
}
|
||||
});
|
||||
|
||||
testCase ("Realtime messages after a system reset message do not repeat it", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0xff),
|
||||
std::byte (0xf8),
|
||||
std::byte (0xfa),
|
||||
std::byte (0xfe) };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
|
||||
expect (vectors == std::vector { std::vector { std::byte (0xff) },
|
||||
std::vector { std::byte (0xf8) },
|
||||
std::vector { std::byte (0xfa) },
|
||||
std::vector { std::byte (0xfe) } });
|
||||
});
|
||||
|
||||
testCase ("System common messages cancel running status", [&]
|
||||
{
|
||||
BytestreamSysexExtractor extractor;
|
||||
const std::byte message[] { std::byte (0x90), // set running status
|
||||
std::byte (0xf8), // realtime byte does no interrupt running status
|
||||
std::byte (0x00),
|
||||
std::byte (0x00),
|
||||
std::byte (0xf3), // system common clears running status
|
||||
std::byte (0x05),
|
||||
std::byte (0x07), // this byte has no status
|
||||
std::byte (0x08), // this byte has no status
|
||||
std::byte (0x90), // set running status
|
||||
std::byte (0x00),
|
||||
std::byte (0x00) };
|
||||
|
||||
std::vector<std::vector<std::byte>> vectors;
|
||||
extractor.push (message, [&] (auto, auto bytes)
|
||||
{
|
||||
vectors.emplace_back (bytes.begin(), bytes.end());
|
||||
});
|
||||
|
||||
expect (vectors == std::vector<std::vector<std::byte>> { std::vector { std::byte (0xf8) },
|
||||
std::vector { std::byte (0x90), std::byte(), std::byte() },
|
||||
std::vector { std::byte (0xf3), std::byte (0x05) },
|
||||
std::vector { std::byte (0x90), std::byte(), std::byte() } });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
static BytestreamSysexExtractorTest bytestreamSysexExtractorTest;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,918 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
namespace MidiFileHelpers
|
||||
{
|
||||
static void writeVariableLengthInt (OutputStream& out, uint32 v)
|
||||
{
|
||||
auto buffer = v & 0x7f;
|
||||
|
||||
while ((v >>= 7) != 0)
|
||||
{
|
||||
buffer <<= 8;
|
||||
buffer |= ((v & 0x7f) | 0x80);
|
||||
}
|
||||
|
||||
for (;;)
|
||||
{
|
||||
out.writeByte ((char) buffer);
|
||||
|
||||
if (buffer & 0x80)
|
||||
buffer >>= 8;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Integral>
|
||||
struct ReadTrait;
|
||||
|
||||
template <>
|
||||
struct ReadTrait<uint32> { static constexpr auto read = ByteOrder::bigEndianInt; };
|
||||
|
||||
template <>
|
||||
struct ReadTrait<uint16> { static constexpr auto read = ByteOrder::bigEndianShort; };
|
||||
|
||||
template <typename Integral>
|
||||
Optional<Integral> tryRead (const uint8*& data, size_t& remaining)
|
||||
{
|
||||
using Trait = ReadTrait<Integral>;
|
||||
constexpr auto size = sizeof (Integral);
|
||||
|
||||
if (remaining < size)
|
||||
return {};
|
||||
|
||||
const Optional<Integral> result { Trait::read (data) };
|
||||
|
||||
data += size;
|
||||
remaining -= size;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
struct HeaderDetails
|
||||
{
|
||||
size_t bytesRead = 0;
|
||||
short timeFormat = 0;
|
||||
short fileType = 0;
|
||||
short numberOfTracks = 0;
|
||||
};
|
||||
|
||||
static Optional<HeaderDetails> parseMidiHeader (const uint8* const initialData,
|
||||
const size_t maxSize)
|
||||
{
|
||||
auto* data = initialData;
|
||||
auto remaining = maxSize;
|
||||
|
||||
auto ch = tryRead<uint32> (data, remaining);
|
||||
|
||||
if (! ch.hasValue())
|
||||
return {};
|
||||
|
||||
if (*ch != ByteOrder::bigEndianInt ("MThd"))
|
||||
{
|
||||
auto ok = false;
|
||||
|
||||
if (*ch == ByteOrder::bigEndianInt ("RIFF"))
|
||||
{
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
ch = tryRead<uint32> (data, remaining);
|
||||
|
||||
if (! ch.hasValue())
|
||||
return {};
|
||||
|
||||
if (*ch == ByteOrder::bigEndianInt ("MThd"))
|
||||
{
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! ok)
|
||||
return {};
|
||||
}
|
||||
|
||||
const auto bytesRemaining = tryRead<uint32> (data, remaining);
|
||||
|
||||
if (! bytesRemaining.hasValue() || *bytesRemaining > remaining)
|
||||
return {};
|
||||
|
||||
const auto optFileType = tryRead<uint16> (data, remaining);
|
||||
|
||||
if (! optFileType.hasValue() || 2 < *optFileType)
|
||||
return {};
|
||||
|
||||
const auto optNumTracks = tryRead<uint16> (data, remaining);
|
||||
|
||||
if (! optNumTracks.hasValue() || (*optFileType == 0 && *optNumTracks != 1))
|
||||
return {};
|
||||
|
||||
const auto optTimeFormat = tryRead<uint16> (data, remaining);
|
||||
|
||||
if (! optTimeFormat.hasValue())
|
||||
return {};
|
||||
|
||||
HeaderDetails result;
|
||||
|
||||
result.fileType = (short) *optFileType;
|
||||
result.timeFormat = (short) *optTimeFormat;
|
||||
result.numberOfTracks = (short) *optNumTracks;
|
||||
result.bytesRead = maxSize - remaining;
|
||||
|
||||
return { result };
|
||||
}
|
||||
|
||||
static double convertTicksToSeconds (double time,
|
||||
const MidiMessageSequence& tempoEvents,
|
||||
int timeFormat)
|
||||
{
|
||||
if (timeFormat < 0)
|
||||
return time / (-(timeFormat >> 8) * (timeFormat & 0xff));
|
||||
|
||||
double lastTime = 0, correctedTime = 0;
|
||||
auto tickLen = 1.0 / (timeFormat & 0x7fff);
|
||||
auto secsPerTick = 0.5 * tickLen;
|
||||
auto numEvents = tempoEvents.getNumEvents();
|
||||
|
||||
for (int i = 0; i < numEvents; ++i)
|
||||
{
|
||||
auto& m = tempoEvents.getEventPointer (i)->message;
|
||||
auto eventTime = m.getTimeStamp();
|
||||
|
||||
if (eventTime >= time)
|
||||
break;
|
||||
|
||||
correctedTime += (eventTime - lastTime) * secsPerTick;
|
||||
lastTime = eventTime;
|
||||
|
||||
if (m.isTempoMetaEvent())
|
||||
secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
|
||||
|
||||
while (i + 1 < numEvents)
|
||||
{
|
||||
auto& m2 = tempoEvents.getEventPointer (i + 1)->message;
|
||||
|
||||
if (! approximatelyEqual (m2.getTimeStamp(), eventTime))
|
||||
break;
|
||||
|
||||
if (m2.isTempoMetaEvent())
|
||||
secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
|
||||
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
return correctedTime + (time - lastTime) * secsPerTick;
|
||||
}
|
||||
|
||||
template <typename MethodType>
|
||||
static void findAllMatchingEvents (const OwnedArray<MidiMessageSequence>& tracks,
|
||||
MidiMessageSequence& results,
|
||||
MethodType method)
|
||||
{
|
||||
for (auto* track : tracks)
|
||||
{
|
||||
auto numEvents = track->getNumEvents();
|
||||
|
||||
for (int j = 0; j < numEvents; ++j)
|
||||
{
|
||||
auto& m = track->getEventPointer (j)->message;
|
||||
|
||||
if ((m.*method)())
|
||||
results.addEvent (m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static MidiMessageSequence readTrack (const uint8* data, int size)
|
||||
{
|
||||
double time = 0;
|
||||
uint8 lastStatusByte = 0;
|
||||
|
||||
MidiMessageSequence result;
|
||||
|
||||
while (size > 0)
|
||||
{
|
||||
const auto delay = MidiMessage::readVariableLengthValue (data, (int) size);
|
||||
|
||||
if (! delay.isValid())
|
||||
break;
|
||||
|
||||
data += delay.bytesUsed;
|
||||
size -= delay.bytesUsed;
|
||||
time += delay.value;
|
||||
|
||||
if (size <= 0)
|
||||
break;
|
||||
|
||||
int messSize = 0;
|
||||
const MidiMessage mm (data, size, messSize, lastStatusByte, time);
|
||||
|
||||
if (messSize <= 0)
|
||||
break;
|
||||
|
||||
size -= messSize;
|
||||
data += messSize;
|
||||
|
||||
result.addEvent (mm);
|
||||
|
||||
auto firstByte = *(mm.getRawData());
|
||||
|
||||
if ((firstByte & 0xf0) != 0xf0)
|
||||
lastStatusByte = firstByte;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiFile::MidiFile() : timeFormat ((short) (unsigned short) 0xe728) {}
|
||||
|
||||
MidiFile::MidiFile (const MidiFile& other) : timeFormat (other.timeFormat)
|
||||
{
|
||||
tracks.addCopiesOf (other.tracks);
|
||||
}
|
||||
|
||||
MidiFile& MidiFile::operator= (const MidiFile& other)
|
||||
{
|
||||
tracks.clear();
|
||||
tracks.addCopiesOf (other.tracks);
|
||||
timeFormat = other.timeFormat;
|
||||
return *this;
|
||||
}
|
||||
|
||||
MidiFile::MidiFile (MidiFile&& other)
|
||||
: tracks (std::move (other.tracks)),
|
||||
timeFormat (other.timeFormat)
|
||||
{
|
||||
}
|
||||
|
||||
MidiFile& MidiFile::operator= (MidiFile&& other)
|
||||
{
|
||||
tracks = std::move (other.tracks);
|
||||
timeFormat = other.timeFormat;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void MidiFile::clear()
|
||||
{
|
||||
tracks.clear();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
int MidiFile::getNumTracks() const noexcept
|
||||
{
|
||||
return tracks.size();
|
||||
}
|
||||
|
||||
const MidiMessageSequence* MidiFile::getTrack (int index) const noexcept
|
||||
{
|
||||
return tracks[index];
|
||||
}
|
||||
|
||||
void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
|
||||
{
|
||||
tracks.add (new MidiMessageSequence (trackSequence));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
short MidiFile::getTimeFormat() const noexcept
|
||||
{
|
||||
return timeFormat;
|
||||
}
|
||||
|
||||
void MidiFile::setTicksPerQuarterNote (int ticks) noexcept
|
||||
{
|
||||
timeFormat = (short) ticks;
|
||||
}
|
||||
|
||||
void MidiFile::setSmpteTimeFormat (int framesPerSecond, int subframeResolution) noexcept
|
||||
{
|
||||
timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiFile::findAllTempoEvents (MidiMessageSequence& results) const
|
||||
{
|
||||
MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTempoMetaEvent);
|
||||
}
|
||||
|
||||
void MidiFile::findAllTimeSigEvents (MidiMessageSequence& results) const
|
||||
{
|
||||
MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTimeSignatureMetaEvent);
|
||||
}
|
||||
|
||||
void MidiFile::findAllKeySigEvents (MidiMessageSequence& results) const
|
||||
{
|
||||
MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isKeySignatureMetaEvent);
|
||||
}
|
||||
|
||||
double MidiFile::getLastTimestamp() const
|
||||
{
|
||||
double t = 0.0;
|
||||
|
||||
for (auto* ms : tracks)
|
||||
t = jmax (t, ms->getEndTime());
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MidiFile::readFrom (InputStream& sourceStream,
|
||||
bool createMatchingNoteOffs,
|
||||
int* fileType)
|
||||
{
|
||||
clear();
|
||||
MemoryBlock data;
|
||||
|
||||
const int maxSensibleMidiFileSize = 200 * 1024 * 1024;
|
||||
|
||||
// (put a sanity-check on the file size, as midi files are generally small)
|
||||
if (! sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
|
||||
return false;
|
||||
|
||||
auto size = data.getSize();
|
||||
auto d = static_cast<const uint8*> (data.getData());
|
||||
|
||||
const auto optHeader = MidiFileHelpers::parseMidiHeader (d, size);
|
||||
|
||||
if (! optHeader.hasValue())
|
||||
return false;
|
||||
|
||||
const auto header = *optHeader;
|
||||
timeFormat = header.timeFormat;
|
||||
|
||||
d += header.bytesRead;
|
||||
size -= (size_t) header.bytesRead;
|
||||
|
||||
for (int track = 0; track < header.numberOfTracks; ++track)
|
||||
{
|
||||
const auto optChunkType = MidiFileHelpers::tryRead<uint32> (d, size);
|
||||
|
||||
if (! optChunkType.hasValue())
|
||||
return false;
|
||||
|
||||
const auto optChunkSize = MidiFileHelpers::tryRead<uint32> (d, size);
|
||||
|
||||
if (! optChunkSize.hasValue())
|
||||
return false;
|
||||
|
||||
const auto chunkSize = *optChunkSize;
|
||||
|
||||
if (size < chunkSize)
|
||||
return false;
|
||||
|
||||
if (*optChunkType == ByteOrder::bigEndianInt ("MTrk"))
|
||||
readNextTrack (d, (int) chunkSize, createMatchingNoteOffs);
|
||||
|
||||
size -= chunkSize;
|
||||
d += chunkSize;
|
||||
}
|
||||
|
||||
const auto successful = (size == 0);
|
||||
|
||||
if (successful && fileType != nullptr)
|
||||
*fileType = header.fileType;
|
||||
|
||||
return successful;
|
||||
}
|
||||
|
||||
template <typename It>
|
||||
static void reorderNoteOnsAfterNoteOffs (const It begin, const It end)
|
||||
{
|
||||
for (auto it = begin; it != end;)
|
||||
{
|
||||
const auto firstNoteOn = std::find_if (it, end, [] (const auto& x)
|
||||
{
|
||||
return x->message.isNoteOn();
|
||||
});
|
||||
|
||||
if (firstNoteOn == end)
|
||||
return;
|
||||
|
||||
const auto channel = (*firstNoteOn)->message.getChannel();
|
||||
const auto noteNumber = (*firstNoteOn)->message.getNoteNumber();
|
||||
const auto rEnd = std::make_reverse_iterator (firstNoteOn);
|
||||
const auto lastNoteOff = std::find_if (std::make_reverse_iterator (end), rEnd, [&] (const auto& x)
|
||||
{
|
||||
return x->message.getChannel() == channel
|
||||
&& x->message.getNoteNumber() == noteNumber
|
||||
&& x->message.isNoteOff();
|
||||
});
|
||||
|
||||
if (lastNoteOff == rEnd)
|
||||
return;
|
||||
|
||||
std::iter_swap (firstNoteOn, std::prev (lastNoteOff.base()));
|
||||
|
||||
it = std::next (firstNoteOn);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiFile::readNextTrack (const uint8* data, int size, bool createMatchingNoteOffs)
|
||||
{
|
||||
auto sequence = MidiFileHelpers::readTrack (data, size);
|
||||
sequence.sort();
|
||||
|
||||
for (auto it = sequence.begin(); it != sequence.end();)
|
||||
{
|
||||
const auto stamp = (*it)->message.getTimeStamp();
|
||||
const auto nextTime = std::find_if (it, sequence.end(), [stamp] (const auto& x)
|
||||
{
|
||||
return ! exactlyEqual (x->message.getTimeStamp(), stamp);
|
||||
});
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (it, nextTime);
|
||||
|
||||
it = nextTime;
|
||||
}
|
||||
|
||||
if (createMatchingNoteOffs)
|
||||
sequence.updateMatchedPairs();
|
||||
|
||||
addTrack (sequence);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiFile::convertTimestampTicksToSeconds()
|
||||
{
|
||||
MidiMessageSequence tempoEvents;
|
||||
findAllTempoEvents (tempoEvents);
|
||||
findAllTimeSigEvents (tempoEvents);
|
||||
|
||||
if (timeFormat != 0)
|
||||
{
|
||||
for (auto* ms : tracks)
|
||||
{
|
||||
for (int j = ms->getNumEvents(); --j >= 0;)
|
||||
{
|
||||
auto& m = ms->getEventPointer (j)->message;
|
||||
m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(), tempoEvents, timeFormat));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MidiFile::writeTo (OutputStream& out, int midiFileType) const
|
||||
{
|
||||
jassert (midiFileType >= 0 && midiFileType <= 2);
|
||||
|
||||
if (! out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"))) return false;
|
||||
if (! out.writeIntBigEndian (6)) return false;
|
||||
if (! out.writeShortBigEndian ((short) midiFileType)) return false;
|
||||
if (! out.writeShortBigEndian ((short) tracks.size())) return false;
|
||||
if (! out.writeShortBigEndian (timeFormat)) return false;
|
||||
|
||||
for (auto* ms : tracks)
|
||||
if (! writeTrack (out, *ms))
|
||||
return false;
|
||||
|
||||
out.flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MidiFile::writeTrack (OutputStream& mainOut, const MidiMessageSequence& ms) const
|
||||
{
|
||||
MemoryOutputStream out;
|
||||
|
||||
int lastTick = 0;
|
||||
uint8 lastStatusByte = 0;
|
||||
bool endOfTrackEventWritten = false;
|
||||
|
||||
for (int i = 0; i < ms.getNumEvents(); ++i)
|
||||
{
|
||||
auto& mm = ms.getEventPointer (i)->message;
|
||||
|
||||
if (mm.isEndOfTrackMetaEvent())
|
||||
endOfTrackEventWritten = true;
|
||||
|
||||
auto tick = roundToInt (mm.getTimeStamp());
|
||||
auto delta = jmax (0, tick - lastTick);
|
||||
MidiFileHelpers::writeVariableLengthInt (out, (uint32) delta);
|
||||
lastTick = tick;
|
||||
|
||||
auto* data = mm.getRawData();
|
||||
auto dataSize = mm.getRawDataSize();
|
||||
auto statusByte = data[0];
|
||||
|
||||
if (statusByte == lastStatusByte
|
||||
&& (statusByte & 0xf0) != 0xf0
|
||||
&& dataSize > 1
|
||||
&& i > 0)
|
||||
{
|
||||
++data;
|
||||
--dataSize;
|
||||
}
|
||||
else if (statusByte == 0xf0) // Write sysex message with length bytes.
|
||||
{
|
||||
out.writeByte ((char) statusByte);
|
||||
|
||||
++data;
|
||||
--dataSize;
|
||||
|
||||
MidiFileHelpers::writeVariableLengthInt (out, (uint32) dataSize);
|
||||
}
|
||||
|
||||
out.write (data, (size_t) dataSize);
|
||||
lastStatusByte = statusByte;
|
||||
}
|
||||
|
||||
if (! endOfTrackEventWritten)
|
||||
{
|
||||
out.writeByte (0); // (tick delta)
|
||||
auto m = MidiMessage::endOfTrack();
|
||||
out.write (m.getRawData(), (size_t) m.getRawDataSize());
|
||||
}
|
||||
|
||||
if (! mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"))) return false;
|
||||
if (! mainOut.writeIntBigEndian ((int) out.getDataSize())) return false;
|
||||
|
||||
mainOut << out;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
struct MidiFileTest final : public UnitTest
|
||||
{
|
||||
MidiFileTest()
|
||||
: UnitTest ("MidiFile", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("ReadTrack respects running status");
|
||||
{
|
||||
const auto sequence = parseSequence ([] (OutputStream& os)
|
||||
{
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 100);
|
||||
writeBytes (os, { 0x90, 0x40, 0x40 });
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 200);
|
||||
writeBytes (os, { 0x40, 0x40 });
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 300);
|
||||
writeBytes (os, { 0xff, 0x2f, 0x00 });
|
||||
});
|
||||
|
||||
expectEquals (sequence.getNumEvents(), 3);
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (2)->message.isEndOfTrackMetaEvent());
|
||||
}
|
||||
|
||||
beginTest ("ReadTrack returns available messages if input is truncated");
|
||||
{
|
||||
{
|
||||
const auto sequence = parseSequence ([] (OutputStream& os)
|
||||
{
|
||||
// Incomplete delta time
|
||||
writeBytes (os, { 0xff });
|
||||
});
|
||||
|
||||
expectEquals (sequence.getNumEvents(), 0);
|
||||
}
|
||||
|
||||
{
|
||||
const auto sequence = parseSequence ([] (OutputStream& os)
|
||||
{
|
||||
// Complete delta with no following event
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 0xffff);
|
||||
});
|
||||
|
||||
expectEquals (sequence.getNumEvents(), 0);
|
||||
}
|
||||
|
||||
{
|
||||
const auto sequence = parseSequence ([] (OutputStream& os)
|
||||
{
|
||||
// Complete delta with malformed following event
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 0xffff);
|
||||
writeBytes (os, { 0x90, 0x40 });
|
||||
});
|
||||
|
||||
expectEquals (sequence.getNumEvents(), 1);
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOff());
|
||||
expectEquals (sequence.getEventPointer (0)->message.getNoteNumber(), 0x40);
|
||||
expectEquals (sequence.getEventPointer (0)->message.getVelocity(), (uint8) 0x00);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Header parsing works");
|
||||
{
|
||||
{
|
||||
// No data
|
||||
const auto header = parseHeader ([] (OutputStream&) {});
|
||||
expect (! header.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Invalid initial byte
|
||||
const auto header = parseHeader ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 0xff });
|
||||
});
|
||||
|
||||
expect (! header.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Type block, but no header data
|
||||
const auto header = parseHeader ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd' });
|
||||
});
|
||||
|
||||
expect (! header.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// We (ll-formed header, but track type is 0 and channels != 1
|
||||
const auto header = parseHeader ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 0, 0, 16, 0, 1 });
|
||||
});
|
||||
|
||||
expect (! header.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Well-formed header, but track type is 5
|
||||
const auto header = parseHeader ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 5, 0, 16, 0, 1 });
|
||||
});
|
||||
|
||||
expect (! header.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Well-formed header
|
||||
const auto header = parseHeader ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 16, 0, 1 });
|
||||
});
|
||||
|
||||
expect (header.hasValue());
|
||||
|
||||
expectEquals (header->fileType, (short) 1);
|
||||
expectEquals (header->numberOfTracks, (short) 16);
|
||||
expectEquals (header->timeFormat, (short) 1);
|
||||
expectEquals ((int) header->bytesRead, 14);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Read from stream");
|
||||
{
|
||||
{
|
||||
// Empty input
|
||||
const auto file = parseFile ([] (OutputStream&) {});
|
||||
expect (! file.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Malformed header
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd' });
|
||||
});
|
||||
|
||||
expect (! file.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Header, no channels
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 0, 0, 1 });
|
||||
});
|
||||
|
||||
expect (file.hasValue());
|
||||
expectEquals (file->getNumTracks(), 0);
|
||||
}
|
||||
|
||||
{
|
||||
// Header, one malformed channel
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
|
||||
writeBytes (os, { 'M', 'T', 'r', '?' });
|
||||
});
|
||||
|
||||
expect (! file.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Header, one channel with malformed message
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
|
||||
writeBytes (os, { 'M', 'T', 'r', 'k', 0, 0, 0, 1, 0xff });
|
||||
});
|
||||
|
||||
expect (file.hasValue());
|
||||
expectEquals (file->getNumTracks(), 1);
|
||||
expectEquals (file->getTrack (0)->getNumEvents(), 0);
|
||||
}
|
||||
|
||||
{
|
||||
// Header, one channel with incorrect length message
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
|
||||
writeBytes (os, { 'M', 'T', 'r', 'k', 0x0f, 0, 0, 0, 0xff });
|
||||
});
|
||||
|
||||
expect (! file.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
// Header, one channel, all well-formed
|
||||
const auto file = parseFile ([] (OutputStream& os)
|
||||
{
|
||||
writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
|
||||
writeBytes (os, { 'M', 'T', 'r', 'k', 0, 0, 0, 4 });
|
||||
|
||||
MidiFileHelpers::writeVariableLengthInt (os, 0x0f);
|
||||
writeBytes (os, { 0x80, 0x00, 0x00 });
|
||||
});
|
||||
|
||||
expect (file.hasValue());
|
||||
expectEquals (file->getNumTracks(), 1);
|
||||
|
||||
auto& track = *file->getTrack (0);
|
||||
expectEquals (track.getNumEvents(), 1);
|
||||
expect (track.getEventPointer (0)->message.isNoteOff());
|
||||
expectEquals (track.getEventPointer (0)->message.getTimeStamp(), (double) 0x0f);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Reorder note on/off");
|
||||
{
|
||||
// Note off before note on does not get reordered
|
||||
{
|
||||
const auto channel = 1;
|
||||
const auto noteNumber = 64;
|
||||
MidiMessageSequence sequence;
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, noteNumber).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, noteNumber, 0.5f).withTimeStamp (0));
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (sequence.begin(), sequence.end());
|
||||
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOff());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOn());
|
||||
}
|
||||
|
||||
// Note on before note off gets swapped
|
||||
{
|
||||
const auto channel = 1;
|
||||
const auto noteNumber = 64;
|
||||
MidiMessageSequence sequence;
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, noteNumber, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, noteNumber).withTimeStamp (0));
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (sequence.begin(), sequence.end());
|
||||
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOff());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOn());
|
||||
}
|
||||
|
||||
// Note on before note off is not swapped if note numbers differ
|
||||
{
|
||||
const auto channel = 1;
|
||||
MidiMessageSequence sequence;
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, 64, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, 65).withTimeStamp (0));
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (sequence.begin(), sequence.end());
|
||||
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOff());
|
||||
}
|
||||
|
||||
// Note on before note off is not swapped if channel numbers differ
|
||||
{
|
||||
const auto noteNumber = 64;
|
||||
MidiMessageSequence sequence;
|
||||
sequence.addEvent (MidiMessage::noteOn (1, noteNumber, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (2, noteNumber).withTimeStamp (0));
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (sequence.begin(), sequence.end());
|
||||
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOff());
|
||||
}
|
||||
|
||||
// If there are several note ons/offs, all offs come before all ons
|
||||
{
|
||||
const auto channel = 1;
|
||||
const auto noteNumber = 64;
|
||||
MidiMessageSequence sequence;
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, noteNumber, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, noteNumber).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, noteNumber, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, noteNumber).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOn (channel, noteNumber, 0.5f).withTimeStamp (0));
|
||||
sequence.addEvent (MidiMessage::noteOff (channel, noteNumber).withTimeStamp (0));
|
||||
|
||||
reorderNoteOnsAfterNoteOffs (sequence.begin(), sequence.end());
|
||||
|
||||
expect (sequence.getEventPointer (0)->message.isNoteOff());
|
||||
expect (sequence.getEventPointer (1)->message.isNoteOff());
|
||||
expect (sequence.getEventPointer (2)->message.isNoteOff());
|
||||
|
||||
expect (sequence.getEventPointer (3)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (4)->message.isNoteOn());
|
||||
expect (sequence.getEventPointer (5)->message.isNoteOn());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static MidiMessageSequence parseSequence (Fn&& fn)
|
||||
{
|
||||
MemoryOutputStream os;
|
||||
fn (os);
|
||||
|
||||
return MidiFileHelpers::readTrack (reinterpret_cast<const uint8*> (os.getData()),
|
||||
(int) os.getDataSize());
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static Optional<MidiFileHelpers::HeaderDetails> parseHeader (Fn&& fn)
|
||||
{
|
||||
MemoryOutputStream os;
|
||||
fn (os);
|
||||
|
||||
return MidiFileHelpers::parseMidiHeader (reinterpret_cast<const uint8*> (os.getData()),
|
||||
os.getDataSize());
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static Optional<MidiFile> parseFile (Fn&& fn)
|
||||
{
|
||||
MemoryOutputStream os;
|
||||
fn (os);
|
||||
|
||||
MemoryInputStream is (os.getData(), os.getDataSize(), false);
|
||||
MidiFile mf;
|
||||
|
||||
int fileType = 0;
|
||||
|
||||
if (mf.readFrom (is, true, &fileType))
|
||||
return mf;
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
static void writeBytes (OutputStream& os, const std::vector<uint8>& bytes)
|
||||
{
|
||||
for (const auto& byte : bytes)
|
||||
os.writeByte ((char) byte);
|
||||
}
|
||||
};
|
||||
|
||||
static MidiFileTest midiFileTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Reads/writes standard midi format files.
|
||||
|
||||
To read a midi file, create a MidiFile object and call its readFrom() method. You
|
||||
can then get the individual midi tracks from it using the getTrack() method.
|
||||
|
||||
To write a file, create a MidiFile object, add some MidiMessageSequence objects
|
||||
to it using the addTrack() method, and then call its writeTo() method to stream
|
||||
it out.
|
||||
|
||||
@see MidiMessageSequence
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiFile
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty MidiFile object. */
|
||||
MidiFile();
|
||||
|
||||
/** Creates a copy of another MidiFile. */
|
||||
MidiFile (const MidiFile&);
|
||||
|
||||
/** Copies from another MidiFile object */
|
||||
MidiFile& operator= (const MidiFile&);
|
||||
|
||||
/** Creates a copy of another MidiFile. */
|
||||
MidiFile (MidiFile&&);
|
||||
|
||||
/** Copies from another MidiFile object */
|
||||
MidiFile& operator= (MidiFile&&);
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of tracks in the file.
|
||||
@see getTrack, addTrack
|
||||
*/
|
||||
int getNumTracks() const noexcept;
|
||||
|
||||
/** Returns a pointer to one of the tracks in the file.
|
||||
@returns a pointer to the track, or nullptr if the index is out-of-range
|
||||
@see getNumTracks, addTrack
|
||||
*/
|
||||
const MidiMessageSequence* getTrack (int index) const noexcept;
|
||||
|
||||
/** Adds a midi track to the file.
|
||||
This will make its own internal copy of the sequence that is passed-in.
|
||||
@see getNumTracks, getTrack
|
||||
*/
|
||||
void addTrack (const MidiMessageSequence& trackSequence);
|
||||
|
||||
/** Removes all midi tracks from the file.
|
||||
@see getNumTracks
|
||||
*/
|
||||
void clear();
|
||||
|
||||
/** Returns the raw time format code that will be written to a stream.
|
||||
|
||||
After reading a midi file, this method will return the time-format that
|
||||
was read from the file's header. It can be changed using the setTicksPerQuarterNote()
|
||||
or setSmpteTimeFormat() methods.
|
||||
|
||||
If the value returned is positive, it indicates the number of midi ticks
|
||||
per quarter-note - see setTicksPerQuarterNote().
|
||||
|
||||
It it's negative, the upper byte indicates the frames-per-second (but negative), and
|
||||
the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
|
||||
*/
|
||||
short getTimeFormat() const noexcept;
|
||||
|
||||
/** Sets the time format to use when this file is written to a stream.
|
||||
|
||||
If this is called, the file will be written as bars/beats using the
|
||||
specified resolution, rather than SMPTE absolute times, as would be
|
||||
used if setSmpteTimeFormat() had been called instead.
|
||||
|
||||
@param ticksPerQuarterNote e.g. 96, 960
|
||||
@see setSmpteTimeFormat
|
||||
*/
|
||||
void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
|
||||
|
||||
/** Sets the time format to use when this file is written to a stream.
|
||||
|
||||
If this is called, the file will be written using absolute times, rather
|
||||
than bars/beats as would be the case if setTicksPerBeat() had been called
|
||||
instead.
|
||||
|
||||
@param framesPerSecond must be 24, 25, 29 or 30
|
||||
@param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
|
||||
8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
|
||||
timing, setSmpteTimeFormat (25, 40)
|
||||
@see setTicksPerBeat
|
||||
*/
|
||||
void setSmpteTimeFormat (int framesPerSecond,
|
||||
int subframeResolution) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
|
||||
Useful for finding the positions of all the tempo changes in a file.
|
||||
@param tempoChangeEvents a list to which all the events will be added
|
||||
*/
|
||||
void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
|
||||
|
||||
/** Makes a list of all the time-signature meta-events from all tracks in the midi file.
|
||||
Useful for finding the positions of all the tempo changes in a file.
|
||||
@param timeSigEvents a list to which all the events will be added
|
||||
*/
|
||||
void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
|
||||
|
||||
/** Makes a list of all the key-signature meta-events from all tracks in the midi file.
|
||||
@param keySigEvents a list to which all the events will be added
|
||||
*/
|
||||
void findAllKeySigEvents (MidiMessageSequence& keySigEvents) const;
|
||||
|
||||
/** Returns the latest timestamp in any of the tracks.
|
||||
(Useful for finding the length of the file).
|
||||
*/
|
||||
double getLastTimestamp() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Reads a midi file format stream.
|
||||
|
||||
After calling this, you can get the tracks that were read from the file by using the
|
||||
getNumTracks() and getTrack() methods.
|
||||
|
||||
The timestamps of the midi events in the tracks will represent their positions in
|
||||
terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
|
||||
method.
|
||||
|
||||
@param sourceStream the source stream
|
||||
@param createMatchingNoteOffs if true, any missing note-offs for previous note-ons will
|
||||
be automatically added at the end of the file by calling
|
||||
MidiMessageSequence::updateMatchedPairs on each track.
|
||||
@param midiFileType if not nullptr, the integer at this address will be set
|
||||
to 0, 1, or 2 depending on the type of the midi file
|
||||
|
||||
@returns true if the stream was read successfully
|
||||
*/
|
||||
bool readFrom (InputStream& sourceStream,
|
||||
bool createMatchingNoteOffs = true,
|
||||
int* midiFileType = nullptr);
|
||||
|
||||
/** Writes the midi tracks as a standard midi file.
|
||||
The midiFileType value is written as the file's format type, which can be 0, 1
|
||||
or 2 - see the midi file spec for more info about that.
|
||||
|
||||
@param destStream the destination stream
|
||||
@param midiFileType the type of midi file
|
||||
|
||||
@returns true if the operation succeeded.
|
||||
*/
|
||||
bool writeTo (OutputStream& destStream, int midiFileType = 1) const;
|
||||
|
||||
/** Converts the timestamp of all the midi events from midi ticks to seconds.
|
||||
|
||||
This will use the midi time format and tempo/time signature info in the
|
||||
tracks to convert all the timestamps to absolute values in seconds.
|
||||
*/
|
||||
void convertTimestampTicksToSeconds();
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
OwnedArray<MidiMessageSequence> tracks;
|
||||
short timeFormat;
|
||||
|
||||
void readNextTrack (const uint8*, int, bool);
|
||||
bool writeTrack (OutputStream&, const MidiMessageSequence&) const;
|
||||
|
||||
JUCE_LEAK_DETECTOR (MidiFile)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MidiKeyboardState::MidiKeyboardState()
|
||||
{
|
||||
zerostruct (noteStates);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiKeyboardState::reset()
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
zerostruct (noteStates);
|
||||
eventsToAdd.clear();
|
||||
}
|
||||
|
||||
bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const noexcept
|
||||
{
|
||||
jassert (midiChannel > 0 && midiChannel <= 16);
|
||||
|
||||
return isPositiveAndBelow (n, 128)
|
||||
&& (noteStates[n] & (1 << (midiChannel - 1))) != 0;
|
||||
}
|
||||
|
||||
bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const noexcept
|
||||
{
|
||||
return isPositiveAndBelow (n, 128)
|
||||
&& (noteStates[n] & midiChannelMask) != 0;
|
||||
}
|
||||
|
||||
void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
|
||||
{
|
||||
jassert (midiChannel > 0 && midiChannel <= 16);
|
||||
jassert (isPositiveAndBelow (midiNoteNumber, 128));
|
||||
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (isPositiveAndBelow (midiNoteNumber, 128))
|
||||
{
|
||||
const int timeNow = (int) Time::getMillisecondCounter();
|
||||
eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
|
||||
eventsToAdd.clear (0, timeNow - 500);
|
||||
|
||||
noteOnInternal (midiChannel, midiNoteNumber, velocity);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
|
||||
{
|
||||
if (isPositiveAndBelow (midiNoteNumber, 128))
|
||||
{
|
||||
noteStates[midiNoteNumber] = static_cast<uint16> (noteStates[midiNoteNumber] | (1 << (midiChannel - 1)));
|
||||
listeners.call ([&] (Listener& l) { l.handleNoteOn (this, midiChannel, midiNoteNumber, velocity); });
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber, const float velocity)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (isNoteOn (midiChannel, midiNoteNumber))
|
||||
{
|
||||
const int timeNow = (int) Time::getMillisecondCounter();
|
||||
eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
|
||||
eventsToAdd.clear (0, timeNow - 500);
|
||||
|
||||
noteOffInternal (midiChannel, midiNoteNumber, velocity);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
|
||||
{
|
||||
if (isNoteOn (midiChannel, midiNoteNumber))
|
||||
{
|
||||
noteStates[midiNoteNumber] = static_cast<uint16> (noteStates[midiNoteNumber] & ~(1 << (midiChannel - 1)));
|
||||
listeners.call ([&] (Listener& l) { l.handleNoteOff (this, midiChannel, midiNoteNumber, velocity); });
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::allNotesOff (const int midiChannel)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (midiChannel <= 0)
|
||||
{
|
||||
for (int i = 1; i <= 16; ++i)
|
||||
allNotesOff (i);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < 128; ++i)
|
||||
noteOff (midiChannel, i, 0.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
|
||||
{
|
||||
if (message.isNoteOn())
|
||||
{
|
||||
noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
|
||||
}
|
||||
else if (message.isNoteOff())
|
||||
{
|
||||
noteOffInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
|
||||
}
|
||||
else if (message.isAllNotesOff())
|
||||
{
|
||||
for (int i = 0; i < 128; ++i)
|
||||
noteOffInternal (message.getChannel(), i, 0.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
|
||||
const int startSample,
|
||||
const int numSamples,
|
||||
const bool injectIndirectEvents)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
for (const auto metadata : buffer)
|
||||
processNextMidiEvent (metadata.getMessage());
|
||||
|
||||
if (injectIndirectEvents)
|
||||
{
|
||||
const int firstEventToAdd = eventsToAdd.getFirstEventTime();
|
||||
const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
|
||||
|
||||
for (const auto metadata : eventsToAdd)
|
||||
{
|
||||
const auto pos = jlimit (0, numSamples - 1, roundToInt ((metadata.samplePosition - firstEventToAdd) * scaleFactor));
|
||||
buffer.addEvent (metadata.getMessage(), startSample + pos);
|
||||
}
|
||||
}
|
||||
|
||||
eventsToAdd.clear();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiKeyboardState::addListener (Listener* listener)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
listeners.add (listener);
|
||||
}
|
||||
|
||||
void MidiKeyboardState::removeListener (Listener* listener)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
listeners.remove (listener);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a piano keyboard, keeping track of which keys are currently pressed.
|
||||
|
||||
This object can parse a stream of midi events, using them to update its idea
|
||||
of which keys are pressed for each individual midi channel.
|
||||
|
||||
When keys go up or down, it can broadcast these events to listener objects.
|
||||
|
||||
It also allows key up/down events to be triggered with its noteOn() and noteOff()
|
||||
methods, and midi messages for these events will be merged into the
|
||||
midi stream that gets processed by processNextMidiBuffer().
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiKeyboardState
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
MidiKeyboardState();
|
||||
|
||||
//==============================================================================
|
||||
/** Resets the state of the object.
|
||||
|
||||
All internal data for all the channels is reset, but no events are sent as a
|
||||
result.
|
||||
|
||||
If you want to release any keys that are currently down, and to send out note-up
|
||||
midi messages for this, use the allNotesOff() method instead.
|
||||
*/
|
||||
void reset();
|
||||
|
||||
/** Returns true if the given midi key is currently held down for the given midi channel.
|
||||
|
||||
The channel number must be between 1 and 16. If you want to see if any notes are
|
||||
on for a range of channels, use the isNoteOnForChannels() method.
|
||||
*/
|
||||
bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
|
||||
|
||||
/** Returns true if the given midi key is currently held down on any of a set of midi channels.
|
||||
|
||||
The channel mask has a bit set for each midi channel you want to test for - bit
|
||||
0 = midi channel 1, bit 1 = midi channel 2, etc.
|
||||
|
||||
If a note is on for at least one of the specified channels, this returns true.
|
||||
*/
|
||||
bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
|
||||
|
||||
/** Turns a specified note on.
|
||||
|
||||
This will cause a suitable midi note-on event to be injected into the midi buffer during the
|
||||
next call to processNextMidiBuffer().
|
||||
|
||||
It will also trigger a synchronous callback to the listeners to tell them that the key has
|
||||
gone down.
|
||||
*/
|
||||
void noteOn (int midiChannel, int midiNoteNumber, float velocity);
|
||||
|
||||
/** Turns a specified note off.
|
||||
|
||||
This will cause a suitable midi note-off event to be injected into the midi buffer during the
|
||||
next call to processNextMidiBuffer().
|
||||
|
||||
It will also trigger a synchronous callback to the listeners to tell them that the key has
|
||||
gone up.
|
||||
|
||||
But if the note isn't actually down for the given channel, this method will in fact do nothing.
|
||||
*/
|
||||
void noteOff (int midiChannel, int midiNoteNumber, float velocity);
|
||||
|
||||
/** This will turn off any currently-down notes for the given midi channel.
|
||||
|
||||
If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
|
||||
|
||||
Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
|
||||
and events being added to the midi stream.
|
||||
*/
|
||||
void allNotesOff (int midiChannel);
|
||||
|
||||
//==============================================================================
|
||||
/** Looks at a key-up/down event and uses it to update the state of this object.
|
||||
|
||||
To process a buffer full of midi messages, use the processNextMidiBuffer() method
|
||||
instead.
|
||||
*/
|
||||
void processNextMidiEvent (const MidiMessage& message);
|
||||
|
||||
/** Scans a midi stream for up/down events and adds its own events to it.
|
||||
|
||||
This will look for any up/down events and use them to update the internal state,
|
||||
synchronously making suitable callbacks to the listeners.
|
||||
|
||||
If injectIndirectEvents is true, then midi events to produce the recent noteOn()
|
||||
and noteOff() calls will be added into the buffer.
|
||||
|
||||
Only the section of the buffer whose timestamps are between startSample and
|
||||
(startSample + numSamples) will be affected, and any events added will be placed
|
||||
between these times.
|
||||
|
||||
If you're going to use this method, you'll need to keep calling it regularly for
|
||||
it to work satisfactorily.
|
||||
|
||||
To process a single midi event at a time, use the processNextMidiEvent() method
|
||||
instead.
|
||||
*/
|
||||
void processNextMidiBuffer (MidiBuffer& buffer,
|
||||
int startSample,
|
||||
int numSamples,
|
||||
bool injectIndirectEvents);
|
||||
|
||||
//==============================================================================
|
||||
/** Receives events from a MidiKeyboardState object. */
|
||||
class JUCE_API Listener
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
virtual ~Listener() = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Called when one of the MidiKeyboardState's keys is pressed.
|
||||
|
||||
This will be called synchronously when the state is either processing a
|
||||
buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
|
||||
when a note is being played with its MidiKeyboardState::noteOn() method.
|
||||
|
||||
Note that this callback could happen from an audio callback thread, so be
|
||||
careful not to block, and avoid any UI activity in the callback.
|
||||
*/
|
||||
virtual void handleNoteOn (MidiKeyboardState* source,
|
||||
int midiChannel, int midiNoteNumber, float velocity) = 0;
|
||||
|
||||
/** Called when one of the MidiKeyboardState's keys is released.
|
||||
|
||||
This will be called synchronously when the state is either processing a
|
||||
buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
|
||||
when a note is being played with its MidiKeyboardState::noteOff() method.
|
||||
|
||||
Note that this callback could happen from an audio callback thread, so be
|
||||
careful not to block, and avoid any UI activity in the callback.
|
||||
*/
|
||||
virtual void handleNoteOff (MidiKeyboardState* source,
|
||||
int midiChannel, int midiNoteNumber, float velocity) = 0;
|
||||
};
|
||||
|
||||
/** Registers a listener for callbacks when keys go up or down.
|
||||
@see removeListener
|
||||
*/
|
||||
void addListener (Listener* listener);
|
||||
|
||||
/** Deregisters a listener.
|
||||
@see addListener
|
||||
*/
|
||||
void removeListener (Listener* listener);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
CriticalSection lock;
|
||||
std::atomic<uint16> noteStates[128];
|
||||
MidiBuffer eventsToAdd;
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
|
||||
void noteOffInternal (int midiChannel, int midiNoteNumber, float velocity);
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState)
|
||||
};
|
||||
|
||||
using MidiKeyboardStateListener = MidiKeyboardState::Listener;
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,882 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& mm) : message (mm) {}
|
||||
MidiMessageSequence::MidiEventHolder::MidiEventHolder (MidiMessage&& mm) : message (std::move (mm)) {}
|
||||
|
||||
//==============================================================================
|
||||
MidiMessageSequence::MidiMessageSequence()
|
||||
{
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
|
||||
{
|
||||
list.addCopiesOf (other.list);
|
||||
|
||||
for (int i = 0; i < list.size(); ++i)
|
||||
{
|
||||
auto noteOffIndex = other.getIndexOfMatchingKeyUp (i);
|
||||
|
||||
if (noteOffIndex >= 0)
|
||||
list.getUnchecked (i)->noteOffObject = list.getUnchecked (noteOffIndex);
|
||||
}
|
||||
}
|
||||
|
||||
MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
|
||||
{
|
||||
MidiMessageSequence otherCopy (other);
|
||||
swapWith (otherCopy);
|
||||
return *this;
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiMessageSequence (MidiMessageSequence&& other) noexcept
|
||||
: list (std::move (other.list))
|
||||
{
|
||||
}
|
||||
|
||||
MidiMessageSequence& MidiMessageSequence::operator= (MidiMessageSequence&& other) noexcept
|
||||
{
|
||||
list = std::move (other.list);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void MidiMessageSequence::swapWith (MidiMessageSequence& other) noexcept
|
||||
{
|
||||
list.swapWith (other.list);
|
||||
}
|
||||
|
||||
void MidiMessageSequence::clear()
|
||||
{
|
||||
list.clear();
|
||||
}
|
||||
|
||||
int MidiMessageSequence::getNumEvents() const noexcept
|
||||
{
|
||||
return list.size();
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (int index) const noexcept
|
||||
{
|
||||
return list[index];
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiEventHolder** MidiMessageSequence::begin() noexcept { return list.begin(); }
|
||||
MidiMessageSequence::MidiEventHolder* const* MidiMessageSequence::begin() const noexcept { return list.begin(); }
|
||||
MidiMessageSequence::MidiEventHolder** MidiMessageSequence::end() noexcept { return list.end(); }
|
||||
MidiMessageSequence::MidiEventHolder* const* MidiMessageSequence::end() const noexcept { return list.end(); }
|
||||
|
||||
double MidiMessageSequence::getTimeOfMatchingKeyUp (int index) const noexcept
|
||||
{
|
||||
if (auto* meh = list[index])
|
||||
if (auto* noteOff = meh->noteOffObject)
|
||||
return noteOff->message.getTimeStamp();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int MidiMessageSequence::getIndexOfMatchingKeyUp (int index) const noexcept
|
||||
{
|
||||
if (auto* meh = list[index])
|
||||
{
|
||||
if (auto* noteOff = meh->noteOffObject)
|
||||
{
|
||||
for (int i = index; i < list.size(); ++i)
|
||||
if (list.getUnchecked (i) == noteOff)
|
||||
return i;
|
||||
|
||||
jassertfalse; // we've somehow got a pointer to a note-off object that isn't in the sequence
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int MidiMessageSequence::getIndexOf (const MidiEventHolder* event) const noexcept
|
||||
{
|
||||
return list.indexOf (event);
|
||||
}
|
||||
|
||||
int MidiMessageSequence::getNextIndexAtTime (double timeStamp) const noexcept
|
||||
{
|
||||
auto numEvents = list.size();
|
||||
int i;
|
||||
|
||||
for (i = 0; i < numEvents; ++i)
|
||||
if (list.getUnchecked (i)->message.getTimeStamp() >= timeStamp)
|
||||
break;
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
double MidiMessageSequence::getStartTime() const noexcept
|
||||
{
|
||||
return getEventTime (0);
|
||||
}
|
||||
|
||||
double MidiMessageSequence::getEndTime() const noexcept
|
||||
{
|
||||
return getEventTime (list.size() - 1);
|
||||
}
|
||||
|
||||
double MidiMessageSequence::getEventTime (const int index) const noexcept
|
||||
{
|
||||
if (auto* meh = list[index])
|
||||
return meh->message.getTimeStamp();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (MidiEventHolder* newEvent, double timeAdjustment)
|
||||
{
|
||||
newEvent->message.addToTimeStamp (timeAdjustment);
|
||||
auto time = newEvent->message.getTimeStamp();
|
||||
int i;
|
||||
|
||||
for (i = list.size(); --i >= 0;)
|
||||
if (list.getUnchecked (i)->message.getTimeStamp() <= time)
|
||||
break;
|
||||
|
||||
list.insert (i + 1, newEvent);
|
||||
return newEvent;
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (const MidiMessage& newMessage, double timeAdjustment)
|
||||
{
|
||||
return addEvent (new MidiEventHolder (newMessage), timeAdjustment);
|
||||
}
|
||||
|
||||
MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (MidiMessage&& newMessage, double timeAdjustment)
|
||||
{
|
||||
return addEvent (new MidiEventHolder (std::move (newMessage)), timeAdjustment);
|
||||
}
|
||||
|
||||
void MidiMessageSequence::deleteEvent (int index, bool deleteMatchingNoteUp)
|
||||
{
|
||||
if (isPositiveAndBelow (index, list.size()))
|
||||
{
|
||||
if (deleteMatchingNoteUp)
|
||||
deleteEvent (getIndexOfMatchingKeyUp (index), false);
|
||||
|
||||
list.remove (index);
|
||||
}
|
||||
}
|
||||
|
||||
void MidiMessageSequence::addSequence (const MidiMessageSequence& other, double timeAdjustment)
|
||||
{
|
||||
for (auto* m : other)
|
||||
{
|
||||
auto newOne = new MidiEventHolder (m->message);
|
||||
newOne->message.addToTimeStamp (timeAdjustment);
|
||||
list.add (newOne);
|
||||
}
|
||||
|
||||
sort();
|
||||
}
|
||||
|
||||
void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
|
||||
double timeAdjustment,
|
||||
double firstAllowableTime,
|
||||
double endOfAllowableDestTimes)
|
||||
{
|
||||
for (auto* m : other)
|
||||
{
|
||||
auto t = m->message.getTimeStamp() + timeAdjustment;
|
||||
|
||||
if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
|
||||
{
|
||||
auto newOne = new MidiEventHolder (m->message);
|
||||
newOne->message.setTimeStamp (t);
|
||||
list.add (newOne);
|
||||
}
|
||||
}
|
||||
|
||||
sort();
|
||||
}
|
||||
|
||||
void MidiMessageSequence::sort() noexcept
|
||||
{
|
||||
std::stable_sort (list.begin(), list.end(),
|
||||
[] (const MidiEventHolder* a, const MidiEventHolder* b) { return a->message.getTimeStamp() < b->message.getTimeStamp(); });
|
||||
}
|
||||
|
||||
void MidiMessageSequence::updateMatchedPairs() noexcept
|
||||
{
|
||||
for (int i = 0; i < list.size(); ++i)
|
||||
{
|
||||
auto* meh = list.getUnchecked (i);
|
||||
auto& m1 = meh->message;
|
||||
|
||||
if (m1.isNoteOn())
|
||||
{
|
||||
meh->noteOffObject = nullptr;
|
||||
auto note = m1.getNoteNumber();
|
||||
auto chan = m1.getChannel();
|
||||
auto len = list.size();
|
||||
|
||||
for (int j = i + 1; j < len; ++j)
|
||||
{
|
||||
auto* meh2 = list.getUnchecked (j);
|
||||
auto& m = meh2->message;
|
||||
|
||||
if (m.getNoteNumber() == note && m.getChannel() == chan)
|
||||
{
|
||||
if (m.isNoteOff())
|
||||
{
|
||||
meh->noteOffObject = meh2;
|
||||
break;
|
||||
}
|
||||
|
||||
if (m.isNoteOn())
|
||||
{
|
||||
auto newEvent = new MidiEventHolder (MidiMessage::noteOff (chan, note));
|
||||
list.insert (j, newEvent);
|
||||
newEvent->message.setTimeStamp (m.getTimeStamp());
|
||||
meh->noteOffObject = newEvent;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MidiMessageSequence::addTimeToMessages (double delta) noexcept
|
||||
{
|
||||
if (! approximatelyEqual (delta, 0.0))
|
||||
for (auto* m : list)
|
||||
m->message.addToTimeStamp (delta);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
|
||||
MidiMessageSequence& destSequence,
|
||||
const bool alsoIncludeMetaEvents) const
|
||||
{
|
||||
for (auto* meh : list)
|
||||
if (meh->message.isForChannel (channelNumberToExtract)
|
||||
|| (alsoIncludeMetaEvents && meh->message.isMetaEvent()))
|
||||
destSequence.addEvent (meh->message);
|
||||
}
|
||||
|
||||
void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
|
||||
{
|
||||
for (auto* meh : list)
|
||||
if (meh->message.isSysEx())
|
||||
destSequence.addEvent (meh->message);
|
||||
}
|
||||
|
||||
void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
|
||||
{
|
||||
for (int i = list.size(); --i >= 0;)
|
||||
if (list.getUnchecked (i)->message.isForChannel (channelNumberToRemove))
|
||||
list.remove (i);
|
||||
}
|
||||
|
||||
void MidiMessageSequence::deleteSysExMessages()
|
||||
{
|
||||
for (int i = list.size(); --i >= 0;)
|
||||
if (list.getUnchecked (i)->message.isSysEx())
|
||||
list.remove (i);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class OptionalPitchWheel
|
||||
{
|
||||
Optional<int> value;
|
||||
|
||||
public:
|
||||
void emit (int channel, Array<MidiMessage>& out) const
|
||||
{
|
||||
if (value.hasValue())
|
||||
out.add (MidiMessage::pitchWheel (channel, *value));
|
||||
}
|
||||
|
||||
void set (int v)
|
||||
{
|
||||
value = v;
|
||||
}
|
||||
};
|
||||
|
||||
class OptionalControllerValues
|
||||
{
|
||||
Optional<char> values[128];
|
||||
|
||||
public:
|
||||
void emit (int channel, Array<MidiMessage>& out) const
|
||||
{
|
||||
for (auto it = std::begin (values); it != std::end (values); ++it)
|
||||
if (it->hasValue())
|
||||
out.add (MidiMessage::controllerEvent (channel, (int) std::distance (std::begin (values), it), **it));
|
||||
}
|
||||
|
||||
void set (int controller, int value)
|
||||
{
|
||||
values[controller] = (char) value;
|
||||
}
|
||||
};
|
||||
|
||||
class OptionalProgramChange
|
||||
{
|
||||
Optional<char> value, bankLSB, bankMSB;
|
||||
|
||||
public:
|
||||
void emit (int channel, double time, Array<MidiMessage>& out) const
|
||||
{
|
||||
if (! value.hasValue())
|
||||
return;
|
||||
|
||||
if (bankLSB.hasValue() && bankMSB.hasValue())
|
||||
{
|
||||
out.add (MidiMessage::controllerEvent (channel, 0x00, *bankMSB).withTimeStamp (time));
|
||||
out.add (MidiMessage::controllerEvent (channel, 0x20, *bankLSB).withTimeStamp (time));
|
||||
}
|
||||
|
||||
out.add (MidiMessage::programChange (channel, *value).withTimeStamp (time));
|
||||
}
|
||||
|
||||
// Returns true if this is a bank number change, and false otherwise.
|
||||
bool trySetBank (int controller, int v)
|
||||
{
|
||||
switch (controller)
|
||||
{
|
||||
case 0x00: bankMSB = (char) v; return true;
|
||||
case 0x20: bankLSB = (char) v; return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void setProgram (int v) { value = (char) v; }
|
||||
};
|
||||
|
||||
class ParameterNumberState
|
||||
{
|
||||
enum class Kind { rpn, nrpn };
|
||||
|
||||
Optional<char> newestRpnLsb, newestRpnMsb, newestNrpnLsb, newestNrpnMsb, lastSentLsb, lastSentMsb;
|
||||
Kind lastSentKind = Kind::rpn, newestKind = Kind::rpn;
|
||||
|
||||
public:
|
||||
// If the effective parameter number has changed since the last time this function was called,
|
||||
// this will emit the current parameter in full (MSB and LSB).
|
||||
// This should be called before each data message (entry, increment, decrement: 0x06, 0x26, 0x60, 0x61)
|
||||
// to ensure that the data message operates on the correct parameter number.
|
||||
void sendIfNecessary (int channel, double time, Array<MidiMessage>& out)
|
||||
{
|
||||
const auto newestMsb = newestKind == Kind::rpn ? newestRpnMsb : newestNrpnMsb;
|
||||
const auto newestLsb = newestKind == Kind::rpn ? newestRpnLsb : newestNrpnLsb;
|
||||
|
||||
auto lastSent = std::tie (lastSentKind, lastSentMsb, lastSentLsb);
|
||||
const auto newest = std::tie (newestKind, newestMsb, newestLsb);
|
||||
|
||||
if (lastSent == newest || ! newestMsb.hasValue() || ! newestLsb.hasValue())
|
||||
return;
|
||||
|
||||
out.add (MidiMessage::controllerEvent (channel, newestKind == Kind::rpn ? 0x65 : 0x63, *newestMsb).withTimeStamp (time));
|
||||
out.add (MidiMessage::controllerEvent (channel, newestKind == Kind::rpn ? 0x64 : 0x62, *newestLsb).withTimeStamp (time));
|
||||
|
||||
lastSent = newest;
|
||||
}
|
||||
|
||||
// Returns true if this is a parameter number change, and false otherwise.
|
||||
bool trySetProgramNumber (int controller, int value)
|
||||
{
|
||||
switch (controller)
|
||||
{
|
||||
case 0x65: newestRpnMsb = (char) value; newestKind = Kind::rpn; return true;
|
||||
case 0x64: newestRpnLsb = (char) value; newestKind = Kind::rpn; return true;
|
||||
case 0x63: newestNrpnMsb = (char) value; newestKind = Kind::nrpn; return true;
|
||||
case 0x62: newestNrpnLsb = (char) value; newestKind = Kind::nrpn; return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
void MidiMessageSequence::createControllerUpdatesForTime (int channel, double time, Array<MidiMessage>& dest)
|
||||
{
|
||||
OptionalProgramChange programChange;
|
||||
OptionalControllerValues controllers;
|
||||
OptionalPitchWheel pitchWheel;
|
||||
ParameterNumberState parameterNumberState;
|
||||
|
||||
for (const auto& item : list)
|
||||
{
|
||||
const auto& mm = item->message;
|
||||
|
||||
if (! (mm.isForChannel (channel) && mm.getTimeStamp() <= time))
|
||||
continue;
|
||||
|
||||
if (mm.isController())
|
||||
{
|
||||
const auto num = mm.getControllerNumber();
|
||||
|
||||
if (parameterNumberState.trySetProgramNumber (num, mm.getControllerValue()))
|
||||
continue;
|
||||
|
||||
if (programChange.trySetBank (num, mm.getControllerValue()))
|
||||
continue;
|
||||
|
||||
constexpr int passthroughs[] { 0x06, 0x26, 0x60, 0x61 };
|
||||
|
||||
if (std::find (std::begin (passthroughs), std::end (passthroughs), num) != std::end (passthroughs))
|
||||
{
|
||||
parameterNumberState.sendIfNecessary (channel, mm.getTimeStamp(), dest);
|
||||
dest.add (mm);
|
||||
}
|
||||
else
|
||||
{
|
||||
controllers.set (num, mm.getControllerValue());
|
||||
}
|
||||
}
|
||||
else if (mm.isProgramChange())
|
||||
{
|
||||
programChange.setProgram (mm.getProgramChangeNumber());
|
||||
}
|
||||
else if (mm.isPitchWheel())
|
||||
{
|
||||
pitchWheel.set (mm.getPitchWheelValue());
|
||||
}
|
||||
}
|
||||
|
||||
pitchWheel.emit (channel, dest);
|
||||
controllers.emit (channel, dest);
|
||||
|
||||
// Also emits bank change messages if necessary.
|
||||
programChange.emit (channel, time, dest);
|
||||
|
||||
// Set the parameter number to its final state.
|
||||
parameterNumberState.sendIfNecessary (channel, time, dest);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
struct MidiMessageSequenceTest final : public UnitTest
|
||||
{
|
||||
MidiMessageSequenceTest()
|
||||
: UnitTest ("MidiMessageSequence", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
MidiMessageSequence s;
|
||||
|
||||
s.addEvent (MidiMessage::noteOn (1, 60, 0.5f).withTimeStamp (0.0));
|
||||
s.addEvent (MidiMessage::noteOff (1, 60, 0.5f).withTimeStamp (4.0));
|
||||
s.addEvent (MidiMessage::noteOn (1, 30, 0.5f).withTimeStamp (2.0));
|
||||
s.addEvent (MidiMessage::noteOff (1, 30, 0.5f).withTimeStamp (8.0));
|
||||
|
||||
beginTest ("Start & end time");
|
||||
expectEquals (s.getStartTime(), 0.0);
|
||||
expectEquals (s.getEndTime(), 8.0);
|
||||
expectEquals (s.getEventTime (1), 2.0);
|
||||
|
||||
beginTest ("Matching note off & ons");
|
||||
s.updateMatchedPairs();
|
||||
expectEquals (s.getTimeOfMatchingKeyUp (0), 4.0);
|
||||
expectEquals (s.getTimeOfMatchingKeyUp (1), 8.0);
|
||||
expectEquals (s.getIndexOfMatchingKeyUp (0), 2);
|
||||
expectEquals (s.getIndexOfMatchingKeyUp (1), 3);
|
||||
|
||||
beginTest ("Time & indices");
|
||||
expectEquals (s.getNextIndexAtTime (0.5), 1);
|
||||
expectEquals (s.getNextIndexAtTime (2.5), 2);
|
||||
expectEquals (s.getNextIndexAtTime (9.0), 4);
|
||||
|
||||
beginTest ("Deleting events");
|
||||
s.deleteEvent (0, true);
|
||||
expectEquals (s.getNumEvents(), 2);
|
||||
|
||||
beginTest ("Merging sequences");
|
||||
MidiMessageSequence s2;
|
||||
s2.addEvent (MidiMessage::noteOn (2, 25, 0.5f).withTimeStamp (0.0));
|
||||
s2.addEvent (MidiMessage::noteOn (2, 40, 0.5f).withTimeStamp (1.0));
|
||||
s2.addEvent (MidiMessage::noteOff (2, 40, 0.5f).withTimeStamp (5.0));
|
||||
s2.addEvent (MidiMessage::noteOn (2, 80, 0.5f).withTimeStamp (3.0));
|
||||
s2.addEvent (MidiMessage::noteOff (2, 80, 0.5f).withTimeStamp (7.0));
|
||||
s2.addEvent (MidiMessage::noteOff (2, 25, 0.5f).withTimeStamp (9.0));
|
||||
|
||||
s.addSequence (s2, 0.0, 0.0, 8.0); // Intentionally cut off the last note off
|
||||
s.updateMatchedPairs();
|
||||
|
||||
expectEquals (s.getNumEvents(), 7);
|
||||
expectEquals (s.getIndexOfMatchingKeyUp (0), -1); // Truncated note, should be no note off
|
||||
expectEquals (s.getTimeOfMatchingKeyUp (1), 5.0);
|
||||
|
||||
struct ControlValue { int control, value; };
|
||||
|
||||
struct DataEntry
|
||||
{
|
||||
int controllerBase, channel, parameter, value;
|
||||
double time;
|
||||
|
||||
std::array<ControlValue, 4> getControlValues() const
|
||||
{
|
||||
return { { { controllerBase + 1, (parameter >> 7) & 0x7f },
|
||||
{ controllerBase + 0, (parameter >> 0) & 0x7f },
|
||||
{ 0x06, (value >> 7) & 0x7f },
|
||||
{ 0x26, (value >> 0) & 0x7f } } };
|
||||
}
|
||||
|
||||
void addToSequence (MidiMessageSequence& s) const
|
||||
{
|
||||
for (const auto& pair : getControlValues())
|
||||
s.addEvent (MidiMessage::controllerEvent (channel, pair.control, pair.value), time);
|
||||
}
|
||||
|
||||
bool matches (const MidiMessage* begin, const MidiMessage* end) const
|
||||
{
|
||||
const auto isEqual = [this] (const ControlValue& cv, const MidiMessage& msg)
|
||||
{
|
||||
return exactlyEqual (msg.getTimeStamp(), time)
|
||||
&& msg.isController()
|
||||
&& msg.getChannel() == channel
|
||||
&& msg.getControllerNumber() == cv.control
|
||||
&& msg.getControllerValue() == cv.value;
|
||||
};
|
||||
|
||||
const auto pairs = getControlValues();
|
||||
return std::equal (pairs.begin(), pairs.end(), begin, end, isEqual);
|
||||
}
|
||||
};
|
||||
|
||||
const auto addNrpn = [&] (MidiMessageSequence& seq, int channel, int parameter, int value, double time = 0.0)
|
||||
{
|
||||
DataEntry { 0x62, channel, parameter, value, time }.addToSequence (seq);
|
||||
};
|
||||
|
||||
const auto addRpn = [&] (MidiMessageSequence& seq, int channel, int parameter, int value, double time = 0.0)
|
||||
{
|
||||
DataEntry { 0x64, channel, parameter, value, time }.addToSequence (seq);
|
||||
};
|
||||
|
||||
const auto checkNrpn = [&] (const MidiMessage* begin, const MidiMessage* end, int channel, int parameter, int value, double time = 0.0)
|
||||
{
|
||||
expect (DataEntry { 0x62, channel, parameter, value, time }.matches (begin, end));
|
||||
};
|
||||
|
||||
const auto checkRpn = [&] (const MidiMessage* begin, const MidiMessage* end, int channel, int parameter, int value, double time = 0.0)
|
||||
{
|
||||
expect (DataEntry { 0x64, channel, parameter, value, time }.matches (begin, end));
|
||||
};
|
||||
|
||||
beginTest ("createControllerUpdatesForTime should emit (N)RPN components in the correct order");
|
||||
{
|
||||
const auto channel = 1;
|
||||
const auto number = 200;
|
||||
const auto value = 300;
|
||||
|
||||
MidiMessageSequence sequence;
|
||||
addNrpn (sequence, channel, number, value);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, 1.0, m);
|
||||
|
||||
checkNrpn (m.begin(), m.end(), channel, number, value);
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime ignores (N)RPNs after the final requested time");
|
||||
{
|
||||
const auto channel = 2;
|
||||
const auto number = 123;
|
||||
const auto value = 456;
|
||||
|
||||
MidiMessageSequence sequence;
|
||||
addRpn (sequence, channel, number, value, 0.5);
|
||||
addRpn (sequence, channel, 111, 222, 1.5);
|
||||
addRpn (sequence, channel, 333, 444, 2.5);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, 1.0, m);
|
||||
|
||||
checkRpn (m.begin(), std::next (m.begin(), 4), channel, number, value, 0.5);
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime should emit separate (N)RPN messages when appropriate");
|
||||
{
|
||||
const auto channel = 2;
|
||||
const auto numberA = 1111;
|
||||
const auto valueA = 9999;
|
||||
|
||||
const auto numberB = 8888;
|
||||
const auto valueB = 2222;
|
||||
|
||||
const auto numberC = 7777;
|
||||
const auto valueC = 3333;
|
||||
|
||||
const auto numberD = 6666;
|
||||
const auto valueD = 4444;
|
||||
|
||||
const auto time = 0.5;
|
||||
|
||||
MidiMessageSequence sequence;
|
||||
addRpn (sequence, channel, numberA, valueA, time);
|
||||
addRpn (sequence, channel, numberB, valueB, time);
|
||||
addNrpn (sequence, channel, numberC, valueC, time);
|
||||
addNrpn (sequence, channel, numberD, valueD, time);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, time * 2, m);
|
||||
|
||||
checkRpn (std::next (m.begin(), 0), std::next (m.begin(), 4), channel, numberA, valueA, time);
|
||||
checkRpn (std::next (m.begin(), 4), std::next (m.begin(), 8), channel, numberB, valueB, time);
|
||||
checkNrpn (std::next (m.begin(), 8), std::next (m.begin(), 12), channel, numberC, valueC, time);
|
||||
checkNrpn (std::next (m.begin(), 12), std::next (m.begin(), 16), channel, numberD, valueD, time);
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime correctly emits (N)RPN messages on multiple channels");
|
||||
{
|
||||
struct Info { int channel, number, value; };
|
||||
|
||||
const Info infos[] { { 2, 1111, 9999 },
|
||||
{ 8, 8888, 2222 },
|
||||
{ 5, 7777, 3333 },
|
||||
{ 1, 6666, 4444 } };
|
||||
|
||||
const auto time = 0.5;
|
||||
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
for (const auto& info : infos)
|
||||
addRpn (sequence, info.channel, info.number, info.value, time);
|
||||
|
||||
for (const auto& info : infos)
|
||||
{
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (info.channel, time * 2, m);
|
||||
checkRpn (std::next (m.begin(), 0), std::next (m.begin(), 4), info.channel, info.number, info.value, time);
|
||||
}
|
||||
}
|
||||
|
||||
const auto messagesAreEqual = [] (const MidiMessage& a, const MidiMessage& b)
|
||||
{
|
||||
return std::equal (a.getRawData(), a.getRawData() + a.getRawDataSize(),
|
||||
b.getRawData(), b.getRawData() + b.getRawDataSize());
|
||||
};
|
||||
|
||||
beginTest ("createControllerUpdatesForTime sends bank select messages when the next program is in a new bank");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
sequence.addEvent (MidiMessage::programChange (channel, 5), time);
|
||||
|
||||
sequence.addEvent (MidiMessage::controllerEvent (channel, 0x00, 128), time);
|
||||
sequence.addEvent (MidiMessage::controllerEvent (channel, 0x20, 64), time);
|
||||
sequence.addEvent (MidiMessage::programChange (channel, 63), time);
|
||||
|
||||
const Array<MidiMessage> finalEvents { MidiMessage::controllerEvent (channel, 0x00, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x20, 40),
|
||||
MidiMessage::programChange (channel, 30) };
|
||||
|
||||
for (const auto& e : finalEvents)
|
||||
sequence.addEvent (e);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, 1.0, m);
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), finalEvents.begin(), finalEvents.end(), messagesAreEqual));
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime preserves all Data Increment and Data Decrement messages");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
const Array<MidiMessage> messages { MidiMessage::controllerEvent (channel, 0x60, 0),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 100),
|
||||
MidiMessage::controllerEvent (channel, 0x26, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x60, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x61, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 20),
|
||||
MidiMessage::controllerEvent (channel, 0x26, 30),
|
||||
MidiMessage::controllerEvent (channel, 0x61, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x61, 20) };
|
||||
|
||||
for (const auto& m : messages)
|
||||
sequence.addEvent (m, time);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, 1.0, m);
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), messages.begin(), messages.end(), messagesAreEqual));
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime does not emit redundant parameter number changes");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
const Array<MidiMessage> messages { MidiMessage::controllerEvent (channel, 0x65, 0),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 100),
|
||||
MidiMessage::controllerEvent (channel, 0x63, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10) };
|
||||
|
||||
for (const auto& m : messages)
|
||||
sequence.addEvent (m, time);
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, 1.0, m);
|
||||
|
||||
const Array<MidiMessage> expected { MidiMessage::controllerEvent (channel, 0x63, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10) };
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), expected.begin(), expected.end(), messagesAreEqual));
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime sets parameter number correctly at end of sequence");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
const Array<MidiMessage> messages { MidiMessage::controllerEvent (channel, 0x65, 0),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 100),
|
||||
MidiMessage::controllerEvent (channel, 0x63, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 5) };
|
||||
|
||||
for (const auto& m : messages)
|
||||
sequence.addEvent (m, time);
|
||||
|
||||
const auto finalTime = 1.0;
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, finalTime, m);
|
||||
|
||||
const Array<MidiMessage> expected { MidiMessage::controllerEvent (channel, 0x63, 50),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10),
|
||||
// Note: we should send both the MSB and LSB!
|
||||
MidiMessage::controllerEvent (channel, 0x65, 0).withTimeStamp (finalTime),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 5).withTimeStamp (finalTime) };
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), expected.begin(), expected.end(), messagesAreEqual));
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime does not emit duplicate parameter number change messages");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
const Array<MidiMessage> messages { MidiMessage::controllerEvent (channel, 0x65, 1),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 2),
|
||||
MidiMessage::controllerEvent (channel, 0x63, 3),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 4),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10),
|
||||
MidiMessage::controllerEvent (channel, 0x63, 30),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 40),
|
||||
MidiMessage::controllerEvent (channel, 0x63, 3),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 4),
|
||||
MidiMessage::controllerEvent (channel, 0x60, 5),
|
||||
MidiMessage::controllerEvent (channel, 0x65, 10) };
|
||||
|
||||
for (const auto& m : messages)
|
||||
sequence.addEvent (m, time);
|
||||
|
||||
const auto finalTime = 1.0;
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, finalTime, m);
|
||||
|
||||
const Array<MidiMessage> expected { MidiMessage::controllerEvent (channel, 0x63, 3),
|
||||
MidiMessage::controllerEvent (channel, 0x62, 4),
|
||||
MidiMessage::controllerEvent (channel, 0x06, 10),
|
||||
// Parameter number is set to (30, 40) then back to (3, 4),
|
||||
// so there is no need to resend it
|
||||
MidiMessage::controllerEvent (channel, 0x60, 5),
|
||||
// Set parameter number to final value
|
||||
MidiMessage::controllerEvent (channel, 0x65, 10).withTimeStamp (finalTime),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 2) .withTimeStamp (finalTime) };
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), expected.begin(), expected.end(), messagesAreEqual));
|
||||
}
|
||||
|
||||
beginTest ("createControllerUpdatesForTime emits bank change messages immediately before program change");
|
||||
{
|
||||
MidiMessageSequence sequence;
|
||||
|
||||
const auto time = 0.0;
|
||||
const auto channel = 1;
|
||||
|
||||
const Array<MidiMessage> messages { MidiMessage::controllerEvent (channel, 0x00, 1),
|
||||
MidiMessage::controllerEvent (channel, 0x20, 2),
|
||||
MidiMessage::controllerEvent (channel, 0x65, 0),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 0),
|
||||
MidiMessage::programChange (channel, 5) };
|
||||
|
||||
for (const auto& m : messages)
|
||||
sequence.addEvent (m, time);
|
||||
|
||||
const auto finalTime = 1.0;
|
||||
|
||||
Array<MidiMessage> m;
|
||||
sequence.createControllerUpdatesForTime (channel, finalTime, m);
|
||||
|
||||
const Array<MidiMessage> expected { MidiMessage::controllerEvent (channel, 0x00, 1),
|
||||
MidiMessage::controllerEvent (channel, 0x20, 2),
|
||||
MidiMessage::programChange (channel, 5),
|
||||
MidiMessage::controllerEvent (channel, 0x65, 0).withTimeStamp (finalTime),
|
||||
MidiMessage::controllerEvent (channel, 0x64, 0).withTimeStamp (finalTime) };
|
||||
|
||||
|
||||
expect (std::equal (m.begin(), m.end(), expected.begin(), expected.end(), messagesAreEqual));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MidiMessageSequenceTest midiMessageSequenceTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A sequence of timestamped midi messages.
|
||||
|
||||
This allows the sequence to be manipulated, and also to be read from and
|
||||
written to a standard midi file.
|
||||
|
||||
@see MidiMessage, MidiFile
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiMessageSequence
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty midi sequence object. */
|
||||
MidiMessageSequence();
|
||||
|
||||
/** Creates a copy of another sequence. */
|
||||
MidiMessageSequence (const MidiMessageSequence&);
|
||||
|
||||
/** Replaces this sequence with another one. */
|
||||
MidiMessageSequence& operator= (const MidiMessageSequence&);
|
||||
|
||||
/** Move constructor */
|
||||
MidiMessageSequence (MidiMessageSequence&&) noexcept;
|
||||
|
||||
/** Move assignment operator */
|
||||
MidiMessageSequence& operator= (MidiMessageSequence&&) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Structure used to hold midi events in the sequence.
|
||||
|
||||
These structures act as 'handles' on the events as they are moved about in
|
||||
the list, and make it quick to find the matching note-offs for note-on events.
|
||||
|
||||
@see MidiMessageSequence::getEventPointer
|
||||
*/
|
||||
class MidiEventHolder
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** The message itself, whose timestamp is used to specify the event's time. */
|
||||
MidiMessage message;
|
||||
|
||||
/** The matching note-off event (if this is a note-on event).
|
||||
|
||||
If this isn't a note-on, this pointer will be nullptr.
|
||||
|
||||
Use the MidiMessageSequence::updateMatchedPairs() method to keep these
|
||||
note-offs up-to-date after events have been moved around in the sequence
|
||||
or deleted.
|
||||
*/
|
||||
MidiEventHolder* noteOffObject = nullptr;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
friend class MidiMessageSequence;
|
||||
MidiEventHolder (const MidiMessage&);
|
||||
MidiEventHolder (MidiMessage&&);
|
||||
JUCE_LEAK_DETECTOR (MidiEventHolder)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Clears the sequence. */
|
||||
void clear();
|
||||
|
||||
/** Returns the number of events in the sequence. */
|
||||
int getNumEvents() const noexcept;
|
||||
|
||||
/** Returns a pointer to one of the events. */
|
||||
MidiEventHolder* getEventPointer (int index) const noexcept;
|
||||
|
||||
/** Iterator for the list of MidiEventHolders */
|
||||
MidiEventHolder** begin() noexcept;
|
||||
|
||||
/** Iterator for the list of MidiEventHolders */
|
||||
MidiEventHolder* const* begin() const noexcept;
|
||||
|
||||
/** Iterator for the list of MidiEventHolders */
|
||||
MidiEventHolder** end() noexcept;
|
||||
|
||||
/** Iterator for the list of MidiEventHolders */
|
||||
MidiEventHolder* const* end() const noexcept;
|
||||
|
||||
/** Returns the time of the note-up that matches the note-on at this index.
|
||||
If the event at this index isn't a note-on, it'll just return 0.
|
||||
@see MidiMessageSequence::MidiEventHolder::noteOffObject
|
||||
*/
|
||||
double getTimeOfMatchingKeyUp (int index) const noexcept;
|
||||
|
||||
/** Returns the index of the note-up that matches the note-on at this index.
|
||||
If the event at this index isn't a note-on, it'll just return -1.
|
||||
@see MidiMessageSequence::MidiEventHolder::noteOffObject
|
||||
*/
|
||||
int getIndexOfMatchingKeyUp (int index) const noexcept;
|
||||
|
||||
/** Returns the index of an event. */
|
||||
int getIndexOf (const MidiEventHolder* event) const noexcept;
|
||||
|
||||
/** Returns the index of the first event on or after the given timestamp.
|
||||
If the time is beyond the end of the sequence, this will return the
|
||||
number of events.
|
||||
*/
|
||||
int getNextIndexAtTime (double timeStamp) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the timestamp of the first event in the sequence.
|
||||
@see getEndTime
|
||||
*/
|
||||
double getStartTime() const noexcept;
|
||||
|
||||
/** Returns the timestamp of the last event in the sequence.
|
||||
@see getStartTime
|
||||
*/
|
||||
double getEndTime() const noexcept;
|
||||
|
||||
/** Returns the timestamp of the event at a given index.
|
||||
If the index is out-of-range, this will return 0.0
|
||||
*/
|
||||
double getEventTime (int index) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Inserts a midi message into the sequence.
|
||||
|
||||
The index at which the new message gets inserted will depend on its timestamp,
|
||||
because the sequence is kept sorted.
|
||||
|
||||
Remember to call updateMatchedPairs() after adding note-on events.
|
||||
|
||||
@param newMessage the new message to add (an internal copy will be made)
|
||||
@param timeAdjustment an optional value to add to the timestamp of the message
|
||||
that will be inserted
|
||||
@see updateMatchedPairs
|
||||
*/
|
||||
MidiEventHolder* addEvent (const MidiMessage& newMessage, double timeAdjustment = 0);
|
||||
|
||||
/** Inserts a midi message into the sequence.
|
||||
|
||||
The index at which the new message gets inserted will depend on its timestamp,
|
||||
because the sequence is kept sorted.
|
||||
|
||||
Remember to call updateMatchedPairs() after adding note-on events.
|
||||
|
||||
@param newMessage the new message to add (an internal copy will be made)
|
||||
@param timeAdjustment an optional value to add to the timestamp of the message
|
||||
that will be inserted
|
||||
@see updateMatchedPairs
|
||||
*/
|
||||
MidiEventHolder* addEvent (MidiMessage&& newMessage, double timeAdjustment = 0);
|
||||
|
||||
/** Deletes one of the events in the sequence.
|
||||
|
||||
Remember to call updateMatchedPairs() after removing events.
|
||||
|
||||
@param index the index of the event to delete
|
||||
@param deleteMatchingNoteUp whether to also remove the matching note-off
|
||||
if the event you're removing is a note-on
|
||||
*/
|
||||
void deleteEvent (int index, bool deleteMatchingNoteUp);
|
||||
|
||||
/** Merges another sequence into this one.
|
||||
Remember to call updateMatchedPairs() after using this method.
|
||||
|
||||
@param other the sequence to add from
|
||||
@param timeAdjustmentDelta an amount to add to the timestamps of the midi events
|
||||
as they are read from the other sequence
|
||||
@param firstAllowableDestTime events will not be added if their time is earlier
|
||||
than this time. (This is after their time has been adjusted
|
||||
by the timeAdjustmentDelta)
|
||||
@param endOfAllowableDestTimes events will not be added if their time is equal to
|
||||
or greater than this time. (This is after their time has
|
||||
been adjusted by the timeAdjustmentDelta)
|
||||
*/
|
||||
void addSequence (const MidiMessageSequence& other,
|
||||
double timeAdjustmentDelta,
|
||||
double firstAllowableDestTime,
|
||||
double endOfAllowableDestTimes);
|
||||
|
||||
/** Merges another sequence into this one.
|
||||
Remember to call updateMatchedPairs() after using this method.
|
||||
|
||||
@param other the sequence to add from
|
||||
@param timeAdjustmentDelta an amount to add to the timestamps of the midi events
|
||||
as they are read from the other sequence
|
||||
*/
|
||||
void addSequence (const MidiMessageSequence& other,
|
||||
double timeAdjustmentDelta);
|
||||
|
||||
//==============================================================================
|
||||
/** Makes sure all the note-on and note-off pairs are up-to-date.
|
||||
|
||||
Call this after re-ordering messages or deleting/adding messages, and it
|
||||
will scan the list and make sure all the note-offs in the MidiEventHolder
|
||||
structures are pointing at the correct ones.
|
||||
*/
|
||||
void updateMatchedPairs() noexcept;
|
||||
|
||||
/** Forces a sort of the sequence.
|
||||
You may need to call this if you've manually modified the timestamps of some
|
||||
events such that the overall order now needs updating.
|
||||
*/
|
||||
void sort() noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Copies all the messages for a particular midi channel to another sequence.
|
||||
|
||||
@param channelNumberToExtract the midi channel to look for, in the range 1 to 16
|
||||
@param destSequence the sequence that the chosen events should be copied to
|
||||
@param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
|
||||
channel) will also be copied across.
|
||||
@see extractSysExMessages
|
||||
*/
|
||||
void extractMidiChannelMessages (int channelNumberToExtract,
|
||||
MidiMessageSequence& destSequence,
|
||||
bool alsoIncludeMetaEvents) const;
|
||||
|
||||
/** Copies all midi sys-ex messages to another sequence.
|
||||
@param destSequence this is the sequence to which any sys-exes in this sequence
|
||||
will be added
|
||||
@see extractMidiChannelMessages
|
||||
*/
|
||||
void extractSysExMessages (MidiMessageSequence& destSequence) const;
|
||||
|
||||
/** Removes any messages in this sequence that have a specific midi channel.
|
||||
@param channelNumberToRemove the midi channel to look for, in the range 1 to 16
|
||||
*/
|
||||
void deleteMidiChannelMessages (int channelNumberToRemove);
|
||||
|
||||
/** Removes any sys-ex messages from this sequence. */
|
||||
void deleteSysExMessages();
|
||||
|
||||
/** Adds an offset to the timestamps of all events in the sequence.
|
||||
@param deltaTime the amount to add to each timestamp.
|
||||
*/
|
||||
void addTimeToMessages (double deltaTime) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Scans through the sequence to determine the state of any midi controllers at
|
||||
a given time.
|
||||
|
||||
This will create a sequence of midi controller changes that can be
|
||||
used to set all midi controllers to the state they would be in at the
|
||||
specified time within this sequence.
|
||||
|
||||
As well as controllers, it will also recreate the midi program number
|
||||
and pitch bend position.
|
||||
|
||||
This function has special handling for the "bank select" and "data entry"
|
||||
controllers (0x00, 0x20, 0x06, 0x26, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65).
|
||||
|
||||
If the sequence contains multiple bank select and program change messages,
|
||||
only the bank select messages immediately preceding the final program change
|
||||
message will be kept.
|
||||
|
||||
All "data increment" and "data decrement" messages will be retained. Some hardware will
|
||||
ignore the requested increment/decrement values, so retaining all messages is the only
|
||||
way to ensure compatibility with all hardware.
|
||||
|
||||
"Parameter number" changes will be slightly condensed. Only the parameter number
|
||||
events immediately preceding each data entry event will be kept. The parameter number
|
||||
will also be set to its final value at the end of the sequence, if necessary.
|
||||
|
||||
@param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
|
||||
for other channels will be ignored.
|
||||
@param time the time at which you want to find out the state - there are
|
||||
no explicit units for this time measurement, it's the same units
|
||||
as used for the timestamps of the messages
|
||||
@param resultMessages an array to which midi controller-change messages will be added. This
|
||||
will be the minimum number of controller changes to recreate the
|
||||
state at the required time.
|
||||
*/
|
||||
void createControllerUpdatesForTime (int channelNumber, double time,
|
||||
Array<MidiMessage>& resultMessages);
|
||||
|
||||
//==============================================================================
|
||||
/** Swaps this sequence with another one. */
|
||||
void swapWith (MidiMessageSequence&) noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
friend class MidiFile;
|
||||
OwnedArray<MidiEventHolder> list;
|
||||
|
||||
MidiEventHolder* addEvent (MidiEventHolder*, double);
|
||||
|
||||
JUCE_LEAK_DETECTOR (MidiMessageSequence)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,447 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
bool MidiRPNDetector::parseControllerMessage (int midiChannel,
|
||||
int controllerNumber,
|
||||
int controllerValue,
|
||||
MidiRPNMessage& result) noexcept
|
||||
{
|
||||
auto parsed = tryParse (midiChannel, controllerNumber, controllerValue);
|
||||
|
||||
if (! parsed.has_value())
|
||||
return false;
|
||||
|
||||
result = *parsed;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<MidiRPNMessage> MidiRPNDetector::tryParse (int midiChannel,
|
||||
int controllerNumber,
|
||||
int controllerValue)
|
||||
{
|
||||
jassert (midiChannel > 0 && midiChannel <= 16);
|
||||
jassert (controllerNumber >= 0 && controllerNumber < 128);
|
||||
jassert (controllerValue >= 0 && controllerValue < 128);
|
||||
|
||||
return states[midiChannel - 1].handleController (midiChannel, controllerNumber, controllerValue);
|
||||
}
|
||||
|
||||
void MidiRPNDetector::reset() noexcept
|
||||
{
|
||||
for (auto& state : states)
|
||||
{
|
||||
state.parameterMSB = 0xff;
|
||||
state.parameterLSB = 0xff;
|
||||
state.resetValue();
|
||||
state.isNRPN = false;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
std::optional<MidiRPNMessage> MidiRPNDetector::ChannelState::handleController (int channel,
|
||||
int controllerNumber,
|
||||
int value) noexcept
|
||||
{
|
||||
switch (controllerNumber)
|
||||
{
|
||||
case 0x62: parameterLSB = uint8 (value); resetValue(); isNRPN = true; break;
|
||||
case 0x63: parameterMSB = uint8 (value); resetValue(); isNRPN = true; break;
|
||||
|
||||
case 0x64: parameterLSB = uint8 (value); resetValue(); isNRPN = false; break;
|
||||
case 0x65: parameterMSB = uint8 (value); resetValue(); isNRPN = false; break;
|
||||
|
||||
case 0x06: valueMSB = uint8 (value); valueLSB = 0xff; return sendIfReady (channel);
|
||||
case 0x26: valueLSB = uint8 (value); return sendIfReady (channel);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void MidiRPNDetector::ChannelState::resetValue() noexcept
|
||||
{
|
||||
valueMSB = 0xff;
|
||||
valueLSB = 0xff;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
std::optional<MidiRPNMessage> MidiRPNDetector::ChannelState::sendIfReady (int channel) noexcept
|
||||
{
|
||||
if (parameterMSB >= 0x80 || parameterLSB >= 0x80 || valueMSB >= 0x80)
|
||||
return {};
|
||||
|
||||
MidiRPNMessage result{};
|
||||
result.channel = channel;
|
||||
result.parameterNumber = (parameterMSB << 7) + parameterLSB;
|
||||
result.isNRPN = isNRPN;
|
||||
|
||||
if (valueLSB < 0x80)
|
||||
{
|
||||
result.value = (valueMSB << 7) + valueLSB;
|
||||
result.is14BitValue = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
result.value = valueMSB;
|
||||
result.is14BitValue = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MidiBuffer MidiRPNGenerator::generate (MidiRPNMessage message)
|
||||
{
|
||||
return generate (message.channel,
|
||||
message.parameterNumber,
|
||||
message.value,
|
||||
message.isNRPN,
|
||||
message.is14BitValue);
|
||||
}
|
||||
|
||||
MidiBuffer MidiRPNGenerator::generate (int midiChannel,
|
||||
int parameterNumber,
|
||||
int value,
|
||||
bool isNRPN,
|
||||
bool use14BitValue)
|
||||
{
|
||||
jassert (midiChannel > 0 && midiChannel <= 16);
|
||||
jassert (parameterNumber >= 0 && parameterNumber < 16384);
|
||||
jassert (value >= 0 && value < (use14BitValue ? 16384 : 128));
|
||||
|
||||
auto parameterLSB = uint8 (parameterNumber & 0x0000007f);
|
||||
auto parameterMSB = uint8 (parameterNumber >> 7);
|
||||
|
||||
uint8 valueLSB = use14BitValue ? uint8 (value & 0x0000007f) : 0x00;
|
||||
uint8 valueMSB = use14BitValue ? uint8 (value >> 7) : uint8 (value);
|
||||
|
||||
auto channelByte = uint8 (0xb0 + midiChannel - 1);
|
||||
|
||||
MidiBuffer buffer;
|
||||
|
||||
buffer.addEvent (MidiMessage (channelByte, isNRPN ? 0x62 : 0x64, parameterLSB), 0);
|
||||
buffer.addEvent (MidiMessage (channelByte, isNRPN ? 0x63 : 0x65, parameterMSB), 0);
|
||||
|
||||
buffer.addEvent (MidiMessage (channelByte, 0x06, valueMSB), 0);
|
||||
|
||||
// According to the MIDI spec, whenever a MSB is received, the corresponding LSB will
|
||||
// be reset. Therefore, the LSB should be sent after the MSB.
|
||||
if (use14BitValue)
|
||||
buffer.addEvent (MidiMessage (channelByte, 0x26, valueLSB), 0);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class MidiRPNDetectorTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MidiRPNDetectorTests()
|
||||
: UnitTest ("MidiRPNDetector class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
// From the MIDI 1.0 spec:
|
||||
// If 128 steps of resolution is sufficient the second byte (LSB) of the data value can be
|
||||
// omitted. If both the MSB and LSB are sent initially, a subsequent fine adjustment only
|
||||
// requires the sending of the LSB. The MSB does not have to be retransmitted. If a
|
||||
// subsequent major adjustment is necessary the MSB must be transmitted again. When an MSB
|
||||
// is received, the receiver should set its concept of the LSB to zero.
|
||||
|
||||
beginTest ("Individual MSB is parsed as 7-bit");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (2, 101, 0));
|
||||
expect (! detector.tryParse (2, 100, 7));
|
||||
|
||||
auto parsed = detector.tryParse (2, 6, 42);
|
||||
expect (parsed.has_value());
|
||||
|
||||
expectEquals (parsed->channel, 2);
|
||||
expectEquals (parsed->parameterNumber, 7);
|
||||
expectEquals (parsed->value, 42);
|
||||
expect (! parsed->isNRPN);
|
||||
expect (! parsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("LSB without preceding MSB is ignored");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (2, 101, 0));
|
||||
expect (! detector.tryParse (2, 100, 7));
|
||||
expect (! detector.tryParse (2, 38, 42));
|
||||
}
|
||||
|
||||
beginTest ("LSB following MSB is parsed as 14-bit");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (1, 101, 2));
|
||||
expect (! detector.tryParse (1, 100, 44));
|
||||
|
||||
expect (detector.tryParse (1, 6, 1).has_value());
|
||||
|
||||
auto lsbParsed = detector.tryParse (1, 38, 94);
|
||||
expect (lsbParsed.has_value());
|
||||
|
||||
expectEquals (lsbParsed->channel, 1);
|
||||
expectEquals (lsbParsed->parameterNumber, 300);
|
||||
expectEquals (lsbParsed->value, 222);
|
||||
expect (! lsbParsed->isNRPN);
|
||||
expect (lsbParsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("Multiple LSB following MSB re-use the MSB");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (1, 101, 2));
|
||||
expect (! detector.tryParse (1, 100, 43));
|
||||
|
||||
expect (detector.tryParse (1, 6, 1).has_value());
|
||||
|
||||
expect (detector.tryParse (1, 38, 94).has_value());
|
||||
expect (detector.tryParse (1, 38, 95).has_value());
|
||||
expect (detector.tryParse (1, 38, 96).has_value());
|
||||
|
||||
auto lsbParsed = detector.tryParse (1, 38, 97);
|
||||
expect (lsbParsed.has_value());
|
||||
|
||||
expectEquals (lsbParsed->channel, 1);
|
||||
expectEquals (lsbParsed->parameterNumber, 299);
|
||||
expectEquals (lsbParsed->value, 225);
|
||||
expect (! lsbParsed->isNRPN);
|
||||
expect (lsbParsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("Sending a new MSB resets the LSB");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (1, 101, 3));
|
||||
expect (! detector.tryParse (1, 100, 43));
|
||||
|
||||
expect (detector.tryParse (1, 6, 1).has_value());
|
||||
expect (detector.tryParse (1, 38, 94).has_value());
|
||||
|
||||
auto newMsb = detector.tryParse (1, 6, 2);
|
||||
expect (newMsb.has_value());
|
||||
|
||||
expectEquals (newMsb->channel, 1);
|
||||
expectEquals (newMsb->parameterNumber, 427);
|
||||
expectEquals (newMsb->value, 2);
|
||||
expect (! newMsb->isNRPN);
|
||||
expect (! newMsb->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("RPNs on multiple channels simultaneously");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (1, 100, 44));
|
||||
expect (! detector.tryParse (2, 101, 0));
|
||||
expect (! detector.tryParse (1, 101, 2));
|
||||
expect (! detector.tryParse (2, 100, 7));
|
||||
expect (detector.tryParse (1, 6, 1).has_value());
|
||||
|
||||
auto channelTwo = detector.tryParse (2, 6, 42);
|
||||
expect (channelTwo.has_value());
|
||||
|
||||
expectEquals (channelTwo->channel, 2);
|
||||
expectEquals (channelTwo->parameterNumber, 7);
|
||||
expectEquals (channelTwo->value, 42);
|
||||
expect (! channelTwo->isNRPN);
|
||||
expect (! channelTwo->is14BitValue);
|
||||
|
||||
auto channelOne = detector.tryParse (1, 38, 94);
|
||||
expect (channelOne.has_value());
|
||||
|
||||
expectEquals (channelOne->channel, 1);
|
||||
expectEquals (channelOne->parameterNumber, 300);
|
||||
expectEquals (channelOne->value, 222);
|
||||
expect (! channelOne->isNRPN);
|
||||
expect (channelOne->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("14-bit RPN with value within 7-bit range");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (16, 100, 0));
|
||||
expect (! detector.tryParse (16, 101, 0));
|
||||
expect (detector.tryParse (16, 6, 0).has_value());
|
||||
|
||||
auto parsed = detector.tryParse (16, 38, 3);
|
||||
expect (parsed.has_value());
|
||||
|
||||
expectEquals (parsed->channel, 16);
|
||||
expectEquals (parsed->parameterNumber, 0);
|
||||
expectEquals (parsed->value, 3);
|
||||
expect (! parsed->isNRPN);
|
||||
expect (parsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("invalid RPN (wrong order)");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (2, 6, 42));
|
||||
expect (! detector.tryParse (2, 101, 0));
|
||||
expect (! detector.tryParse (2, 100, 7));
|
||||
}
|
||||
|
||||
beginTest ("14-bit RPN interspersed with unrelated CC messages");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (16, 3, 80));
|
||||
expect (! detector.tryParse (16, 100, 0));
|
||||
expect (! detector.tryParse (16, 4, 81));
|
||||
expect (! detector.tryParse (16, 101, 0));
|
||||
expect (! detector.tryParse (16, 5, 82));
|
||||
expect (! detector.tryParse (16, 5, 83));
|
||||
expect (detector.tryParse (16, 6, 0).has_value());
|
||||
expect (! detector.tryParse (16, 4, 84).has_value());
|
||||
expect (! detector.tryParse (16, 3, 85).has_value());
|
||||
|
||||
auto parsed = detector.tryParse (16, 38, 3);
|
||||
expect (parsed.has_value());
|
||||
|
||||
expectEquals (parsed->channel, 16);
|
||||
expectEquals (parsed->parameterNumber, 0);
|
||||
expectEquals (parsed->value, 3);
|
||||
expect (! parsed->isNRPN);
|
||||
expect (parsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("14-bit NRPN");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (1, 98, 44));
|
||||
expect (! detector.tryParse (1, 99 , 2));
|
||||
expect (detector.tryParse (1, 6, 1).has_value());
|
||||
|
||||
auto parsed = detector.tryParse (1, 38, 94);
|
||||
expect (parsed.has_value());
|
||||
|
||||
expectEquals (parsed->channel, 1);
|
||||
expectEquals (parsed->parameterNumber, 300);
|
||||
expectEquals (parsed->value, 222);
|
||||
expect (parsed->isNRPN);
|
||||
expect (parsed->is14BitValue);
|
||||
}
|
||||
|
||||
beginTest ("reset");
|
||||
{
|
||||
MidiRPNDetector detector;
|
||||
expect (! detector.tryParse (2, 101, 0));
|
||||
detector.reset();
|
||||
expect (! detector.tryParse (2, 100, 7));
|
||||
expect (! detector.tryParse (2, 6, 42));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MidiRPNDetectorTests MidiRPNDetectorUnitTests;
|
||||
|
||||
//==============================================================================
|
||||
class MidiRPNGeneratorTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MidiRPNGeneratorTests()
|
||||
: UnitTest ("MidiRPNGenerator class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("generating RPN/NRPN");
|
||||
{
|
||||
{
|
||||
MidiBuffer buffer = MidiRPNGenerator::generate (1, 23, 1337, true, true);
|
||||
expectContainsRPN (buffer, 1, 23, 1337, true, true);
|
||||
}
|
||||
{
|
||||
MidiBuffer buffer = MidiRPNGenerator::generate (16, 101, 34, false, false);
|
||||
expectContainsRPN (buffer, 16, 101, 34, false, false);
|
||||
}
|
||||
{
|
||||
MidiRPNMessage message = { 16, 101, 34, false, false };
|
||||
MidiBuffer buffer = MidiRPNGenerator::generate (message);
|
||||
expectContainsRPN (buffer, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void expectContainsRPN (const MidiBuffer& midiBuffer,
|
||||
int channel,
|
||||
int parameterNumber,
|
||||
int value,
|
||||
bool isNRPN,
|
||||
bool is14BitValue)
|
||||
{
|
||||
MidiRPNMessage expected = { channel, parameterNumber, value, isNRPN, is14BitValue };
|
||||
expectContainsRPN (midiBuffer, expected);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void expectContainsRPN (const MidiBuffer& midiBuffer, MidiRPNMessage expected)
|
||||
{
|
||||
std::optional<MidiRPNMessage> result;
|
||||
MidiRPNDetector detector;
|
||||
|
||||
for (const auto metadata : midiBuffer)
|
||||
{
|
||||
const auto midiMessage = metadata.getMessage();
|
||||
|
||||
result = detector.tryParse (midiMessage.getChannel(),
|
||||
midiMessage.getControllerNumber(),
|
||||
midiMessage.getControllerValue());
|
||||
}
|
||||
|
||||
expect (result.has_value());
|
||||
expectEquals (result->channel, expected.channel);
|
||||
expectEquals (result->parameterNumber, expected.parameterNumber);
|
||||
expectEquals (result->value, expected.value);
|
||||
expect (result->isNRPN == expected.isNRPN);
|
||||
expect (result->is14BitValue == expected.is14BitValue);
|
||||
}
|
||||
};
|
||||
|
||||
static MidiRPNGeneratorTests MidiRPNGeneratorUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/** Represents a MIDI RPN (registered parameter number) or NRPN (non-registered
|
||||
parameter number) message.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct MidiRPNMessage
|
||||
{
|
||||
/** Midi channel of the message, in the range 1 to 16. */
|
||||
int channel;
|
||||
|
||||
/** The 14-bit parameter index, in the range 0 to 16383 (0x3fff). */
|
||||
int parameterNumber;
|
||||
|
||||
/** The parameter value, in the range 0 to 16383 (0x3fff).
|
||||
If the message contains no value LSB, the value will be in the range
|
||||
0 to 127 (0x7f).
|
||||
*/
|
||||
int value;
|
||||
|
||||
/** True if this message is an NRPN; false if it is an RPN. */
|
||||
bool isNRPN;
|
||||
|
||||
/** True if the value uses 14-bit resolution (LSB + MSB); false if
|
||||
the value is 7-bit (MSB only).
|
||||
*/
|
||||
bool is14BitValue;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Parses a stream of MIDI data to assemble RPN and NRPN messages from their
|
||||
constituent MIDI CC messages.
|
||||
|
||||
The detector uses the following parsing rules: the parameter number
|
||||
LSB/MSB can be sent/received in either order and must both come before the
|
||||
parameter value; for the parameter value, LSB always has to be sent/received
|
||||
before the value MSB, otherwise it will be treated as 7-bit (MSB only).
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiRPNDetector
|
||||
{
|
||||
public:
|
||||
/** Constructor. */
|
||||
MidiRPNDetector() noexcept = default;
|
||||
|
||||
/** Destructor. */
|
||||
~MidiRPNDetector() noexcept = default;
|
||||
|
||||
/** Resets the RPN detector's internal state, so that it forgets about
|
||||
previously received MIDI CC messages.
|
||||
*/
|
||||
void reset() noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** @see tryParse() */
|
||||
[[deprecated ("Use tryParse() instead")]]
|
||||
bool parseControllerMessage (int midiChannel,
|
||||
int controllerNumber,
|
||||
int controllerValue,
|
||||
MidiRPNMessage& result) noexcept;
|
||||
|
||||
/** Takes the next in a stream of incoming MIDI CC messages and returns
|
||||
a MidiRPNMessage if the current message produces a well-formed RPN or NRPN.
|
||||
|
||||
Note that senders are expected to send the MSB before the LSB, but senders are
|
||||
not required to send a LSB at all. Therefore, tryParse() will return a non-null
|
||||
optional on all MSB messages (provided a parameter number has been set), and will
|
||||
also return a non-null optional for each LSB that follows the initial MSB.
|
||||
|
||||
This behaviour allows senders to transmit a single MSB followed by multiple LSB
|
||||
messages to facilitate fine-tuning of parameters.
|
||||
|
||||
The result of parsing a MSB will always be a 7-bit value.
|
||||
The result of parsing a LSB that follows an MSB will always be a 14-bit value.
|
||||
*/
|
||||
std::optional<MidiRPNMessage> tryParse (int midiChannel,
|
||||
int controllerNumber,
|
||||
int controllerValue);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct ChannelState
|
||||
{
|
||||
std::optional<MidiRPNMessage> handleController (int channel, int controllerNumber,
|
||||
int value) noexcept;
|
||||
void resetValue() noexcept;
|
||||
std::optional<MidiRPNMessage> sendIfReady (int channel) noexcept;
|
||||
|
||||
uint8 parameterMSB = 0xff, parameterLSB = 0xff, valueMSB = 0xff, valueLSB = 0xff;
|
||||
bool isNRPN = false;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
ChannelState states[16];
|
||||
|
||||
JUCE_LEAK_DETECTOR (MidiRPNDetector)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Generates an appropriate sequence of MIDI CC messages to represent an RPN
|
||||
or NRPN message.
|
||||
|
||||
This sequence (as a MidiBuffer) can then be directly sent to a MidiOutput.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MidiRPNGenerator
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Generates a MIDI sequence representing the given RPN or NRPN message. */
|
||||
static MidiBuffer generate (MidiRPNMessage message);
|
||||
|
||||
//==============================================================================
|
||||
/** Generates a MIDI sequence representing an RPN or NRPN message with the
|
||||
given parameters.
|
||||
|
||||
@param channel The MIDI channel of the RPN/NRPN message.
|
||||
|
||||
@param parameterNumber The parameter number, in the range 0 to 16383.
|
||||
|
||||
@param value The parameter value, in the range 0 to 16383, or
|
||||
in the range 0 to 127 if sendAs14BitValue is false.
|
||||
|
||||
@param isNRPN Whether you need a MIDI RPN or NRPN sequence (RPN is default).
|
||||
|
||||
@param use14BitValue If true (default), the value will have 14-bit precision
|
||||
(two MIDI bytes). If false, instead the value will have
|
||||
7-bit precision (a single MIDI byte).
|
||||
*/
|
||||
static MidiBuffer generate (int channel,
|
||||
int parameterNumber,
|
||||
int value,
|
||||
bool isNRPN = false,
|
||||
bool use14BitValue = true);
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#include "juce_UMPProtocols.h"
|
||||
#include "juce_UMPUtils.h"
|
||||
#include "juce_UMPacket.h"
|
||||
#include "juce_UMPSysEx7.h"
|
||||
#include "juce_UMPView.h"
|
||||
#include "juce_UMPIterator.h"
|
||||
#include "juce_UMPackets.h"
|
||||
#include "juce_UMPFactory.h"
|
||||
#include "juce_UMPConversion.h"
|
||||
#include "juce_UMPMidi1ToBytestreamTranslator.h"
|
||||
#include "juce_UMPMidi1ToMidi2DefaultTranslator.h"
|
||||
#include "juce_UMPConverters.h"
|
||||
#include "juce_UMPDispatcher.h"
|
||||
#include "juce_UMPStringUtils.h"
|
||||
|
||||
/** @cond */
|
||||
namespace juce
|
||||
{
|
||||
namespace ump = universal_midi_packets;
|
||||
}
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
/**
|
||||
Holds a UMP group, and a span of bytes that were received or are to be
|
||||
sent on that group. Helpful when working with sysex messages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct BytesOnGroup
|
||||
{
|
||||
uint8_t group{};
|
||||
Span<const std::byte> bytes;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,361 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/** Represents a MIDI message on bytestream transport that happened at a particular time.
|
||||
|
||||
Unlike MidiMessage, BytestreamMidiView is non-owning.
|
||||
*/
|
||||
struct BytestreamMidiView
|
||||
{
|
||||
constexpr BytestreamMidiView (Span<const std::byte> bytesIn, double timestampIn)
|
||||
: bytes (bytesIn), timestamp (timestampIn) {}
|
||||
|
||||
/** Creates a view over the provided message.
|
||||
|
||||
Note that the argument is a pointer, not a reference, in order to avoid taking a reference
|
||||
to a temporary.
|
||||
*/
|
||||
explicit BytestreamMidiView (const MidiMessage* msg)
|
||||
: bytes (msg->asSpan()),
|
||||
timestamp (msg->getTimeStamp()) {}
|
||||
|
||||
explicit BytestreamMidiView (const MidiMessageMetadata msg)
|
||||
: bytes (msg.asSpan()),
|
||||
timestamp (msg.samplePosition) {}
|
||||
|
||||
MidiMessage getMessage() const
|
||||
{
|
||||
return MidiMessage (bytes.data(), (int) bytes.size(), timestamp);
|
||||
}
|
||||
|
||||
MidiMessageMetadata getMidiMessageMetadata() const
|
||||
{
|
||||
return MidiMessageMetadata { reinterpret_cast<const uint8*> (bytes.data()),
|
||||
(int) bytes.size(),
|
||||
(int) timestamp };
|
||||
}
|
||||
|
||||
Span<const std::byte> bytes;
|
||||
double timestamp = 0.0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Functions to assist conversion of UMP messages to/from other formats,
|
||||
especially older 'bytestream' formatted MidiMessages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct Conversion
|
||||
{
|
||||
/** Converts 7-bit data (the most significant bit of each byte must be unset) to a series of
|
||||
Universal MIDI Packets.
|
||||
*/
|
||||
template <typename PacketCallbackFunction>
|
||||
static void umpFrom7BitData (BytesOnGroup msg, PacketCallbackFunction&& callback)
|
||||
{
|
||||
// If this is hit, non-7-bit data was supplied.
|
||||
// Maybe you forgot to trim the leading/trailing bytes that delimit a bytestream SysEx message.
|
||||
jassert (std::all_of (msg.bytes.begin(), msg.bytes.end(), [] (std::byte b) { return (b & std::byte { 0x80 }) == std::byte{}; }));
|
||||
|
||||
Factory::splitIntoPackets (msg.bytes, 6, [&] (SysEx7::Kind kind, Span<const std::byte> bytesThisTime)
|
||||
{
|
||||
const auto packet = Factory::Detail::makeSysEx (msg.group, kind, bytesThisTime);
|
||||
const uint32_t paddedPacket[] { packet[0], packet[1], 0, 0 };
|
||||
callback (View (paddedPacket));
|
||||
});
|
||||
}
|
||||
|
||||
/** Converts from a MIDI 1 bytestream to MIDI 1 on Universal MIDI Packets.
|
||||
|
||||
@param bytes the bytes in a single well-formed bytestream MIDI message
|
||||
@param callback a function that accepts a single View argument. This may be called several
|
||||
times for each invocation of toMidi1 if the bytestream message converts
|
||||
to multiple Universal MIDI Packets.
|
||||
*/
|
||||
template <typename PacketCallbackFunction>
|
||||
static void toMidi1 (const BytesOnGroup& groupBytes, PacketCallbackFunction&& callback)
|
||||
{
|
||||
const auto size = groupBytes.bytes.size();
|
||||
|
||||
if (size <= 0)
|
||||
return;
|
||||
|
||||
const auto* data = groupBytes.bytes.data();
|
||||
const auto firstByte = data[0];
|
||||
|
||||
if (firstByte != std::byte { 0xf0 })
|
||||
{
|
||||
const auto mask = [size]() -> uint32_t
|
||||
{
|
||||
switch (size)
|
||||
{
|
||||
case 0: return 0xff000000;
|
||||
case 1: return 0xffff0000;
|
||||
case 2: return 0xffffff00;
|
||||
case 3: return 0xffffffff;
|
||||
}
|
||||
|
||||
// This function can only handle a single bytestream MIDI message at a time!
|
||||
jassertfalse;
|
||||
return 0x00000000;
|
||||
}();
|
||||
|
||||
const auto extraByte = ((((firstByte & std::byte { 0xf0 }) == std::byte { 0xf0 }) ? std::byte { 0x1 } : std::byte { 0x2 }) << 0x4);
|
||||
const std::byte group { (uint8_t) (groupBytes.group & 0xf) };
|
||||
const uint32_t packet[] { mask & Utils::bytesToWord (extraByte | group, data[0], data[1], data[2]), 0, 0, 0 };
|
||||
callback (View (packet));
|
||||
return;
|
||||
}
|
||||
|
||||
umpFrom7BitData ({ groupBytes.group, Span (data + 1, size - 2) }, std::forward<PacketCallbackFunction> (callback));
|
||||
}
|
||||
|
||||
/** Widens a 7-bit MIDI 1.0 value to a 8-bit MIDI 2.0 value. */
|
||||
static uint8_t scaleTo8 (uint8_t word7Bit)
|
||||
{
|
||||
const auto shifted = (uint8_t) (word7Bit << 0x1);
|
||||
const auto repeat = (uint8_t) (word7Bit & 0x3f);
|
||||
const auto mask = (uint8_t) (word7Bit <= 0x40 ? 0x0 : 0xff);
|
||||
return (uint8_t) (shifted | ((repeat >> 5) & mask));
|
||||
}
|
||||
|
||||
/** Widens a 7-bit MIDI 1.0 value to a 16-bit MIDI 2.0 value. */
|
||||
static uint16_t scaleTo16 (uint8_t word7Bit)
|
||||
{
|
||||
const auto shifted = (uint16_t) (word7Bit << 0x9);
|
||||
const auto repeat = (uint16_t) (word7Bit & 0x3f);
|
||||
const auto mask = (uint16_t) (word7Bit <= 0x40 ? 0x0 : 0xffff);
|
||||
return (uint16_t) (shifted | (((repeat << 3) | (repeat >> 3)) & mask));
|
||||
}
|
||||
|
||||
/** Widens a 14-bit MIDI 1.0 value to a 16-bit MIDI 2.0 value. */
|
||||
static uint16_t scaleTo16 (uint16_t word14Bit)
|
||||
{
|
||||
const auto shifted = (uint16_t) (word14Bit << 0x2);
|
||||
const auto repeat = (uint16_t) (word14Bit & 0x1fff);
|
||||
const auto mask = (uint16_t) (word14Bit <= 0x2000 ? 0x0 : 0xffff);
|
||||
return (uint16_t) (shifted | ((repeat >> 11) & mask));
|
||||
}
|
||||
|
||||
/** Widens a 7-bit MIDI 1.0 value to a 32-bit MIDI 2.0 value. */
|
||||
static uint32_t scaleTo32 (uint8_t word7Bit)
|
||||
{
|
||||
const auto shifted = (uint32_t) (word7Bit << 0x19);
|
||||
const auto repeat = (uint32_t) (word7Bit & 0x3f);
|
||||
const auto mask = (uint32_t) (word7Bit <= 0x40 ? 0x0 : 0xffffffff);
|
||||
return (uint32_t) (shifted | (((repeat << 19)
|
||||
| (repeat << 13)
|
||||
| (repeat << 7)
|
||||
| (repeat << 1)
|
||||
| (repeat >> 5)) & mask));
|
||||
}
|
||||
|
||||
/** Widens a 14-bit MIDI 1.0 value to a 32-bit MIDI 2.0 value. */
|
||||
static uint32_t scaleTo32 (uint16_t word14Bit)
|
||||
{
|
||||
const auto shifted = (uint32_t) (word14Bit << 0x12);
|
||||
const auto repeat = (uint32_t) (word14Bit & 0x1fff);
|
||||
const auto mask = (uint32_t) (word14Bit <= 0x2000 ? 0x0 : 0xffffffff);
|
||||
return (uint32_t) (shifted | (((repeat << 5) | (repeat >> 8)) & mask));
|
||||
}
|
||||
|
||||
/** Narrows a 16-bit MIDI 2.0 value to a 7-bit MIDI 1.0 value. */
|
||||
static uint8_t scaleTo7 (uint8_t word8Bit) { return (uint8_t) (word8Bit >> 1); }
|
||||
|
||||
/** Narrows a 16-bit MIDI 2.0 value to a 7-bit MIDI 1.0 value. */
|
||||
static uint8_t scaleTo7 (uint16_t word16Bit) { return (uint8_t) (word16Bit >> 9); }
|
||||
|
||||
/** Narrows a 32-bit MIDI 2.0 value to a 7-bit MIDI 1.0 value. */
|
||||
static uint8_t scaleTo7 (uint32_t word32Bit) { return (uint8_t) (word32Bit >> 25); }
|
||||
|
||||
/** Narrows a 32-bit MIDI 2.0 value to a 14-bit MIDI 1.0 value. */
|
||||
static uint16_t scaleTo14 (uint16_t word16Bit) { return (uint16_t) (word16Bit >> 2); }
|
||||
|
||||
/** Narrows a 32-bit MIDI 2.0 value to a 14-bit MIDI 1.0 value. */
|
||||
static uint16_t scaleTo14 (uint32_t word32Bit) { return (uint16_t) (word32Bit >> 18); }
|
||||
|
||||
/** Converts UMP messages which may include MIDI 2.0 channel voice messages into
|
||||
equivalent MIDI 1.0 messages (still in UMP format).
|
||||
|
||||
`callback` is a function that accepts a single View argument and will be
|
||||
called with each converted packet.
|
||||
|
||||
Note that not all MIDI 2.0 messages have MIDI 1.0 equivalents, so such
|
||||
messages will be ignored.
|
||||
*/
|
||||
template <typename Callback>
|
||||
static void midi2ToMidi1DefaultTranslation (const View& v, Callback&& callback)
|
||||
{
|
||||
const auto firstWord = v[0];
|
||||
|
||||
if (Utils::getMessageType (firstWord) != Utils::MessageKind::channelVoice2)
|
||||
{
|
||||
callback (v);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto status = Utils::getStatus (firstWord);
|
||||
const auto typeAndGroup = ((std::byte { 0x2 } << 0x4) | std::byte { Utils::getGroup (firstWord) });
|
||||
|
||||
switch ((uint8_t) status)
|
||||
{
|
||||
case 0x8: // note off
|
||||
case 0x9: // note on
|
||||
case 0xa: // poly pressure
|
||||
case 0xb: // control change
|
||||
{
|
||||
const auto statusAndChannel = std::byte ((firstWord >> 0x10) & 0xff);
|
||||
const auto byte2 = std::byte ((firstWord >> 0x08) & 0xff);
|
||||
const auto byte3 = std::byte { scaleTo7 (v[1]) };
|
||||
|
||||
// If this is a note-on, and the scaled byte is 0,
|
||||
// the scaled velocity should be 1 instead of 0
|
||||
const auto needsCorrection = status == std::byte { 0x9 } && byte3 == std::byte { 0 };
|
||||
const auto correctedByte = needsCorrection ? std::byte { 1 } : byte3;
|
||||
|
||||
const auto shouldIgnore = status == std::byte { 0xb } && [&]
|
||||
{
|
||||
switch (uint8_t (byte2))
|
||||
{
|
||||
case 0:
|
||||
case 6:
|
||||
case 32:
|
||||
case 38:
|
||||
case 98:
|
||||
case 99:
|
||||
case 100:
|
||||
case 101:
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}();
|
||||
|
||||
if (shouldIgnore)
|
||||
return;
|
||||
|
||||
const PacketX1 packet { Utils::bytesToWord (typeAndGroup,
|
||||
statusAndChannel,
|
||||
byte2,
|
||||
correctedByte) };
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xd: // channel pressure
|
||||
{
|
||||
const auto statusAndChannel = std::byte ((firstWord >> 0x10) & 0xff);
|
||||
const auto byte2 = std::byte { scaleTo7 (v[1]) };
|
||||
|
||||
const PacketX1 packet { Utils::bytesToWord (typeAndGroup,
|
||||
statusAndChannel,
|
||||
byte2,
|
||||
std::byte { 0 }) };
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0x2: // rpn
|
||||
case 0x3: // nrpn
|
||||
{
|
||||
const auto ccX = status == std::byte { 0x2 } ? std::byte { 101 } : std::byte { 99 };
|
||||
const auto ccY = status == std::byte { 0x2 } ? std::byte { 100 } : std::byte { 98 };
|
||||
const auto statusAndChannel = std::byte ((0xb << 0x4) | Utils::getChannel (firstWord));
|
||||
const auto data = scaleTo14 (v[1]);
|
||||
|
||||
const PacketX1 packets[]
|
||||
{
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, ccX, std::byte ((firstWord >> 0x8) & 0x7f)) },
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, ccY, std::byte ((firstWord >> 0x0) & 0x7f)) },
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, std::byte { 6 }, std::byte ((data >> 0x7) & 0x7f)) },
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, std::byte { 38 }, std::byte ((data >> 0x0) & 0x7f)) },
|
||||
};
|
||||
|
||||
for (const auto& packet : packets)
|
||||
callback (View (packet.data()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xc: // program change / bank select
|
||||
{
|
||||
if (firstWord & 1)
|
||||
{
|
||||
const auto statusAndChannel = std::byte ((0xb << 0x4) | Utils::getChannel (firstWord));
|
||||
const auto secondWord = v[1];
|
||||
|
||||
const PacketX1 packets[]
|
||||
{
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, std::byte { 0 }, std::byte ((secondWord >> 0x8) & 0x7f)) },
|
||||
PacketX1 { Utils::bytesToWord (typeAndGroup, statusAndChannel, std::byte { 32 }, std::byte ((secondWord >> 0x0) & 0x7f)) },
|
||||
};
|
||||
|
||||
for (const auto& packet : packets)
|
||||
callback (View (packet.data()));
|
||||
}
|
||||
|
||||
const auto statusAndChannel = std::byte ((0xc << 0x4) | Utils::getChannel (firstWord));
|
||||
const PacketX1 packet { Utils::bytesToWord (typeAndGroup,
|
||||
statusAndChannel,
|
||||
std::byte ((v[1] >> 0x18) & 0x7f),
|
||||
std::byte { 0 }) };
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xe: // pitch bend
|
||||
{
|
||||
const auto data = scaleTo14 (v[1]);
|
||||
const auto statusAndChannel = std::byte ((firstWord >> 0x10) & 0xff);
|
||||
const PacketX1 packet { Utils::bytesToWord (typeAndGroup,
|
||||
statusAndChannel,
|
||||
std::byte (data & 0x7f),
|
||||
std::byte ((data >> 7) & 0x7f)) };
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
default: // other message types do not translate
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,214 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
/**
|
||||
Allows conversion from bytestream- or Universal MIDI Packet-formatted
|
||||
messages to MIDI 1.0 messages in UMP format.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct ToUMP1Converter
|
||||
{
|
||||
template <typename Fn>
|
||||
void convert (const BytesOnGroup& m, Fn&& fn)
|
||||
{
|
||||
Conversion::toMidi1 (m, std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const View& v, Fn&& fn)
|
||||
{
|
||||
Conversion::midi2ToMidi1DefaultTranslation (v, std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
/**
|
||||
Allows conversion from bytestream- or Universal MIDI Packet-formatted
|
||||
messages to MIDI 2.0 messages in UMP format.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct ToUMP2Converter
|
||||
{
|
||||
template <typename Fn>
|
||||
void convert (const BytesOnGroup& m, Fn&& fn)
|
||||
{
|
||||
Conversion::toMidi1 (m, [&] (const View& v)
|
||||
{
|
||||
translator.dispatch (v, fn);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const View& v, Fn&& fn)
|
||||
{
|
||||
translator.dispatch (v, std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
translator.reset();
|
||||
}
|
||||
|
||||
Midi1ToMidi2DefaultTranslator translator;
|
||||
};
|
||||
|
||||
/**
|
||||
Allows conversion from bytestream- or Universal MIDI Packet-formatted
|
||||
messages to UMP format.
|
||||
|
||||
The packet protocol can be selected using the constructor parameter.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class GenericUMPConverter
|
||||
{
|
||||
using Converters = std::variant<ToUMP1Converter, ToUMP2Converter>;
|
||||
|
||||
template <typename This, typename Fn>
|
||||
static void visit (This& t, Fn&& fn)
|
||||
{
|
||||
if (auto* converter1 = std::get_if<ToUMP1Converter> (&t.converters))
|
||||
fn (*converter1);
|
||||
else if (auto* converter2 = std::get_if<ToUMP2Converter> (&t.converters))
|
||||
fn (*converter2);
|
||||
}
|
||||
|
||||
public:
|
||||
explicit GenericUMPConverter (PacketProtocol m)
|
||||
: converters (m == PacketProtocol::MIDI_1_0 ? Converters (ToUMP1Converter()) : Converters (ToUMP2Converter())) {}
|
||||
|
||||
void reset()
|
||||
{
|
||||
visit (*this, [] (auto& c) { c.reset(); });
|
||||
}
|
||||
|
||||
template <typename Converter, typename Fn>
|
||||
static void convertImpl (Converter& converter, const BytesOnGroup& m, Fn&& fn)
|
||||
{
|
||||
converter.convert (m, std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
template <typename Converter, typename Fn>
|
||||
static void convertImpl (Converter& converter, const View& m, Fn&& fn)
|
||||
{
|
||||
converter.convert (m, std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
template <typename Converter, typename Fn>
|
||||
static void convertImpl (Converter& converter, Iterator b, Iterator e, Fn&& fn)
|
||||
{
|
||||
std::for_each (b, e, [&] (const auto& v)
|
||||
{
|
||||
convertImpl (converter, v, fn);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Converter, typename Fn>
|
||||
static void convertImpl (Converter& converter, const Packets& packets, Fn&& fn)
|
||||
{
|
||||
convertImpl (converter, packets.begin(), packets.end(), std::forward<Fn> (fn));
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const BytesOnGroup& m, Fn&& fn)
|
||||
{
|
||||
visit (*this, [&] (auto& c) { convertImpl (c, m, std::forward<Fn> (fn)); });
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const View& v, Fn&& fn)
|
||||
{
|
||||
visit (*this, [&] (auto& c) { convertImpl (c, v, std::forward<Fn> (fn)); });
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (Iterator begin, Iterator end, Fn&& fn)
|
||||
{
|
||||
visit (*this, [&] (auto& c) { convertImpl (c, begin, end, std::forward<Fn> (fn)); });
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const Packets& packets, Fn&& fn)
|
||||
{
|
||||
visit (*this, [&] (auto& c) { convertImpl (c, packets, std::forward<Fn> (fn)); });
|
||||
}
|
||||
|
||||
PacketProtocol getProtocol() const noexcept
|
||||
{
|
||||
return std::holds_alternative<ToUMP1Converter> (converters) ? PacketProtocol::MIDI_1_0
|
||||
: PacketProtocol::MIDI_2_0;
|
||||
}
|
||||
|
||||
private:
|
||||
Converters converters;
|
||||
};
|
||||
|
||||
/**
|
||||
Allows conversion from bytestream- or Universal MIDI Packet-formatted
|
||||
messages to bytestream format.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct ToBytestreamConverter
|
||||
{
|
||||
explicit ToBytestreamConverter (int storageSize)
|
||||
: translator (storageSize) {}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const MidiMessage& m, Fn&& fn)
|
||||
{
|
||||
fn (m);
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void convert (const View& v, double time, Fn&& fn)
|
||||
{
|
||||
Conversion::midi2ToMidi1DefaultTranslation (v, [&] (const View& midi1)
|
||||
{
|
||||
translator.dispatch (midi1, time, fn);
|
||||
});
|
||||
}
|
||||
|
||||
void reset() { translator.reset(); }
|
||||
|
||||
SingleGroupMidi1ToBytestreamTranslator translator;
|
||||
};
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 DeviceInfo::tie() const
|
||||
{
|
||||
return std::tie (manufacturer, family, modelNumber, revision);
|
||||
}
|
||||
|
||||
bool DeviceInfo::operator== (const DeviceInfo& other) const
|
||||
{
|
||||
return tie() == other.tie();
|
||||
}
|
||||
|
||||
bool DeviceInfo::operator!= (const DeviceInfo& other) const
|
||||
{
|
||||
return tie() != other.tie();
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
/**
|
||||
Holds MIDI device info that may be required by certain UMP messages and
|
||||
MIDI-CI messages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct DeviceInfo
|
||||
{
|
||||
std::array<std::byte, 3> manufacturer;
|
||||
std::array<std::byte, 2> family; ///< LSB first
|
||||
std::array<std::byte, 2> modelNumber; ///< LSB first
|
||||
std::array<std::byte, 4> revision;
|
||||
|
||||
private:
|
||||
auto tie() const;
|
||||
|
||||
public:
|
||||
bool operator== (const DeviceInfo& other) const;
|
||||
bool operator!= (const DeviceInfo& other) const;
|
||||
|
||||
static constexpr auto marshallingVersion = std::nullopt;
|
||||
|
||||
template <typename Archive, typename This>
|
||||
static auto serialise (Archive& archive, This& t)
|
||||
{
|
||||
return archive (named ("manufacturer", t.manufacturer),
|
||||
named ("family", t.family),
|
||||
named ("modelNumber", t.modelNumber),
|
||||
named ("revision", t.revision));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Parses a raw stream of uint32_t, and calls a user-provided callback every time
|
||||
a full Universal MIDI Packet is encountered.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Dispatcher
|
||||
{
|
||||
public:
|
||||
/** Clears the dispatcher. */
|
||||
void reset() { currentPacketLen = 0; }
|
||||
|
||||
/** Calls `callback` with a View of each packet encountered in the range delimited
|
||||
by `begin` and `end`.
|
||||
|
||||
If the range ends part-way through a packet, the next call to `dispatch` will
|
||||
continue from that point in the packet (unless `reset` is called first).
|
||||
*/
|
||||
template <typename PacketCallbackFunction>
|
||||
void dispatch (Span<const uint32_t> words,
|
||||
double timeStamp,
|
||||
PacketCallbackFunction&& callback)
|
||||
{
|
||||
for (const auto word : words)
|
||||
{
|
||||
nextPacket[currentPacketLen++] = word;
|
||||
|
||||
if (currentPacketLen == Utils::getNumWordsForMessageType (nextPacket.front()))
|
||||
{
|
||||
callback (View (nextPacket.data()), timeStamp);
|
||||
currentPacketLen = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<uint32_t, 4> nextPacket;
|
||||
size_t currentPacketLen = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Parses a stream of bytes representing a sequence of bytestream-encoded MIDI 1.0 messages,
|
||||
converting the messages to UMP format and passing the packets to a user-provided callback
|
||||
as they become ready.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class BytestreamToUMPDispatcher
|
||||
{
|
||||
public:
|
||||
/** Initialises the dispatcher.
|
||||
|
||||
Channel messages will be converted to the requested protocol format `pp`.
|
||||
`storageSize` bytes will be allocated to store incomplete messages.
|
||||
*/
|
||||
BytestreamToUMPDispatcher (uint8_t targetGroup, PacketProtocol pp, int storageSize)
|
||||
: concatenator (storageSize),
|
||||
converter (pp),
|
||||
group (targetGroup)
|
||||
{}
|
||||
|
||||
void reset()
|
||||
{
|
||||
concatenator.reset();
|
||||
converter.reset();
|
||||
}
|
||||
|
||||
/** Calls `callback` with a View of each converted packet as it becomes ready.
|
||||
|
||||
@param bytes range of bytes representing bytestream-encoded MIDI messages.
|
||||
@param timestamp a timestamp to apply to the created packets.
|
||||
@param callback a callback which will be passed a View pointing to each new packet as it becomes ready.
|
||||
*/
|
||||
template <typename PacketCallbackFunction>
|
||||
void dispatch (Span<const std::byte> bytes,
|
||||
double timestamp,
|
||||
PacketCallbackFunction&& callback)
|
||||
{
|
||||
using CallbackPtr = decltype (std::addressof (callback));
|
||||
|
||||
struct Callback
|
||||
{
|
||||
Callback (BytestreamToUMPDispatcher& d, CallbackPtr c)
|
||||
: dispatch (d), callbackPtr (c) {}
|
||||
|
||||
void handleIncomingMidiMessage (void*, const MidiMessage& msg) const
|
||||
{
|
||||
Conversion::toMidi1 ({ dispatch.group, msg.asSpan() }, [&] (const View& view)
|
||||
{
|
||||
dispatch.converter.convert (view, [&] (const View& v)
|
||||
{
|
||||
(*callbackPtr) (v, msg.getTimeStamp());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void handlePartialSysexMessage (void*, const uint8*, int, double) const {}
|
||||
|
||||
BytestreamToUMPDispatcher& dispatch;
|
||||
CallbackPtr callbackPtr = nullptr;
|
||||
};
|
||||
|
||||
Callback inputCallback { *this, &callback };
|
||||
concatenator.pushMidiData (bytes, timestamp, (void*) nullptr, inputCallback);
|
||||
}
|
||||
|
||||
PacketProtocol getProtocol() const
|
||||
{
|
||||
return converter.getProtocol();
|
||||
}
|
||||
|
||||
private:
|
||||
MidiDataConcatenator concatenator;
|
||||
GenericUMPConverter converter;
|
||||
uint8_t group{};
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Parses a stream of 32-bit words representing a sequence of UMP-encoded MIDI messages,
|
||||
converting the messages to MIDI 1.0 bytestream format and passing them to a user-provided
|
||||
callback as they become ready.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class ToBytestreamDispatcher
|
||||
{
|
||||
public:
|
||||
/** Initialises the dispatcher.
|
||||
|
||||
`storageSize` bytes will be allocated to store incomplete messages.
|
||||
*/
|
||||
explicit ToBytestreamDispatcher (int storageSize)
|
||||
: converter (storageSize) {}
|
||||
|
||||
/** Clears the dispatcher. */
|
||||
void reset()
|
||||
{
|
||||
dispatcher.reset();
|
||||
converter.reset();
|
||||
}
|
||||
|
||||
/** Calls `callback` with converted bytestream-formatted MidiMessage whenever
|
||||
a new message becomes available.
|
||||
|
||||
@param begin the first word in a stream of words representing UMP-encoded MIDI packets.
|
||||
@param end one-past the last word in a stream of words representing UMP-encoded MIDI packets.
|
||||
@param timestamp a timestamp to apply to converted messages.
|
||||
@param callback a callback which will be passed a MidiMessage each time a new message becomes ready.
|
||||
*/
|
||||
template <typename BytestreamMessageCallback>
|
||||
void dispatch (Span<const uint32_t> words,
|
||||
double timestamp,
|
||||
BytestreamMessageCallback&& callback)
|
||||
{
|
||||
dispatcher.dispatch (words, timestamp, [&] (const View& view, double time)
|
||||
{
|
||||
converter.convert (view, time, callback);
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
Dispatcher dispatcher;
|
||||
ToBytestreamConverter converter;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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 EndpointInfo::tie() const
|
||||
{
|
||||
return std::tie (versionMajor, versionMinor, numFunctionBlocks, flags);
|
||||
}
|
||||
|
||||
bool EndpointInfo::operator== (const EndpointInfo& other) const
|
||||
{
|
||||
return tie() == other.tie();
|
||||
}
|
||||
|
||||
bool EndpointInfo::operator!= (const EndpointInfo& other) const
|
||||
{
|
||||
return tie() != other.tie();
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,914 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Holds the data from a stream configuration notification message, with strong types.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class StreamConfiguration
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] StreamConfiguration withProtocol (PacketProtocol p) const { return withFlag (isMidi2, p == PacketProtocol::MIDI_2_0); }
|
||||
[[nodiscard]] StreamConfiguration withTransmitTimestamp (bool b) const { return withFlag (transmitTimestamp, b); }
|
||||
[[nodiscard]] StreamConfiguration withReceiveTimestamp (bool b) const { return withFlag (receiveTimestamp, b); }
|
||||
|
||||
/** The protocol in use by the endpoint. This protocol will be used for sending and receiving messages. */
|
||||
[[nodiscard]] PacketProtocol getProtocol() const { return getFlag (isMidi2) ? PacketProtocol::MIDI_2_0 : PacketProtocol::MIDI_1_0; }
|
||||
/** True if this endpoint intends to send JR timestamps. */
|
||||
[[nodiscard]] bool getTransmitTimestamp() const { return getFlag (transmitTimestamp); }
|
||||
/** True if this endpoint expects to receive JR timestamps. */
|
||||
[[nodiscard]] bool getReceiveTimestamp() const { return getFlag (receiveTimestamp); }
|
||||
|
||||
bool operator== (const StreamConfiguration& other) const { return options == other.options; }
|
||||
bool operator!= (const StreamConfiguration& other) const { return options != other.options; }
|
||||
|
||||
private:
|
||||
enum Flags
|
||||
{
|
||||
isMidi2 = 1 << 0,
|
||||
transmitTimestamp = 1 << 1,
|
||||
receiveTimestamp = 1 << 2,
|
||||
};
|
||||
|
||||
StreamConfiguration withFlag (Flags f, bool value) const
|
||||
{
|
||||
return withMember (*this, &StreamConfiguration::options, value ? (options | f) : (options & ~f));
|
||||
}
|
||||
|
||||
bool getFlag (Flags f) const
|
||||
{
|
||||
return (options & f) != 0;
|
||||
}
|
||||
|
||||
int options = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
Holds the data from an endpoint info notification message, with strong types.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class EndpointInfo
|
||||
{
|
||||
auto tie() const;
|
||||
|
||||
public:
|
||||
[[nodiscard]] EndpointInfo withVersion (uint8_t major, uint8_t minor) const
|
||||
{
|
||||
return withMember (withMember (*this, &EndpointInfo::versionMinor, minor), &EndpointInfo::versionMajor, major);
|
||||
}
|
||||
|
||||
[[nodiscard]] EndpointInfo withNumFunctionBlocks (uint8_t x) const
|
||||
{
|
||||
return withMember (*this, &EndpointInfo::numFunctionBlocks, x);
|
||||
}
|
||||
|
||||
[[nodiscard]] EndpointInfo withStaticFunctionBlocks (bool b) const { return withFlag (staticFunctionBlocks, b); }
|
||||
[[nodiscard]] EndpointInfo withMidi1Support (bool b) const { return withFlag (supportsMidi1, b); }
|
||||
[[nodiscard]] EndpointInfo withMidi2Support (bool b) const { return withFlag (supportsMidi2, b); }
|
||||
[[nodiscard]] EndpointInfo withReceiveJRSupport (bool b) const { return withFlag (supportsReceiveJR, b); }
|
||||
[[nodiscard]] EndpointInfo withTransmitJRSupport (bool b) const { return withFlag (supportsTransmitJR, b); }
|
||||
|
||||
/** The major version byte. */
|
||||
[[nodiscard]] uint8_t getVersionMajor() const { return versionMajor; }
|
||||
/** The minor version byte. */
|
||||
[[nodiscard]] uint8_t getVersionMinor() const { return versionMinor; }
|
||||
/** The number of function blocks declared on this endpoint. */
|
||||
[[nodiscard]] uint8_t getNumFunctionBlocks() const { return numFunctionBlocks; }
|
||||
/** True if the function block configuration cannot change. */
|
||||
[[nodiscard]] bool hasStaticFunctionBlocks() const { return getFlag (staticFunctionBlocks); }
|
||||
/** True if this endpoint is capable of supporting the MIDI 1.0 protocol. */
|
||||
[[nodiscard]] bool hasMidi1Support() const { return getFlag (supportsMidi1); }
|
||||
/** True if this endpoint is capable of supporting the MIDI 2.0 protocol. */
|
||||
[[nodiscard]] bool hasMidi2Support() const { return getFlag (supportsMidi2); }
|
||||
/** True if this endpoint is capable of receiving JR timestamps. */
|
||||
[[nodiscard]] bool hasReceiveJRSupport() const { return getFlag (supportsReceiveJR); }
|
||||
/** True if this endpoint is capable of transmitting JR timestamps. */
|
||||
[[nodiscard]] bool hasTransmitJRSupport() const { return getFlag (supportsTransmitJR); }
|
||||
|
||||
bool operator== (const EndpointInfo& other) const;
|
||||
bool operator!= (const EndpointInfo& other) const;
|
||||
|
||||
private:
|
||||
enum Flags
|
||||
{
|
||||
staticFunctionBlocks = 1 << 0,
|
||||
supportsMidi1 = 1 << 1,
|
||||
supportsMidi2 = 1 << 2,
|
||||
supportsReceiveJR = 1 << 3,
|
||||
supportsTransmitJR = 1 << 4,
|
||||
};
|
||||
|
||||
EndpointInfo withFlag (Flags f, bool value) const
|
||||
{
|
||||
return withMember (*this, &EndpointInfo::flags, (uint8_t) (value ? (flags | f) : (flags & ~f)));
|
||||
}
|
||||
|
||||
bool getFlag (Flags f) const
|
||||
{
|
||||
return (flags & f) != 0;
|
||||
}
|
||||
|
||||
uint8_t versionMajor, versionMinor, numFunctionBlocks, flags;
|
||||
};
|
||||
|
||||
/** Directions that can apply to a Function Block or Group Terminal Block. */
|
||||
enum class BlockDirection : uint8_t
|
||||
{
|
||||
unknown = 0b00, ///< Block direction is unknown or undeclared
|
||||
receiver = 0b01, ///< Block is a receiver of messages
|
||||
sender = 0b10, ///< Block is a sender of messages
|
||||
bidirectional = 0b11, ///< Block both sends and receives messages
|
||||
};
|
||||
|
||||
/** UI hints that can apply to a Function Block or Group Terminal Block. */
|
||||
enum class BlockUiHint : uint8_t
|
||||
{
|
||||
unknown = 0b00, ///< Block direction is unknown or undeclared
|
||||
receiver = 0b01, ///< Block is a receiver of messages
|
||||
sender = 0b10, ///< Block is a sender of messages
|
||||
bidirectional = 0b11, ///< Block both sends and receives messages
|
||||
};
|
||||
|
||||
/** Describes how a MIDI 1.0 port maps to a given Block, if applicable. */
|
||||
enum class BlockMIDI1ProxyKind : uint8_t
|
||||
{
|
||||
inapplicable = 0b00, ///< Block does not represent a MIDI 1.0 port
|
||||
unrestrictedBandwidth = 0b01, ///< Block represents a MIDI 1.0 port and can handle high bandwidth
|
||||
restrictedBandwidth = 0b10, ///< Block represents a MIDI 1.0 port that requires restricted bandwidth
|
||||
};
|
||||
|
||||
/**
|
||||
Holds the data from a function block info notification message, with strong types.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class BlockInfo
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] BlockInfo withEnabled (bool x) const { return withMember (*this, &BlockInfo::enabled, x); }
|
||||
[[nodiscard]] BlockInfo withUiHint (BlockUiHint x) const { return withMember (*this, &BlockInfo::flags, replaceBits<4, 2> (flags, (uint8_t) x)); }
|
||||
[[nodiscard]] BlockInfo withMIDI1ProxyKind (BlockMIDI1ProxyKind x) const { return withMember (*this, &BlockInfo::flags, replaceBits<2, 2> (flags, (uint8_t) x)); }
|
||||
[[nodiscard]] BlockInfo withDirection (BlockDirection x) const { return withMember (*this, &BlockInfo::flags, replaceBits<0, 2> (flags, (uint8_t) x)); }
|
||||
[[nodiscard]] BlockInfo withFirstGroup (uint8_t x) const { return withMember (*this, &BlockInfo::firstGroup, x); }
|
||||
[[nodiscard]] BlockInfo withNumGroups (uint8_t x) const { return withMember (*this, &BlockInfo::numGroups, x); }
|
||||
[[nodiscard]] BlockInfo withCiVersion (uint8_t x) const { return withMember (*this, &BlockInfo::ciVersion, x); }
|
||||
[[nodiscard]] BlockInfo withMaxSysex8Streams (uint8_t x) const { return withMember (*this, &BlockInfo::numSysex8Streams, x); }
|
||||
|
||||
/** True if the block is enabled/active, false otherwise. */
|
||||
bool isEnabled() const { return enabled; }
|
||||
/** The directionality of the block, for display to the user. */
|
||||
BlockUiHint getUiHint() const { return (BlockUiHint) getBits<4, 2> (flags); }
|
||||
/** The kind of MIDI 1.0 proxy represented by this block, if any. */
|
||||
BlockMIDI1ProxyKind getMIDI1ProxyKind() const { return (BlockMIDI1ProxyKind) getBits<2, 2> (flags); }
|
||||
/** The actual directionality of the block. */
|
||||
BlockDirection getDirection() const { return (BlockDirection) getBits<0, 2> (flags); }
|
||||
/** The zero-based index of the first group in the block. */
|
||||
uint8_t getFirstGroup() const { return firstGroup; }
|
||||
/** The number of groups contained in the block, must be one or greater. */
|
||||
uint8_t getNumGroups() const { return numGroups; }
|
||||
/** The CI version supported by this block. Implies a bidirectional block. */
|
||||
uint8_t getCiVersion() const { return ciVersion; }
|
||||
/** The number of simultaneous SysEx8 streams supported on this block. */
|
||||
uint8_t getMaxSysex8Streams() const { return numSysex8Streams; }
|
||||
|
||||
bool operator== (const BlockInfo& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x)
|
||||
{
|
||||
return std::tuple (x.enabled, x.flags, x.firstGroup, x.numGroups, x.ciVersion, x.numSysex8Streams);
|
||||
};
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool operator!= (const BlockInfo& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
private:
|
||||
template <auto position, auto numBits, typename Value>
|
||||
static Value replaceBits (Value value, Value replacement)
|
||||
{
|
||||
constexpr auto mask = ((Value) 1 << numBits) - 1;
|
||||
const auto maskedValue = value & ~(mask << position);
|
||||
return (Value) (maskedValue | (replacement << position));
|
||||
}
|
||||
|
||||
template <auto position, auto numBits, typename Value>
|
||||
static Value getBits (Value value)
|
||||
{
|
||||
constexpr auto mask = ((Value) 1 << numBits) - 1;
|
||||
return (value >> position) & mask;
|
||||
}
|
||||
|
||||
uint8_t enabled{};
|
||||
uint8_t flags{};
|
||||
uint8_t firstGroup{};
|
||||
uint8_t numGroups{};
|
||||
uint8_t ciVersion{};
|
||||
uint8_t numSysex8Streams{};
|
||||
};
|
||||
|
||||
/**
|
||||
This struct holds functions that can be used to create different kinds
|
||||
of Universal MIDI Packet.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct Factory
|
||||
{
|
||||
template <typename Callback>
|
||||
static void splitIntoPackets (Span<const std::byte> bytes, size_t bytesPerPacket, Callback&& callback)
|
||||
{
|
||||
const auto numPackets = (bytes.size() / bytesPerPacket) + ((bytes.size() % bytesPerPacket) != 0);
|
||||
auto* dataOffset = bytes.data();
|
||||
|
||||
if (numPackets <= 1)
|
||||
{
|
||||
callback (SysEx7::Kind::complete, bytes);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto i = static_cast<ssize_t> (bytes.size()); i > 0; i -= (ssize_t) bytesPerPacket, dataOffset += bytesPerPacket)
|
||||
{
|
||||
const auto kind = [&]
|
||||
{
|
||||
if (i == (ssize_t) bytes.size())
|
||||
return SysEx7::Kind::begin;
|
||||
|
||||
if (i <= (ssize_t) bytesPerPacket)
|
||||
return SysEx7::Kind::end;
|
||||
|
||||
return SysEx7::Kind::continuation;
|
||||
}();
|
||||
|
||||
const auto bytesNow = std::min ((ssize_t) bytesPerPacket, i);
|
||||
callback (kind, Span (dataOffset, (size_t) bytesNow));
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
struct Detail
|
||||
{
|
||||
static PacketX1 makeSystem() { return PacketX1{}.withMessageType (Utils::MessageKind::commonRealtime); }
|
||||
static PacketX1 makeV1() { return PacketX1{}.withMessageType (Utils::MessageKind::channelVoice1); }
|
||||
static PacketX2 makeV2() { return PacketX2{}.withMessageType (Utils::MessageKind::channelVoice2); }
|
||||
static PacketX4 makeStream() { return PacketX4{}.withMessageType (Utils::MessageKind::stream); }
|
||||
|
||||
static PacketX2 makeSysEx (uint8_t group, SysEx7::Kind status, Span<const std::byte> data)
|
||||
{
|
||||
jassert (data.size() <= 6);
|
||||
|
||||
std::array<std::byte, 8> bytes { {} };
|
||||
bytes[0] = std::byte (0x3 << 0x4) | std::byte (group);
|
||||
bytes[1] = std::byte ((uint8_t) status << 0x4) | std::byte (data.size());
|
||||
|
||||
std::memcpy (bytes.data() + 2, data.data(), data.size());
|
||||
|
||||
std::array<uint32_t, 2> words;
|
||||
|
||||
for (const auto [index, word] : enumerate (words))
|
||||
word = ByteOrder::bigEndianInt (bytes.data() + 4 * index);
|
||||
|
||||
return PacketX2 { words };
|
||||
}
|
||||
|
||||
static PacketX4 makeSysEx8 (uint8_t group,
|
||||
std::byte status,
|
||||
uint8_t dataStart,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
jassert (data.size() <= (size_t) (16 - dataStart));
|
||||
|
||||
std::array<std::byte, 16> bytes{{}};
|
||||
bytes[0] = std::byte (0x5 << 0x4) | std::byte (group);
|
||||
bytes[1] = std::byte (status << 0x4) | std::byte (data.size());
|
||||
|
||||
std::memcpy (bytes.data() + dataStart, data.data(), data.size());
|
||||
|
||||
std::array<uint32_t, 4> words;
|
||||
|
||||
for (const auto [index, word] : enumerate (words))
|
||||
word = ByteOrder::bigEndianInt (bytes.data() + 4 * index);
|
||||
|
||||
return PacketX4 { words };
|
||||
}
|
||||
|
||||
static PacketX4 makePacketX4 (Span<const std::byte> header,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
jassert (data.size() <= 14);
|
||||
|
||||
std::array<std::byte, 16> bytes{{}};
|
||||
std::copy (header.begin(), header.end(), bytes.begin());
|
||||
std::copy (data.begin(), data.end(), std::next (bytes.begin(), (ptrdiff_t) header.size()));
|
||||
|
||||
std::array<uint32_t, 4> words{};
|
||||
|
||||
size_t index = 0;
|
||||
|
||||
for (auto& word : words)
|
||||
word = ByteOrder::bigEndianInt (bytes.data() + 4 * index++);
|
||||
|
||||
return PacketX4 { words };
|
||||
}
|
||||
|
||||
static PacketX4 makeStreamSubpacket (std::byte status,
|
||||
SysEx7::Kind kind,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
jassert (data.size() <= 14);
|
||||
const std::byte header[] { std::byte (0xf0) | std::byte ((uint8_t) kind << 2), status, };
|
||||
return makePacketX4 (header, data);
|
||||
}
|
||||
|
||||
static PacketX4 makeStreamConfiguration (StreamConfiguration options)
|
||||
{
|
||||
return Detail::makeStream().withU8<0x2> (options.getProtocol() == PacketProtocol::MIDI_2_0 ? 0x2 : 0x1)
|
||||
.withU8<0x3> ((options.getReceiveTimestamp() ? 0x2 : 0x0) | (options.getTransmitTimestamp() ? 0x1 : 0x0));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
static PacketX1 makeNoop (uint8_t group)
|
||||
{
|
||||
return PacketX1{}.withGroup (group);
|
||||
}
|
||||
|
||||
static PacketX1 makeJRClock (uint8_t group, uint16_t time)
|
||||
{
|
||||
return PacketX1 { time }.withStatus (std::byte { 1 }).withGroup (group);
|
||||
}
|
||||
|
||||
static PacketX1 makeJRTimestamp (uint8_t group, uint16_t time)
|
||||
{
|
||||
return PacketX1 { time }.withStatus (std::byte { 2 }).withGroup (group);
|
||||
}
|
||||
|
||||
static PacketX1 makeTimeCode (uint8_t group, uint8_t code)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xf1)
|
||||
.withU8<2> (code & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeSongPositionPointer (uint8_t group, uint16_t pos)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xf2)
|
||||
.withU8<2> (pos & 0x7f)
|
||||
.withU8<3> ((pos >> 7) & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeSongSelect (uint8_t group, uint8_t song)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xf3)
|
||||
.withU8<2> (song & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeTuneRequest (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xf6);
|
||||
}
|
||||
|
||||
static PacketX1 makeTimingClock (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xf8);
|
||||
}
|
||||
|
||||
static PacketX1 makeStart (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xfa);
|
||||
}
|
||||
|
||||
static PacketX1 makeContinue (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xfb);
|
||||
}
|
||||
|
||||
static PacketX1 makeStop (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xfc);
|
||||
}
|
||||
|
||||
static PacketX1 makeActiveSensing (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xfe);
|
||||
}
|
||||
|
||||
static PacketX1 makeReset (uint8_t group)
|
||||
{
|
||||
return Detail::makeSystem().withGroup (group)
|
||||
.withU8<1> (0xff);
|
||||
}
|
||||
|
||||
static PacketX1 makeNoteOffV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint8_t velocity)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0x8 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> (velocity & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeNoteOnV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint8_t velocity)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0x9 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> (velocity & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makePolyPressureV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint8_t pressure)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0xa })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> (pressure & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeControlChangeV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t controller,
|
||||
uint8_t value)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0xb })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (controller & 0x7f)
|
||||
.withU8<3> (value & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeProgramChangeV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t program)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0xc })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (program & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makeChannelPressureV1 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t pressure)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0xd })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (pressure & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX1 makePitchBend (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint16_t pitchbend)
|
||||
{
|
||||
return Detail::makeV1().withGroup (group)
|
||||
.withStatus (std::byte { 0xe })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (pitchbend & 0x7f)
|
||||
.withU8<3> ((pitchbend >> 7) & 0x7f);
|
||||
}
|
||||
|
||||
static PacketX2 makeSysExIn1Packet (uint8_t group,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx (group, SysEx7::Kind::complete, data);
|
||||
}
|
||||
|
||||
static PacketX2 makeSysExStart (uint8_t group,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx (group, SysEx7::Kind::begin, data);
|
||||
}
|
||||
|
||||
static PacketX2 makeSysExContinue (uint8_t group,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx (group, SysEx7::Kind::continuation, data);
|
||||
}
|
||||
|
||||
static PacketX2 makeSysExEnd (uint8_t group,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx (group, SysEx7::Kind::end, data);
|
||||
}
|
||||
|
||||
static PacketX2 makeRegisteredPerNoteControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint8_t controller,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x0 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> (controller & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeAssignablePerNoteControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint8_t controller,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x1 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> (controller & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeRegisteredControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t bank,
|
||||
uint8_t index,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x2 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (bank & 0x7f)
|
||||
.withU8<3> (index & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeAssignableControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t bank,
|
||||
uint8_t index,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x3 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (bank & 0x7f)
|
||||
.withU8<3> (index & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeRelativeRegisteredControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t bank,
|
||||
uint8_t index,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x4 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (bank & 0x7f)
|
||||
.withU8<3> (index & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeRelativeAssignableControllerV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t bank,
|
||||
uint8_t index,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x5 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (bank & 0x7f)
|
||||
.withU8<3> (index & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makePerNotePitchBendV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x6 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
enum class NoteAttributeKind : uint8_t
|
||||
{
|
||||
none = 0x00,
|
||||
manufacturer = 0x01,
|
||||
profile = 0x02,
|
||||
pitch7_9 = 0x03
|
||||
};
|
||||
|
||||
static PacketX2 makeNoteOffV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
NoteAttributeKind attribute,
|
||||
uint16_t velocity,
|
||||
uint16_t attributeValue)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x8 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> ((uint8_t) attribute)
|
||||
.withU16<2> (velocity)
|
||||
.withU16<3> (attributeValue);
|
||||
}
|
||||
|
||||
static PacketX2 makeNoteOnV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
NoteAttributeKind attribute,
|
||||
uint16_t velocity,
|
||||
uint16_t attributeValue)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0x9 })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU8<3> ((uint8_t) attribute)
|
||||
.withU16<2> (velocity)
|
||||
.withU16<3> (attributeValue);
|
||||
}
|
||||
|
||||
static PacketX2 makePolyPressureV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xa })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeControlChangeV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t controller,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xb })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (controller & 0x7f)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makeProgramChangeV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t optionFlags,
|
||||
uint8_t program,
|
||||
uint8_t bankMsb,
|
||||
uint8_t bankLsb)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xc })
|
||||
.withChannel (channel)
|
||||
.withU8<3> (optionFlags)
|
||||
.withU8<4> (program)
|
||||
.withU8<6> (bankMsb)
|
||||
.withU8<7> (bankLsb);
|
||||
}
|
||||
|
||||
static PacketX2 makeChannelPressureV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xd })
|
||||
.withChannel (channel)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makePitchBendV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint32_t data)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xe })
|
||||
.withChannel (channel)
|
||||
.withU32<1> (data);
|
||||
}
|
||||
|
||||
static PacketX2 makePerNoteManagementV2 (uint8_t group,
|
||||
uint8_t channel,
|
||||
uint8_t note,
|
||||
std::byte optionFlags)
|
||||
{
|
||||
return Detail::makeV2().withGroup (group)
|
||||
.withStatus (std::byte { 0xf })
|
||||
.withChannel (channel)
|
||||
.withU8<2> (note)
|
||||
.withU8<3> (uint8_t (optionFlags));
|
||||
}
|
||||
|
||||
|
||||
static PacketX4 makeSysEx8in1Packet (uint8_t group,
|
||||
uint8_t streamId,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx8 (group, std::byte { 0x0 }, 3, data).withU8<2> (streamId);
|
||||
}
|
||||
|
||||
static PacketX4 makeSysEx8Start (uint8_t group,
|
||||
uint8_t streamId,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx8 (group, std::byte { 0x1 }, 3, data).withU8<2> (streamId);
|
||||
}
|
||||
|
||||
static PacketX4 makeSysEx8Continue (uint8_t group,
|
||||
uint8_t streamId,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx8 (group, std::byte { 0x2 }, 3, data).withU8<2> (streamId);
|
||||
}
|
||||
|
||||
static PacketX4 makeSysEx8End (uint8_t group,
|
||||
uint8_t streamId,
|
||||
Span<const std::byte> data)
|
||||
{
|
||||
return Detail::makeSysEx8 (group, std::byte { 0x3 }, 3, data).withU8<2> (streamId);
|
||||
}
|
||||
|
||||
static PacketX4 makeEndpointDiscovery (uint8_t versionMajor,
|
||||
uint8_t versionMinor,
|
||||
std::byte filterBitmap)
|
||||
{
|
||||
return Detail::makeStream().withU8<2> (versionMajor)
|
||||
.withU8<3> (versionMinor)
|
||||
.withU8<7> ((uint8_t) filterBitmap);
|
||||
}
|
||||
|
||||
static PacketX4 makeEndpointInfoNotification (const EndpointInfo& info)
|
||||
{
|
||||
return Detail::makeStream().withU8<1> (1)
|
||||
.withU8<2> (info.getVersionMajor())
|
||||
.withU8<3> (info.getVersionMinor())
|
||||
.withU8<4> (info.getNumFunctionBlocks() | (info.hasStaticFunctionBlocks() ? 0x80 : 0x00))
|
||||
.withU8<6> ((info.hasMidi1Support() ? 0x1 : 0x0) | (info.hasMidi2Support() ? 0x2 : 0x0))
|
||||
.withU8<7> ((info.hasTransmitJRSupport() ? 0x1 : 0x0) | (info.hasReceiveJRSupport() ? 0x2 : 0x0));
|
||||
}
|
||||
|
||||
static PacketX4 makeFunctionBlockDiscovery (uint8_t block, std::byte filterBitmap)
|
||||
{
|
||||
return Detail::makeStream().withU8<1> (0x10)
|
||||
.withU8<2> (block)
|
||||
.withU8<3> ((uint8_t) filterBitmap);
|
||||
}
|
||||
|
||||
static PacketX4 makeDeviceIdentityNotification (DeviceInfo info)
|
||||
{
|
||||
return Detail::makeStream().withU8<0x1> (2)
|
||||
.withU8<0x5> ((uint8_t) info.manufacturer[0])
|
||||
.withU8<0x6> ((uint8_t) info.manufacturer[1])
|
||||
.withU8<0x7> ((uint8_t) info.manufacturer[2])
|
||||
.withU8<0x8> ((uint8_t) info.family[0])
|
||||
.withU8<0x9> ((uint8_t) info.family[1])
|
||||
.withU8<0xa> ((uint8_t) info.modelNumber[0])
|
||||
.withU8<0xb> ((uint8_t) info.modelNumber[1])
|
||||
.withU8<0xc> ((uint8_t) info.revision[0])
|
||||
.withU8<0xd> ((uint8_t) info.revision[1])
|
||||
.withU8<0xe> ((uint8_t) info.revision[2])
|
||||
.withU8<0xf> ((uint8_t) info.revision[3]);
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static bool makeEndpointNameNotification (const String& bytes, Fn&& fn)
|
||||
{
|
||||
constexpr auto maxSize = 98;
|
||||
|
||||
if (maxSize <= bytes.getNumBytesAsUTF8())
|
||||
return false;
|
||||
|
||||
const Span byteSpan { reinterpret_cast<const std::byte*> (bytes.toRawUTF8()), bytes.getNumBytesAsUTF8() };
|
||||
|
||||
splitIntoPackets (byteSpan, 14, [&] (SysEx7::Kind kind, Span<const std::byte> bytesThisTime)
|
||||
{
|
||||
const auto packet = Detail::makeStreamSubpacket (std::byte (3), kind, bytesThisTime);
|
||||
fn (View (packet.data()));
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static bool makeProductInstanceIdNotification (const String& bytes, Fn&& fn)
|
||||
{
|
||||
constexpr auto maxSize = 42;
|
||||
|
||||
if (maxSize < bytes.getNumBytesAsUTF8())
|
||||
return false;
|
||||
|
||||
const Span byteSpan { reinterpret_cast<const std::byte*> (bytes.toRawUTF8()), bytes.getNumBytesAsUTF8() };
|
||||
|
||||
splitIntoPackets (byteSpan, 14, [&] (SysEx7::Kind kind, Span<const std::byte> bytesThisTime)
|
||||
{
|
||||
const auto packet = Detail::makeStreamSubpacket (std::byte (4), kind, bytesThisTime);
|
||||
fn (View (packet.data()));
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
static bool makeFunctionBlockNameNotification (uint8_t index, const String& bytes, Fn&& fn)
|
||||
{
|
||||
constexpr auto maxSize = 91;
|
||||
|
||||
if (maxSize < bytes.getNumBytesAsUTF8())
|
||||
return false;
|
||||
|
||||
const Span byteSpan { reinterpret_cast<const std::byte*> (bytes.toRawUTF8()), bytes.getNumBytesAsUTF8() };
|
||||
|
||||
splitIntoPackets (byteSpan, 13, [&] (SysEx7::Kind kind, Span<const std::byte> bytesThisTime)
|
||||
{
|
||||
const std::byte header[] { std::byte (0xf0) | std::byte ((uint8_t) kind << 2), std::byte (0x12), std::byte (index) };
|
||||
fn (View (Detail::makePacketX4 (header, bytesThisTime).data()));
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static PacketX4 makeFunctionBlockInfoNotification (uint8_t index, const BlockInfo& info)
|
||||
{
|
||||
const auto flags = ((uint8_t) info.getDirection() << 0)
|
||||
| ((uint8_t) info.getMIDI1ProxyKind() << 2)
|
||||
| ((uint8_t) info.getUiHint() << 4);
|
||||
return Detail::makeStream().withU8<0x1> (0x11)
|
||||
.withU8<0x2> ((uint8_t) (index | (info.isEnabled() << 7)))
|
||||
.withU8<0x3> ((uint8_t) flags)
|
||||
.withU8<0x4> (info.getFirstGroup())
|
||||
.withU8<0x5> (info.getNumGroups())
|
||||
.withU8<0x6> (info.getCiVersion())
|
||||
.withU8<0x7> (info.getMaxSysex8Streams());
|
||||
}
|
||||
|
||||
static PacketX4 makeStreamConfigurationRequest (StreamConfiguration options)
|
||||
{
|
||||
return Detail::makeStreamConfiguration (options).withU8<0x1> (5);
|
||||
}
|
||||
|
||||
static PacketX4 makeStreamConfigurationNotification (StreamConfiguration options)
|
||||
{
|
||||
return Detail::makeStreamConfiguration (options).withU8<0x1> (6);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -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
|
||||
{
|
||||
|
||||
Iterator::Iterator (const uint32_t* ptr, [[maybe_unused]] size_t words) noexcept
|
||||
: view (ptr)
|
||||
#if JUCE_DEBUG
|
||||
, wordsRemaining (words)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Enables iteration over a collection of Universal MIDI Packets stored as
|
||||
a contiguous range of 32-bit words.
|
||||
|
||||
This iterator is used by Packets to allow access to the messages
|
||||
that it contains.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Iterator
|
||||
{
|
||||
public:
|
||||
/** Creates an invalid (singular) iterator. */
|
||||
Iterator() noexcept = default;
|
||||
|
||||
/** Creates an iterator pointing at `ptr`. */
|
||||
explicit Iterator (const uint32_t* ptr, size_t words) noexcept;
|
||||
|
||||
using difference_type = std::iterator_traits<const uint32_t*>::difference_type;
|
||||
using value_type = View;
|
||||
using reference = const View&;
|
||||
using pointer = const View*;
|
||||
using iterator_category = std::forward_iterator_tag;
|
||||
|
||||
/** Moves this iterator to the next packet in the range. */
|
||||
Iterator& operator++() noexcept
|
||||
{
|
||||
const auto increment = view.size();
|
||||
|
||||
#if JUCE_DEBUG
|
||||
// If you hit this, the memory region contained a truncated or otherwise
|
||||
// malformed Universal MIDI Packet.
|
||||
// The Iterator can only be used on regions containing complete packets!
|
||||
jassert (increment <= wordsRemaining);
|
||||
wordsRemaining -= increment;
|
||||
#endif
|
||||
|
||||
view = View (view.data() + increment);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Moves this iterator to the next packet in the range,
|
||||
returning the value of the iterator before it was
|
||||
incremented.
|
||||
*/
|
||||
Iterator operator++ (int) noexcept
|
||||
{
|
||||
auto copy = *this;
|
||||
++(*this);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Returns true if this iterator points to the same address
|
||||
as another iterator.
|
||||
*/
|
||||
bool operator== (const Iterator& other) const noexcept
|
||||
{
|
||||
return view == other.view;
|
||||
}
|
||||
|
||||
/** Returns false if this iterator points to the same address
|
||||
as another iterator.
|
||||
*/
|
||||
bool operator!= (const Iterator& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
/** Returns a reference to a View of the packet currently
|
||||
pointed-to by this iterator.
|
||||
|
||||
The View can be queried for its size and content.
|
||||
*/
|
||||
reference operator*() const noexcept { return view; }
|
||||
|
||||
/** Returns a pointer to a View of the packet currently
|
||||
pointed-to by this iterator.
|
||||
|
||||
The View can be queried for its size and content.
|
||||
*/
|
||||
pointer operator->() const noexcept { return &view; }
|
||||
|
||||
private:
|
||||
View view;
|
||||
|
||||
#if JUCE_DEBUG
|
||||
size_t wordsRemaining = 0;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Extracts from a series of Universal MIDI Packets the bytes that are also meaningful in the
|
||||
bytestream MIDI 1.0 format.
|
||||
*/
|
||||
class SingleGroupMidi1ToBytestreamExtractor
|
||||
{
|
||||
public:
|
||||
void reset()
|
||||
{
|
||||
sysexInProgress = false;
|
||||
}
|
||||
|
||||
/** Converts a Universal MIDI Packet using the MIDI 1.0 Protocol to
|
||||
an equivalent MidiMessage. If the packet doesn't convert to a single bytestream message
|
||||
(as may be the case for long sysex7 data), then the the callback will be passed just the
|
||||
sysex bytes in the current packet. To reconstruct the entire sysex message, the caller
|
||||
can bytes that are marked as ongoingSysex, and process the full message once the callback
|
||||
receives bytes that are marked as lastSysex.
|
||||
|
||||
@param packet a packet which is using the MIDI 1.0 Protocol.
|
||||
@param time the timestamp to be applied to these messages.
|
||||
@param callback a callback that will be called with each converted MidiMessage.
|
||||
*/
|
||||
template <typename MessageCallback>
|
||||
void dispatch (const View& packet, double time, MessageCallback&& callback)
|
||||
{
|
||||
const auto firstWord = *packet.data();
|
||||
|
||||
if (sysexInProgress && shouldPacketTerminateSysExEarly (firstWord))
|
||||
{
|
||||
// unexpected end of last sysex
|
||||
callback (SysexExtractorCallbackKind::lastSysex, Span<const std::byte>());
|
||||
sysexInProgress = false;
|
||||
}
|
||||
|
||||
switch (packet.size())
|
||||
{
|
||||
case 1:
|
||||
{
|
||||
// Utility messages don't translate to bytestream format
|
||||
if (Utils::getMessageType (firstWord) != Utils::MessageKind::utility)
|
||||
{
|
||||
const auto converted = fromUmp (PacketX1 { firstWord }, time);
|
||||
callback (SysexExtractorCallbackKind::notSysex,
|
||||
Span (unalignedPointerCast<const std::byte*> (converted.getRawData()),
|
||||
(size_t) converted.getRawDataSize()));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
if (Utils::getMessageType (firstWord) == Utils::MessageKind::sysex7)
|
||||
processSysEx (PacketX2 { packet[0], packet[1] }, callback);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 3: // no 3-word packets in the current spec
|
||||
case 4: // no 4-word packets translate to bytestream format
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Converts from a Universal MIDI Packet to MIDI 1 bytestream format.
|
||||
|
||||
This is only capable of converting a single Universal MIDI Packet to
|
||||
an equivalent bytestream MIDI message. This function cannot understand
|
||||
multi-packet messages, like SysEx7 messages.
|
||||
|
||||
To convert multi-packet messages, use `Midi1ToBytestreamTranslator`
|
||||
to convert from a UMP MIDI 1.0 stream, or `ToBytestreamDispatcher`
|
||||
to convert from both MIDI 2.0 and MIDI 1.0.
|
||||
*/
|
||||
static MidiMessage fromUmp (const PacketX1& m, double time = 0)
|
||||
{
|
||||
const auto word = m.front();
|
||||
jassert (Utils::getNumWordsForMessageType (word) == 1);
|
||||
|
||||
const std::array<std::byte, 3> bytes { { std::byte ((word >> 0x10) & 0xff),
|
||||
std::byte ((word >> 0x08) & 0xff),
|
||||
std::byte ((word >> 0x00) & 0xff) } };
|
||||
const auto numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8_t) bytes.front());
|
||||
return MidiMessage (bytes.data(), numBytes, time);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename MessageCallback>
|
||||
void processSysEx (const PacketX2& packet, MessageCallback&& callback)
|
||||
{
|
||||
const std::array<std::byte, 1> initial { std::byte { 0xf0 } }, final { std::byte { 0xf7 } };
|
||||
std::array<std::byte, 8> storage{};
|
||||
size_t validBytes = 0;
|
||||
|
||||
const auto pushBytes = [&] (const Span<const std::byte> b)
|
||||
{
|
||||
std::copy (b.begin(), b.end(), storage.data() + validBytes);
|
||||
validBytes += b.size();
|
||||
};
|
||||
|
||||
const auto pushPacket = [&] (const PacketX2& p)
|
||||
{
|
||||
const auto newBytes = SysEx7::getDataBytes (p);
|
||||
pushBytes (Span<const std::byte> (newBytes.data.data(), newBytes.size));
|
||||
};
|
||||
|
||||
const auto kind = getSysEx7Kind (packet[0]);
|
||||
|
||||
if ( ( sysexInProgress && (kind == SysEx7::Kind::begin || kind == SysEx7::Kind::complete))
|
||||
|| (! sysexInProgress && (kind == SysEx7::Kind::continuation || kind == SysEx7::Kind::end)))
|
||||
{
|
||||
// Malformed SysEx, drop progress and return
|
||||
callback (SysexExtractorCallbackKind::lastSysex, Span<const std::byte>());
|
||||
sysexInProgress = false;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case SysEx7::Kind::complete:
|
||||
pushBytes (Span (initial));
|
||||
pushPacket (packet);
|
||||
pushBytes (Span (final));
|
||||
break;
|
||||
|
||||
case SysEx7::Kind::begin:
|
||||
pushBytes (Span (initial));
|
||||
pushPacket (packet);
|
||||
break;
|
||||
|
||||
case SysEx7::Kind::continuation:
|
||||
pushPacket (packet);
|
||||
break;
|
||||
|
||||
case SysEx7::Kind::end:
|
||||
pushPacket (packet);
|
||||
pushBytes (Span (final));
|
||||
break;
|
||||
}
|
||||
|
||||
sysexInProgress = sysexInProgress ? (kind == SysEx7::Kind::continuation)
|
||||
: (kind == SysEx7::Kind::begin);
|
||||
const auto callbackKind = sysexInProgress ? SysexExtractorCallbackKind::ongoingSysex
|
||||
: SysexExtractorCallbackKind::lastSysex;
|
||||
callback (callbackKind, Span (storage.data(), validBytes));
|
||||
}
|
||||
|
||||
static bool shouldPacketTerminateSysExEarly (uint32_t firstWord)
|
||||
{
|
||||
return ! (isSysExContinuation (firstWord)
|
||||
|| isSystemRealTime (firstWord)
|
||||
|| isJROrNOP (firstWord));
|
||||
}
|
||||
|
||||
static SysEx7::Kind getSysEx7Kind (uint32_t word)
|
||||
{
|
||||
return SysEx7::Kind ((word >> 0x14) & 0xf);
|
||||
}
|
||||
|
||||
static bool isJROrNOP (uint32_t word)
|
||||
{
|
||||
return Utils::getMessageType (word) == Utils::MessageKind::utility;
|
||||
}
|
||||
|
||||
static bool isSysExContinuation (uint32_t word)
|
||||
{
|
||||
if (Utils::getMessageType (word) != Utils::MessageKind::sysex7)
|
||||
return false;
|
||||
|
||||
const auto kind = getSysEx7Kind (word);
|
||||
return kind == SysEx7::Kind::continuation || kind == SysEx7::Kind::end;
|
||||
}
|
||||
|
||||
static bool isSystemRealTime (uint32_t word)
|
||||
{
|
||||
return Utils::getMessageType (word) == Utils::MessageKind::commonRealtime && ((word >> 0x10) & 0xff) >= 0xf8;
|
||||
}
|
||||
|
||||
bool sysexInProgress = false;
|
||||
};
|
||||
|
||||
/**
|
||||
Parses a raw stream of uint32_t holding a series of Universal MIDI Packets using
|
||||
the MIDI 1.0 Protocol, converting to plain (non-UMP) MidiMessages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class SingleGroupMidi1ToBytestreamTranslator
|
||||
{
|
||||
public:
|
||||
/** Ensures that there is room in the internal buffer for a sysex message of at least
|
||||
initialBufferSize bytes.
|
||||
*/
|
||||
explicit SingleGroupMidi1ToBytestreamTranslator (int initialBufferSize)
|
||||
{
|
||||
pendingSysExData.reserve (size_t (initialBufferSize));
|
||||
}
|
||||
|
||||
/** Clears the concatenator. */
|
||||
void reset()
|
||||
{
|
||||
extractor.reset();
|
||||
pendingSysExData.clear();
|
||||
pendingSysExTime = 0.0;
|
||||
}
|
||||
|
||||
/** Converts a Universal MIDI Packet using the MIDI 1.0 Protocol to
|
||||
an equivalent MidiMessage. Accumulates SysEx packets into a single
|
||||
MidiMessage, as appropriate.
|
||||
|
||||
@param packet a packet which is using the MIDI 1.0 Protocol.
|
||||
@param time the timestamp to be applied to these messages.
|
||||
@param callback a callback which will be called with each converted MidiMessage.
|
||||
*/
|
||||
template <typename MessageCallback>
|
||||
void dispatch (const View& packet, double time, MessageCallback&& callback)
|
||||
{
|
||||
extractor.dispatch (packet, time, [&] (SysexExtractorCallbackKind kind, Span<const std::byte> bytes)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case SysexExtractorCallbackKind::notSysex:
|
||||
callback (BytesOnGroup { 0, bytes }, time);
|
||||
return;
|
||||
|
||||
case SysexExtractorCallbackKind::ongoingSysex:
|
||||
{
|
||||
if (pendingSysExData.empty())
|
||||
pendingSysExTime = time;
|
||||
|
||||
pendingSysExData.insert (pendingSysExData.end(), bytes.begin(), bytes.end());
|
||||
return;
|
||||
}
|
||||
|
||||
case SysexExtractorCallbackKind::lastSysex:
|
||||
{
|
||||
if (pendingSysExData.empty())
|
||||
pendingSysExTime = time;
|
||||
|
||||
pendingSysExData.insert (pendingSysExData.end(), bytes.begin(), bytes.end());
|
||||
|
||||
if (pendingSysExData.empty())
|
||||
return;
|
||||
|
||||
// If this is not true, then the sysex message was truncated somehow and we
|
||||
// probably shouldn't allow it to propagate
|
||||
if (pendingSysExData.back() == std::byte { 0xf7 })
|
||||
callback (BytesOnGroup { 0, Span<const std::byte> (pendingSysExData) }, pendingSysExTime);
|
||||
|
||||
pendingSysExData.clear();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
SingleGroupMidi1ToBytestreamExtractor extractor;
|
||||
std::vector<std::byte> pendingSysExData;
|
||||
double pendingSysExTime = 0.0;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
PacketX2 Midi1ToMidi2DefaultTranslator::processNoteOnOrOff (const HelperValues helpers)
|
||||
{
|
||||
const auto velocity = helpers.byte2;
|
||||
const auto needsConversion = (helpers.byte0 & std::byte { 0xf0 }) == std::byte { 0x90 } && velocity == std::byte { 0 };
|
||||
const auto firstByte = needsConversion ? (std::byte { 0x80 } | (helpers.byte0 & std::byte { 0xf }))
|
||||
: helpers.byte0;
|
||||
|
||||
return PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, firstByte, helpers.byte1, std::byte { 0 }),
|
||||
(uint32_t) (Conversion::scaleTo16 (uint8_t (velocity)) << 0x10)
|
||||
};
|
||||
}
|
||||
|
||||
PacketX2 Midi1ToMidi2DefaultTranslator::processPolyPressure (const HelperValues helpers)
|
||||
{
|
||||
return PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, helpers.byte0, helpers.byte1, std::byte { 0 }),
|
||||
Conversion::scaleTo32 (uint8_t (helpers.byte2))
|
||||
};
|
||||
}
|
||||
|
||||
bool Midi1ToMidi2DefaultTranslator::processControlChange (const HelperValues helpers,
|
||||
PacketX2& packet)
|
||||
{
|
||||
const auto statusAndChannel = helpers.byte0;
|
||||
const auto cc = uint8_t (helpers.byte1);
|
||||
|
||||
const auto shouldAccumulate = [&]
|
||||
{
|
||||
switch (cc)
|
||||
{
|
||||
case 6:
|
||||
case 38:
|
||||
case 98:
|
||||
case 99:
|
||||
case 100:
|
||||
case 101:
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}();
|
||||
|
||||
const auto group = (uint8_t) (helpers.typeAndGroup & std::byte { 0xf });
|
||||
const auto channel = (uint8_t) (statusAndChannel & std::byte { 0xf });
|
||||
const auto byte = helpers.byte2;
|
||||
|
||||
if (shouldAccumulate)
|
||||
{
|
||||
auto& accumulator = groupAccumulators[group][channel];
|
||||
|
||||
if (accumulator.addByte (cc, byte))
|
||||
{
|
||||
const auto& bytes = accumulator.getBytes();
|
||||
const auto bank = bytes[0];
|
||||
const auto index = bytes[1];
|
||||
const auto msb = bytes[2];
|
||||
const auto lsb = bytes[3];
|
||||
|
||||
const auto value = uint16_t ((uint16_t (msb & std::byte { 0x7f }) << 7) | uint16_t (lsb & std::byte { 0x7f }));
|
||||
|
||||
const auto newStatus = accumulator.getKind() == PnKind::nrpn ? std::byte { 0x3 } : std::byte { 0x2 };
|
||||
|
||||
packet = PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, std::byte ((newStatus << 0x4) | std::byte { channel }), bank, index),
|
||||
Conversion::scaleTo32 (value)
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cc == 0)
|
||||
{
|
||||
groupBanks[group][channel].setMsb (byte);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cc == 32)
|
||||
{
|
||||
groupBanks[group][channel].setLsb (byte);
|
||||
return false;
|
||||
}
|
||||
|
||||
packet = PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, statusAndChannel, std::byte { cc }, std::byte { 0 }),
|
||||
Conversion::scaleTo32 (uint8_t (helpers.byte2))
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
PacketX2 Midi1ToMidi2DefaultTranslator::processProgramChange (const HelperValues helpers) const
|
||||
{
|
||||
const auto group = (uint8_t) (helpers.typeAndGroup & std::byte { 0xf });
|
||||
const auto channel = (uint8_t) (helpers.byte0 & std::byte { 0xf });
|
||||
const auto bank = groupBanks[group][channel];
|
||||
const auto valid = bank.isValid();
|
||||
|
||||
return PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup,
|
||||
helpers.byte0,
|
||||
std::byte { 0 },
|
||||
valid ? std::byte { 1 } : std::byte { 0 }),
|
||||
Utils::bytesToWord (helpers.byte1,
|
||||
std::byte { 0 },
|
||||
valid ? std::byte { bank.getMsb() } : std::byte { 0 },
|
||||
valid ? std::byte { bank.getLsb() } : std::byte { 0 })
|
||||
};
|
||||
}
|
||||
|
||||
PacketX2 Midi1ToMidi2DefaultTranslator::processChannelPressure (const HelperValues helpers)
|
||||
{
|
||||
return PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, helpers.byte0, std::byte { 0 }, std::byte { 0 }),
|
||||
Conversion::scaleTo32 (uint8_t (helpers.byte1))
|
||||
};
|
||||
}
|
||||
|
||||
PacketX2 Midi1ToMidi2DefaultTranslator::processPitchBend (const HelperValues helpers)
|
||||
{
|
||||
const auto lsb = helpers.byte1;
|
||||
const auto msb = helpers.byte2;
|
||||
const auto value = uint16_t (uint16_t (msb) << 7 | uint16_t (lsb));
|
||||
|
||||
return PacketX2
|
||||
{
|
||||
Utils::bytesToWord (helpers.typeAndGroup, helpers.byte0, std::byte { 0 }, std::byte { 0 }),
|
||||
Conversion::scaleTo32 (value)
|
||||
};
|
||||
}
|
||||
|
||||
bool Midi1ToMidi2DefaultTranslator::PnAccumulator::addByte (uint8_t cc, std::byte byte)
|
||||
{
|
||||
const auto isStart = cc == 99 || cc == 101;
|
||||
|
||||
if (isStart)
|
||||
{
|
||||
kind = cc == 99 ? PnKind::nrpn : PnKind::rpn;
|
||||
index = 0;
|
||||
}
|
||||
|
||||
bytes[index] = byte;
|
||||
|
||||
const auto shouldContinue = [&]
|
||||
{
|
||||
switch (index)
|
||||
{
|
||||
case 0: return isStart;
|
||||
case 1: return kind == PnKind::nrpn ? cc == 98 : cc == 100;
|
||||
case 2: return cc == 6;
|
||||
case 3: return cc == 38;
|
||||
}
|
||||
|
||||
return false;
|
||||
}();
|
||||
|
||||
index = shouldContinue ? index + 1 : 0;
|
||||
|
||||
if (index != bytes.size())
|
||||
return false;
|
||||
|
||||
index = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Translates a series of MIDI 1 Universal MIDI Packets to corresponding MIDI 2
|
||||
packets.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Midi1ToMidi2DefaultTranslator
|
||||
{
|
||||
public:
|
||||
Midi1ToMidi2DefaultTranslator() = default;
|
||||
|
||||
/** Converts MIDI 1 Universal MIDI Packets to corresponding MIDI 2 packets,
|
||||
calling `callback` with each converted packet.
|
||||
|
||||
In some cases (such as RPN/NRPN messages) multiple MIDI 1 packets will
|
||||
convert to a single MIDI 2 packet. In these cases, the translator will
|
||||
accumulate the full message internally, and send a single callback with
|
||||
the completed message, once all the individual MIDI 1 packets have been
|
||||
processed.
|
||||
*/
|
||||
template <typename PacketCallback>
|
||||
void dispatch (const View& v, PacketCallback&& callback)
|
||||
{
|
||||
const auto firstWord = v[0];
|
||||
const auto messageType = Utils::getMessageType (firstWord);
|
||||
|
||||
if (messageType != Utils::MessageKind::channelVoice1)
|
||||
{
|
||||
callback (v);
|
||||
return;
|
||||
}
|
||||
|
||||
const HelperValues helperValues
|
||||
{
|
||||
std::byte (0x40 | Utils::getGroup (firstWord)),
|
||||
std::byte ((firstWord >> 0x10) & 0xff),
|
||||
std::byte ((firstWord >> 0x08) & 0x7f),
|
||||
std::byte ((firstWord >> 0x00) & 0x7f),
|
||||
};
|
||||
|
||||
switch ((uint8_t) Utils::getStatus (firstWord))
|
||||
{
|
||||
case 0x8:
|
||||
case 0x9:
|
||||
{
|
||||
const auto packet = processNoteOnOrOff (helperValues);
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xa:
|
||||
{
|
||||
const auto packet = processPolyPressure (helperValues);
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xb:
|
||||
{
|
||||
PacketX2 packet;
|
||||
|
||||
if (processControlChange (helperValues, packet))
|
||||
callback (View (packet.data()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xc:
|
||||
{
|
||||
const auto packet = processProgramChange (helperValues);
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xd:
|
||||
{
|
||||
const auto packet = processChannelPressure (helperValues);
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
|
||||
case 0xe:
|
||||
{
|
||||
const auto packet = processPitchBend (helperValues);
|
||||
callback (View (packet.data()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
groupAccumulators = {};
|
||||
groupBanks = {};
|
||||
}
|
||||
|
||||
private:
|
||||
enum class PnKind { nrpn, rpn };
|
||||
|
||||
struct HelperValues
|
||||
{
|
||||
std::byte typeAndGroup;
|
||||
std::byte byte0;
|
||||
std::byte byte1;
|
||||
std::byte byte2;
|
||||
};
|
||||
|
||||
static PacketX2 processNoteOnOrOff (HelperValues helpers);
|
||||
static PacketX2 processPolyPressure (HelperValues helpers);
|
||||
|
||||
bool processControlChange (HelperValues helpers, PacketX2& packet);
|
||||
|
||||
PacketX2 processProgramChange (HelperValues helpers) const;
|
||||
|
||||
static PacketX2 processChannelPressure (HelperValues helpers);
|
||||
static PacketX2 processPitchBend (HelperValues helpers);
|
||||
|
||||
class PnAccumulator
|
||||
{
|
||||
public:
|
||||
bool addByte (uint8_t cc, std::byte byte);
|
||||
|
||||
const std::array<std::byte, 4>& getBytes() const noexcept { return bytes; }
|
||||
PnKind getKind() const noexcept { return kind; }
|
||||
|
||||
private:
|
||||
std::array<std::byte, 4> bytes;
|
||||
uint8_t index = 0;
|
||||
PnKind kind = PnKind::nrpn;
|
||||
};
|
||||
|
||||
class Bank
|
||||
{
|
||||
public:
|
||||
bool isValid() const noexcept { return (msb & std::byte { 0x80 }) == std::byte { 0 }; }
|
||||
|
||||
std::byte getMsb() const noexcept { return msb & std::byte (0x7f); }
|
||||
std::byte getLsb() const noexcept { return lsb & std::byte (0x7f); }
|
||||
|
||||
void setMsb (std::byte i) noexcept { msb = i & std::byte (0x7f); }
|
||||
void setLsb (std::byte i) noexcept { msb &= std::byte (0x7f); lsb = i & std::byte (0x7f); }
|
||||
|
||||
private:
|
||||
// We use the top bit to indicate whether this bank is valid.
|
||||
// After reading the spec, it's not clear how we should determine whether
|
||||
// there are valid values, so we'll just assume that the bank is valid
|
||||
// once either the lsb or msb have been written.
|
||||
std::byte msb { 0x80 };
|
||||
std::byte lsb { 0x00 };
|
||||
};
|
||||
|
||||
using ChannelAccumulators = std::array<PnAccumulator, 16>;
|
||||
std::array<ChannelAccumulators, 16> groupAccumulators;
|
||||
|
||||
using ChannelBanks = std::array<Bank, 16>;
|
||||
std::array<ChannelBanks, 16> groupBanks;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/** Kinds of MIDI message transport.
|
||||
*/
|
||||
enum class Transport : uint8_t
|
||||
{
|
||||
bytestream, ///< A stream of variable-length messages. Suitable for MIDI 1.0.
|
||||
ump, ///< A stream of 32-bit words. Suitable for MIDI-1UP and MIDI 2.0.
|
||||
};
|
||||
|
||||
/** The kinds of MIDI protocol that can be formatted into Universal MIDI Packets.
|
||||
*/
|
||||
enum class PacketProtocol : uint8_t
|
||||
{
|
||||
MIDI_1_0,
|
||||
MIDI_2_0,
|
||||
};
|
||||
|
||||
/** All kinds of MIDI protocol understood by JUCE.
|
||||
*/
|
||||
enum class MidiProtocol : uint8_t
|
||||
{
|
||||
bytestream,
|
||||
UMP_MIDI_1_0,
|
||||
UMP_MIDI_2_0,
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
String StringUtils::getHexString (const View& view)
|
||||
{
|
||||
auto result = String::toHexString (*view.data());
|
||||
|
||||
std::for_each (std::next (view.begin()), view.end(), [&] (uint32_t word)
|
||||
{
|
||||
result << ' ' << String::toHexString (word);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static String getUtilityMessageDescription (const PacketX1& p)
|
||||
{
|
||||
const auto word = p.front();
|
||||
|
||||
switch ((uint8_t) Utils::getStatus (word))
|
||||
{
|
||||
case 0x0: return "NOOP";
|
||||
case 0x1: return "JR Clock " + String::toHexString ((word >> 0x10) & 0xff);
|
||||
case 0x2: return "JR Timestamp " + String::toHexString ((word >> 0x10) & 0xff);
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getPacketDescription (const PacketX1& p)
|
||||
{
|
||||
switch (Utils::getMessageType (p.front()))
|
||||
{
|
||||
case Utils::MessageKind::utility: return "Utility: " + getUtilityMessageDescription (p);
|
||||
case Utils::MessageKind::commonRealtime: return "System: " + SingleGroupMidi1ToBytestreamExtractor::fromUmp (p).getDescription();
|
||||
case Utils::MessageKind::channelVoice1: return "MIDI 1.0 Channel Voice: " + SingleGroupMidi1ToBytestreamExtractor::fromUmp (p).getDescription();
|
||||
|
||||
case Utils::MessageKind::channelVoice2:
|
||||
case Utils::MessageKind::sysex7:
|
||||
case Utils::MessageKind::sysex8:
|
||||
case Utils::MessageKind::stream:
|
||||
break;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getData64MessageDescription (const PacketX2& p)
|
||||
{
|
||||
const auto bytes = SysEx7::getDataBytes (p);
|
||||
|
||||
String byteString;
|
||||
|
||||
std::for_each (bytes.data.data(), bytes.data.data() + bytes.size, [&] (std::byte byte)
|
||||
{
|
||||
byteString << String::toHexString ((uint8_t) byte);
|
||||
});
|
||||
|
||||
switch (SysEx7::Kind (Utils::getStatus (p.front())))
|
||||
{
|
||||
case SysEx7::Kind::complete: return "Full: " + byteString;
|
||||
case SysEx7::Kind::begin: return "Start: " + byteString;
|
||||
case SysEx7::Kind::continuation: return "Continue: " + byteString;
|
||||
case SysEx7::Kind::end: return "End: " + byteString;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getMidi2ChannelVoiceDescription (const PacketX2& p)
|
||||
{
|
||||
const auto getNoteName = [&] { return MidiMessage::getMidiNoteName ((p[0] >> 0x8) & 0xff, true, true, 3); };
|
||||
const auto getByte3 = [&] { return String::toHexString ((p[0] >> 0x8) & 0xff); };
|
||||
const auto getByte4 = [&] { return String::toHexString ((p[0] >> 0x0) & 0xff); };
|
||||
|
||||
const auto getVelocity = [&] { return String::toHexString ((p[1] >> 0x10) & 0xffff); };
|
||||
const auto getAttribute = [&] { return String::toHexString ((p[1] >> 0x00) & 0xffff); };
|
||||
|
||||
const auto getChannel = [&] { return String::toHexString (p.getChannel()); };
|
||||
|
||||
switch ((uint8_t) Utils::getStatus (p[0]))
|
||||
{
|
||||
case 0x0: return "Registered Per-Note Controller " + getByte4()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Note " + getNoteName()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x1: return "Assignable Per-Note Controller " + getByte4()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Note " + getNoteName()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x2: return "Registered Controller Bank " + getByte3()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Index " + getByte4()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x3: return "Assignable Controller Bank " + getByte3()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Index " + getByte4()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x4: return "Relative Registered Controller Bank " + getByte3()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Index " + getByte4()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x5: return "Relative Assignable Controller Bank " + getByte3()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Index " + getByte4()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x6: return "Per-Note Pitch Bend Note " + getNoteName()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0x8: return "Note Off " + getNoteName()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Attribute Type " + getByte4()
|
||||
+ " Velocity " + getVelocity()
|
||||
+ " Attribute Data " + getAttribute();
|
||||
case 0x9: return "Note On " + getNoteName()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Attribute Type " + getByte4()
|
||||
+ " Velocity " + getVelocity()
|
||||
+ " Attribute Data " + getAttribute();
|
||||
case 0xa: return "Poly Pressure Note " + getNoteName()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0xb: return "Control Change " + getByte3()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Data " + String::toHexString (p[1]);
|
||||
case 0xc: return "Program Change Options " + getByte4()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Program " + String::toHexString ((p[1] >> 0x18) & 0xff)
|
||||
+ " Bank MSB " + String::toHexString ((p[1] >> 0x08) & 0xff)
|
||||
+ " Bank LSB " + String::toHexString ((p[1] >> 0x00) & 0xff);
|
||||
case 0xd: return "Channel Pressure " + String::toHexString (p[1])
|
||||
+ " Channel " + getChannel();
|
||||
case 0xe: return "Pitch Bend " + String::toHexString (p[1])
|
||||
+ " Channel " + getChannel();
|
||||
case 0xf: return "Per-Note Management Note " + getNoteName()
|
||||
+ " Channel " + getChannel()
|
||||
+ " Options " + getByte4();
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getPacketDescription (const PacketX2& p)
|
||||
{
|
||||
switch (Utils::getMessageType (p.front()))
|
||||
{
|
||||
case Utils::MessageKind::sysex7: return "Data 64-Bit: " + getData64MessageDescription (p);
|
||||
case Utils::MessageKind::channelVoice2: return "MIDI 2.0 Channel Voice: " + getMidi2ChannelVoiceDescription (p);
|
||||
|
||||
case Utils::MessageKind::utility:
|
||||
case Utils::MessageKind::channelVoice1:
|
||||
case Utils::MessageKind::sysex8:
|
||||
case Utils::MessageKind::commonRealtime:
|
||||
case Utils::MessageKind::stream:
|
||||
break;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getPacketDescription (const PacketX3&)
|
||||
{
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
static String getPacketDescription (const PacketX4& p)
|
||||
{
|
||||
switch (Utils::getMessageType (p[0]))
|
||||
{
|
||||
case Utils::MessageKind::sysex8: return "Data 128 Bit"; // TODO
|
||||
case Utils::MessageKind::stream: return "Stream Configuration"; // TODO
|
||||
|
||||
case Utils::MessageKind::utility:
|
||||
case Utils::MessageKind::sysex7:
|
||||
case Utils::MessageKind::channelVoice1:
|
||||
case Utils::MessageKind::channelVoice2:
|
||||
case Utils::MessageKind::commonRealtime:
|
||||
break;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
String StringUtils::getDescription (const View& v)
|
||||
{
|
||||
const auto group = (String ("Group ") + String (Utils::getGroup (*v.data()))) + ' ';
|
||||
|
||||
switch (v.size())
|
||||
{
|
||||
case 1:
|
||||
return group + getPacketDescription (PacketX1 { v[0] });
|
||||
|
||||
case 2:
|
||||
return group + getPacketDescription (PacketX2 { v[0], v[1] });
|
||||
|
||||
case 3:
|
||||
return group + getPacketDescription (PacketX3 { v[0], v[1], v[2] });
|
||||
|
||||
case 4:
|
||||
return group + getPacketDescription (PacketX4 { v[0], v[1], v[2], v[3] });
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
/**
|
||||
Holds utility functions for extracting textual representations of Universal
|
||||
MIDI Packets.
|
||||
*/
|
||||
struct StringUtils
|
||||
{
|
||||
/** Return a textual description of this packet. */
|
||||
static String getHexString (const View&);
|
||||
|
||||
/** Return a textual description of this packet. */
|
||||
static String getDescription (const View&);
|
||||
|
||||
private:
|
||||
StringUtils() = default;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
uint32_t SysEx7::getNumPacketsRequiredForDataSize (uint32_t size)
|
||||
{
|
||||
constexpr auto denom = 6;
|
||||
return (size / denom) + ((size % denom) != 0);
|
||||
}
|
||||
|
||||
SysEx7::PacketBytes SysEx7::getDataBytes (const PacketX2& packet)
|
||||
{
|
||||
const auto numBytes = Utils::getChannel (packet[0]);
|
||||
constexpr uint8_t maxBytes = 6;
|
||||
jassert (numBytes <= maxBytes);
|
||||
|
||||
return
|
||||
{
|
||||
{ { std::byte { packet.getU8<2>() },
|
||||
std::byte { packet.getU8<3>() },
|
||||
std::byte { packet.getU8<4>() },
|
||||
std::byte { packet.getU8<5>() },
|
||||
std::byte { packet.getU8<6>() },
|
||||
std::byte { packet.getU8<7>() } } },
|
||||
jmin (numBytes, maxBytes)
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
This struct acts as a single-file namespace for Universal MIDI Packet
|
||||
functionality related to 7-bit SysEx.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct SysEx7
|
||||
{
|
||||
/** Returns the number of 64-bit packets required to hold a series of
|
||||
SysEx bytes.
|
||||
|
||||
The number passed to this function should exclude the leading/trailing
|
||||
SysEx bytes used in an old midi bytestream, as these are not required
|
||||
when using Universal MIDI Packets.
|
||||
*/
|
||||
static uint32_t getNumPacketsRequiredForDataSize (uint32_t);
|
||||
|
||||
/** The different kinds of UMP SysEx-7 message. */
|
||||
enum class Kind : uint8_t
|
||||
{
|
||||
/** The whole message fits in a single 2-word packet. */
|
||||
complete = 0,
|
||||
|
||||
/** The packet begins a SysEx message that will continue in subsequent packets. */
|
||||
begin = 1,
|
||||
|
||||
/** The packet is a continuation of an ongoing SysEx message. */
|
||||
continuation = 2,
|
||||
|
||||
/** The packet terminates an ongoing SysEx message. */
|
||||
end = 3
|
||||
};
|
||||
|
||||
/** Holds the bytes from a single SysEx-7 packet. */
|
||||
struct PacketBytes
|
||||
{
|
||||
std::array<std::byte, 6> data;
|
||||
uint8_t size;
|
||||
};
|
||||
|
||||
/** Extracts the data bytes from a 64-bit data message. */
|
||||
static PacketBytes getDataBytes (const PacketX2& packet);
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
uint32_t Utils::getNumWordsForMessageType (uint32_t mt)
|
||||
{
|
||||
switch ((uint8_t) Utils::getMessageType (mt))
|
||||
{
|
||||
case 0x0:
|
||||
case 0x1:
|
||||
case 0x2:
|
||||
case 0x6:
|
||||
case 0x7:
|
||||
return 1;
|
||||
case 0x3:
|
||||
case 0x4:
|
||||
case 0x8:
|
||||
case 0x9:
|
||||
case 0xa:
|
||||
return 2;
|
||||
case 0xb:
|
||||
case 0xc:
|
||||
return 3;
|
||||
case 0x5:
|
||||
case 0xd:
|
||||
case 0xe:
|
||||
case 0xf:
|
||||
return 4;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return 1;
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Helpful types and functions for interacting with Universal MIDI Packets.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct Utils
|
||||
{
|
||||
/** Joins 4 bytes into a single 32-bit word. */
|
||||
static constexpr uint32_t bytesToWord (std::byte a, std::byte b, std::byte c, std::byte d)
|
||||
{
|
||||
return uint32_t (a) << 0x18
|
||||
| uint32_t (b) << 0x10
|
||||
| uint32_t (c) << 0x08
|
||||
| uint32_t (d) << 0x00;
|
||||
}
|
||||
|
||||
/** Returns the expected number of 32-bit words in a Universal MIDI Packet, given
|
||||
the first word of the packet.
|
||||
|
||||
The result will be between 1 and 4 inclusive.
|
||||
A result of 1 means that the word is itself a complete packet.
|
||||
*/
|
||||
static uint32_t getNumWordsForMessageType (uint32_t);
|
||||
|
||||
/**
|
||||
Helper functions for setting/getting 4-bit ranges inside a 32-bit word.
|
||||
*/
|
||||
template <size_t Index>
|
||||
struct U4
|
||||
{
|
||||
static constexpr uint32_t shift = (uint32_t) 0x1c - Index * 4;
|
||||
|
||||
static constexpr uint32_t set (uint32_t word, uint8_t value)
|
||||
{
|
||||
return (word & ~((uint32_t) 0xf << shift)) | (uint32_t) ((value & 0xf) << shift);
|
||||
}
|
||||
|
||||
static constexpr uint8_t get (uint32_t word)
|
||||
{
|
||||
return (word >> shift) & 0xf;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
Helper functions for setting/getting 8-bit ranges inside a 32-bit word.
|
||||
*/
|
||||
template <size_t Index>
|
||||
struct U8
|
||||
{
|
||||
static constexpr uint32_t shift = (uint32_t) 0x18 - Index * 8;
|
||||
|
||||
static constexpr uint32_t set (uint32_t word, uint8_t value)
|
||||
{
|
||||
return (word & ~((uint32_t) 0xff << shift)) | (uint32_t) (value << shift);
|
||||
}
|
||||
|
||||
static constexpr uint8_t get (uint32_t word)
|
||||
{
|
||||
return (word >> shift) & 0xff;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
Helper functions for setting/getting 16-bit ranges inside a 32-bit word.
|
||||
*/
|
||||
template <size_t Index>
|
||||
struct U16
|
||||
{
|
||||
static constexpr uint32_t shift = (uint32_t) 0x10 - Index * 16;
|
||||
|
||||
static constexpr uint32_t set (uint32_t word, uint16_t value)
|
||||
{
|
||||
return (word & ~((uint32_t) 0xffff << shift)) | (uint32_t) (value << shift);
|
||||
}
|
||||
|
||||
static constexpr uint16_t get (uint32_t word)
|
||||
{
|
||||
return (uint16_t) ((word >> shift) & 0xffff);
|
||||
}
|
||||
};
|
||||
|
||||
enum class MessageKind : uint8_t
|
||||
{
|
||||
utility = 0x0,
|
||||
commonRealtime = 0x1,
|
||||
channelVoice1 = 0x2,
|
||||
sysex7 = 0x3,
|
||||
channelVoice2 = 0x4,
|
||||
sysex8 = 0x5,
|
||||
stream = 0xf,
|
||||
};
|
||||
|
||||
static constexpr bool hasGroup (MessageKind k)
|
||||
{
|
||||
return ! isGroupless (k);
|
||||
}
|
||||
|
||||
static constexpr bool isGroupless (MessageKind k)
|
||||
{
|
||||
return k == MessageKind::utility || k == MessageKind::stream;
|
||||
}
|
||||
|
||||
static constexpr MessageKind getMessageType (uint32_t w) noexcept { return MessageKind { U4<0>::get (w) }; }
|
||||
static constexpr std::byte getStatus (uint32_t w) noexcept { return std::byte { U4<2>::get (w) }; }
|
||||
static constexpr uint8_t getChannel (uint32_t w) noexcept { return U4<3>::get (w); }
|
||||
static constexpr uint8_t getGroup (uint32_t w) noexcept { return U4<1>::get (w); }
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
uint32_t View::size() const noexcept
|
||||
{
|
||||
jassert (ptr != nullptr);
|
||||
return Utils::getNumWordsForMessageType (*ptr);
|
||||
}
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Points to a single Universal MIDI Packet.
|
||||
|
||||
The packet must be well-formed for member functions to work correctly.
|
||||
|
||||
Specifically, the constructor argument must be the beginning of a region of
|
||||
uint32_t that contains at least `getNumWordsForMessageType (*data)` items,
|
||||
where `data` is the constructor argument.
|
||||
|
||||
NOTE: Instances of this class do not own the memory that they point to!
|
||||
If you need to store a packet pointed-to by a View for later use, copy
|
||||
the view contents to a Packets collection, or use the Utils::PacketX types.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class View
|
||||
{
|
||||
public:
|
||||
/** Create an invalid view. */
|
||||
View() noexcept = default;
|
||||
|
||||
/** Create a view of the packet starting at address `d`. */
|
||||
explicit View (const uint32_t* data) noexcept : ptr (data) {}
|
||||
|
||||
/** Get a pointer to the first word in the Universal MIDI Packet currently
|
||||
pointed-to by this view.
|
||||
*/
|
||||
const uint32_t* data() const noexcept { return ptr; }
|
||||
|
||||
/** Get the number of 32 bit words (between 1 and 4 inclusive) in the Universal
|
||||
MIDI Packet currently pointed-to by this view.
|
||||
*/
|
||||
uint32_t size() const noexcept;
|
||||
|
||||
/** Get a specific word from this packet.
|
||||
|
||||
Passing an `index` that is greater than or equal to the result of `size`
|
||||
will cause undefined behaviour.
|
||||
*/
|
||||
const uint32_t& operator[] (size_t index) const noexcept { return ptr[index]; }
|
||||
|
||||
/** Get an iterator pointing to the first word in the packet. */
|
||||
const uint32_t* begin() const noexcept { return ptr; }
|
||||
const uint32_t* cbegin() const noexcept { return ptr; }
|
||||
|
||||
/** Get an iterator pointing one-past the last word in the packet. */
|
||||
const uint32_t* end() const noexcept { return ptr + size(); }
|
||||
const uint32_t* cend() const noexcept { return ptr + size(); }
|
||||
|
||||
/** Return true if this view is pointing to the same address as another view. */
|
||||
bool operator== (const View& other) const noexcept { return ptr == other.ptr; }
|
||||
|
||||
/** Return false if this view is pointing to the same address as another view. */
|
||||
bool operator!= (const View& other) const noexcept { return ! operator== (other); }
|
||||
|
||||
private:
|
||||
const uint32_t* ptr = nullptr;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Holds a single Universal MIDI Packet.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
template <size_t numWords>
|
||||
class Packet
|
||||
{
|
||||
public:
|
||||
Packet() = default;
|
||||
|
||||
template <size_t w = numWords, std::enable_if_t<w == 1, int> = 0>
|
||||
Packet (uint32_t a)
|
||||
: contents { { a } }
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (a) == 1);
|
||||
}
|
||||
|
||||
template <size_t w = numWords, std::enable_if_t<w == 2, int> = 0>
|
||||
Packet (uint32_t a, uint32_t b)
|
||||
: contents { { a, b } }
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (a) == 2);
|
||||
}
|
||||
|
||||
template <size_t w = numWords, std::enable_if_t<w == 3, int> = 0>
|
||||
Packet (uint32_t a, uint32_t b, uint32_t c)
|
||||
: contents { { a, b, c } }
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (a) == 3);
|
||||
}
|
||||
|
||||
template <size_t w = numWords, std::enable_if_t<w == 4, int> = 0>
|
||||
Packet (uint32_t a, uint32_t b, uint32_t c, uint32_t d)
|
||||
: contents { { a, b, c, d } }
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (a) == 4);
|
||||
}
|
||||
|
||||
template <size_t w, std::enable_if_t<w == numWords, int> = 0>
|
||||
explicit Packet (const std::array<uint32_t, w>& fullPacket)
|
||||
: contents (fullPacket)
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (fullPacket.front()) == numWords);
|
||||
}
|
||||
|
||||
Packet withMessageType (Utils::MessageKind type) const noexcept
|
||||
{
|
||||
return withU4<0> (uint8_t (type));
|
||||
}
|
||||
|
||||
Packet withGroup (uint8_t group) const noexcept
|
||||
{
|
||||
return withU4<1> (group);
|
||||
}
|
||||
|
||||
Packet withStatus (std::byte status) const noexcept
|
||||
{
|
||||
return withU4<2> (uint8_t (status));
|
||||
}
|
||||
|
||||
Packet withChannel (uint8_t channel) const noexcept
|
||||
{
|
||||
return withU4<3> (channel);
|
||||
}
|
||||
|
||||
Utils::MessageKind getMessageType() const noexcept { return Utils::MessageKind (getU4<0>()); }
|
||||
|
||||
uint8_t getGroup() const noexcept { return getU4<1>(); }
|
||||
|
||||
std::byte getStatus() const noexcept { return getU4<2>(); }
|
||||
|
||||
uint8_t getChannel() const noexcept { return getU4<3>(); }
|
||||
|
||||
template <size_t index>
|
||||
Packet withU4 (uint8_t value) const noexcept
|
||||
{
|
||||
constexpr auto word = index / 8;
|
||||
auto copy = *this;
|
||||
std::get<word> (copy.contents) = Utils::U4<index % 8>::set (copy.template getU32<word>(), value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
Packet withU8 (uint8_t value) const noexcept
|
||||
{
|
||||
constexpr auto word = index / 4;
|
||||
auto copy = *this;
|
||||
std::get<word> (copy.contents) = Utils::U8<index % 4>::set (copy.template getU32<word>(), value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
Packet withU16 (uint16_t value) const noexcept
|
||||
{
|
||||
constexpr auto word = index / 2;
|
||||
auto copy = *this;
|
||||
std::get<word> (copy.contents) = Utils::U16<index % 2>::set (copy.template getU32<word>(), value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
Packet withU32 (uint32_t value) const noexcept
|
||||
{
|
||||
auto copy = *this;
|
||||
std::get<index> (copy.contents) = value;
|
||||
return copy;
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
uint8_t getU4() const noexcept
|
||||
{
|
||||
return Utils::U4<index % 8>::get (this->template getU32<index / 8>());
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
uint8_t getU8() const noexcept
|
||||
{
|
||||
return Utils::U8<index % 4>::get (this->template getU32<index / 4>());
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
uint16_t getU16() const noexcept
|
||||
{
|
||||
return Utils::U16<index % 2>::get (this->template getU32<index / 2>());
|
||||
}
|
||||
|
||||
template <size_t index>
|
||||
uint32_t getU32() const noexcept
|
||||
{
|
||||
return std::get<index> (contents);
|
||||
}
|
||||
|
||||
bool operator== (const Packet& other) const
|
||||
{
|
||||
return contents == other.contents;
|
||||
}
|
||||
|
||||
bool operator!= (const Packet& other) const
|
||||
{
|
||||
return contents != other.contents;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
using Contents = std::array<uint32_t, numWords>;
|
||||
|
||||
using const_iterator = typename Contents::const_iterator;
|
||||
|
||||
const_iterator begin() const noexcept { return contents.begin(); }
|
||||
const_iterator cbegin() const noexcept { return contents.begin(); }
|
||||
|
||||
const_iterator end() const noexcept { return contents.end(); }
|
||||
const_iterator cend() const noexcept { return contents.end(); }
|
||||
|
||||
const uint32_t* data() const noexcept { return contents.data(); }
|
||||
size_t size() const noexcept { return contents.size(); }
|
||||
|
||||
const uint32_t& front() const noexcept { return contents.front(); }
|
||||
const uint32_t& back() const noexcept { return contents.back(); }
|
||||
|
||||
const uint32_t& operator[] (size_t index) const noexcept { return contents[index]; }
|
||||
|
||||
private:
|
||||
Contents contents { {} };
|
||||
};
|
||||
|
||||
using PacketX1 = Packet<1>;
|
||||
using PacketX2 = Packet<2>;
|
||||
using PacketX3 = Packet<3>;
|
||||
using PacketX4 = Packet<4>;
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
/** @cond */
|
||||
namespace juce::universal_midi_packets
|
||||
{
|
||||
|
||||
/**
|
||||
Holds a collection of Universal MIDI Packets.
|
||||
|
||||
Unlike MidiBuffer, this collection does not store any additional information
|
||||
(e.g. timestamps) alongside the raw messages.
|
||||
|
||||
If timestamps are required, these can be added to the container in UMP format,
|
||||
as Jitter Reduction Utility messages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class Packets
|
||||
{
|
||||
public:
|
||||
/** Adds a single packet to the collection.
|
||||
|
||||
The View must be valid for this to work. If the view
|
||||
points to a malformed message, or if the view points to a region
|
||||
too short for the contained message, this call will result in
|
||||
undefined behaviour.
|
||||
*/
|
||||
void add (const View& v) { storage.insert (storage.end(), v.cbegin(), v.cend()); }
|
||||
|
||||
void add (const PacketX1& p) { addImpl (p); }
|
||||
void add (const PacketX2& p) { addImpl (p); }
|
||||
void add (const PacketX3& p) { addImpl (p); }
|
||||
void add (const PacketX4& p) { addImpl (p); }
|
||||
|
||||
/** Pre-allocates space for at least `numWords` 32-bit words in this collection. */
|
||||
void reserve (size_t numWords) { storage.reserve (numWords); }
|
||||
|
||||
/** Removes all previously-added packets from this collection. */
|
||||
void clear() { storage.clear(); }
|
||||
|
||||
/** Gets an iterator pointing to the first packet in this collection. */
|
||||
Iterator cbegin() const noexcept { return Iterator (data(), size()); }
|
||||
Iterator begin() const noexcept { return cbegin(); }
|
||||
|
||||
/** Gets an iterator pointing one-past the last packet in this collection. */
|
||||
Iterator cend() const noexcept { return Iterator (data() + size(), 0); }
|
||||
Iterator end() const noexcept { return cend(); }
|
||||
|
||||
/** Gets a pointer to the contents of the collection as a range of raw 32-bit words. */
|
||||
const uint32_t* data() const noexcept { return storage.data(); }
|
||||
|
||||
/** Returns the number of uint32_t words in storage.
|
||||
|
||||
Note that this is likely to be larger than the number of packets
|
||||
currently being stored, as some packets span multiple words.
|
||||
*/
|
||||
size_t size() const noexcept { return storage.size(); }
|
||||
|
||||
private:
|
||||
template <size_t numWords>
|
||||
void addImpl (const Packet<numWords>& p)
|
||||
{
|
||||
jassert (Utils::getNumWordsForMessageType (p[0]) == numWords);
|
||||
add (View (p.data()));
|
||||
}
|
||||
|
||||
std::vector<uint32_t> storage;
|
||||
};
|
||||
|
||||
} // namespace juce::universal_midi_packets
|
||||
/** @endcond */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,438 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class represents an instrument handling MPE.
|
||||
|
||||
It has an MPE zone layout and maintains a state of currently
|
||||
active (playing) notes and the values of their dimensions of expression.
|
||||
|
||||
You can trigger and modulate notes:
|
||||
- by passing MIDI messages with the method processNextMidiEvent;
|
||||
- by directly calling the methods noteOn, noteOff etc.
|
||||
|
||||
The class implements the channel and note management logic specified in
|
||||
MPE. If you pass it a message, it will know what notes on what
|
||||
channels (if any) should be affected by that message.
|
||||
|
||||
The class has a Listener class that can be used to react to note and
|
||||
state changes and trigger some functionality for your application.
|
||||
For example, you can use this class to write an MPE visualiser.
|
||||
|
||||
If you want to write a real-time audio synth with MPE functionality,
|
||||
you should instead use the classes MPESynthesiserBase, which adds
|
||||
the ability to render audio and to manage voices.
|
||||
|
||||
@see MPENote, MPEZoneLayout, MPESynthesiser
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPEInstrument
|
||||
{
|
||||
public:
|
||||
/** Constructor.
|
||||
|
||||
This will construct an MPE instrument with inactive lower and upper zones.
|
||||
|
||||
In order to process incoming MIDI messages call setZoneLayout, use the MPEZoneLayout
|
||||
constructor, define the layout via MIDI RPN messages, or set the instrument to legacy mode.
|
||||
*/
|
||||
MPEInstrument() noexcept;
|
||||
|
||||
/** Constructs an MPE instrument with the specified zone layout. */
|
||||
MPEInstrument (MPEZoneLayout layout);
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~MPEInstrument();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the current zone layout of the instrument.
|
||||
This happens by value, to enforce thread-safety and class invariants.
|
||||
|
||||
Note: If the instrument is in legacy mode, the return value of this
|
||||
method is unspecified.
|
||||
*/
|
||||
MPEZoneLayout getZoneLayout() const noexcept;
|
||||
|
||||
/** Re-sets the zone layout of the instrument to the one passed in.
|
||||
As a side effect, this will discard all currently playing notes,
|
||||
and call noteReleased for all of them.
|
||||
|
||||
This will also disable legacy mode in case it was enabled previously.
|
||||
*/
|
||||
void setZoneLayout (MPEZoneLayout newLayout);
|
||||
|
||||
/** Returns true if the given MIDI channel (1-16) is a note channel in any
|
||||
of the MPEInstrument's MPE zones; false otherwise.
|
||||
|
||||
When in legacy mode, this will return true if the given channel is
|
||||
contained in the current legacy mode channel range; false otherwise.
|
||||
*/
|
||||
bool isMemberChannel (int midiChannel) const noexcept;
|
||||
|
||||
/** Returns true if the given MIDI channel (1-16) is a master channel (channel
|
||||
1 or 16).
|
||||
|
||||
In legacy mode, this will always return false.
|
||||
*/
|
||||
bool isMasterChannel (int midiChannel) const noexcept;
|
||||
|
||||
/** Returns true if the given MIDI channel (1-16) is used by any of the
|
||||
MPEInstrument's MPE zones; false otherwise.
|
||||
|
||||
When in legacy mode, this will return true if the given channel is
|
||||
contained in the current legacy mode channel range; false otherwise.
|
||||
*/
|
||||
bool isUsingChannel (int midiChannel) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** The MPE note tracking mode. In case there is more than one note playing
|
||||
simultaneously on the same MIDI channel, this determines which of these
|
||||
notes will be modulated by an incoming MPE message on that channel
|
||||
(pressure, pitchbend, or timbre).
|
||||
|
||||
The default is lastNotePlayedOnChannel.
|
||||
*/
|
||||
enum TrackingMode
|
||||
{
|
||||
lastNotePlayedOnChannel, /**< The most recent note on the channel that is still played (key down and/or sustained). */
|
||||
lowestNoteOnChannel, /**< The lowest note (by initialNote) on the channel with the note key still down. */
|
||||
highestNoteOnChannel, /**< The highest note (by initialNote) on the channel with the note key still down. */
|
||||
allNotesOnChannel /**< All notes on the channel (key down and/or sustained). */
|
||||
};
|
||||
|
||||
/** Set the MPE tracking mode for the pressure dimension. */
|
||||
void setPressureTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
/** Set the MPE tracking mode for the pitchbend dimension. */
|
||||
void setPitchbendTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
/** Set the MPE tracking mode for the timbre dimension. */
|
||||
void setTimbreTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
//==============================================================================
|
||||
/** Process a MIDI message and trigger the appropriate method calls
|
||||
(noteOn, noteOff etc.)
|
||||
|
||||
You can override this method if you need some special MIDI message
|
||||
treatment on top of the standard MPE logic implemented here.
|
||||
*/
|
||||
virtual void processNextMidiEvent (const MidiMessage& message);
|
||||
|
||||
//==============================================================================
|
||||
/** Request a note-on on the given channel, with the given initial note
|
||||
number and velocity.
|
||||
|
||||
If the message arrives on a valid note channel, this will create a
|
||||
new MPENote and call the noteAdded callback.
|
||||
*/
|
||||
virtual void noteOn (int midiChannel, int midiNoteNumber, MPEValue midiNoteOnVelocity);
|
||||
|
||||
/** Request a note-off.
|
||||
|
||||
If there is a matching playing note, this will release the note
|
||||
(except if it is sustained by a sustain or sostenuto pedal) and call
|
||||
the noteReleased callback.
|
||||
*/
|
||||
virtual void noteOff (int midiChannel, int midiNoteNumber, MPEValue midiNoteOffVelocity);
|
||||
|
||||
/** Request a pitchbend on the given channel with the given value (in units
|
||||
of MIDI pitchwheel position).
|
||||
|
||||
Internally, this will determine whether the pitchwheel move is a
|
||||
per-note pitchbend or a master pitchbend (depending on midiChannel),
|
||||
take the correct per-note or master pitchbend range of the affected MPE
|
||||
zone, and apply the resulting pitchbend to the affected note(s) (if any).
|
||||
*/
|
||||
virtual void pitchbend (int midiChannel, MPEValue pitchbend);
|
||||
|
||||
/** Request a pressure change on the given channel with the given value.
|
||||
|
||||
This will modify the pressure dimension of the note currently held down
|
||||
on this channel (if any). If the channel is a zone master channel,
|
||||
the pressure change will be broadcast to all notes in this zone.
|
||||
*/
|
||||
virtual void pressure (int midiChannel, MPEValue value);
|
||||
|
||||
/** Request a third dimension (timbre) change on the given channel with the
|
||||
given value.
|
||||
|
||||
This will modify the timbre dimension of the note currently held down
|
||||
on this channel (if any). If the channel is a zone master channel,
|
||||
the timbre change will be broadcast to all notes in this zone.
|
||||
*/
|
||||
virtual void timbre (int midiChannel, MPEValue value);
|
||||
|
||||
/** Request a poly-aftertouch change for a given note number.
|
||||
|
||||
The change will be broadcast to all notes sharing the channel and note
|
||||
number of the change message.
|
||||
*/
|
||||
virtual void polyAftertouch (int midiChannel, int midiNoteNumber, MPEValue value);
|
||||
|
||||
/** Request a sustain pedal press or release.
|
||||
|
||||
If midiChannel is a zone's master channel, this will act on all notes in
|
||||
that zone; otherwise, nothing will happen.
|
||||
*/
|
||||
virtual void sustainPedal (int midiChannel, bool isDown);
|
||||
|
||||
/** Request a sostenuto pedal press or release.
|
||||
|
||||
If midiChannel is a zone's master channel, this will act on all notes in
|
||||
that zone; otherwise, nothing will happen.
|
||||
*/
|
||||
virtual void sostenutoPedal (int midiChannel, bool isDown);
|
||||
|
||||
/** Discard all currently playing notes.
|
||||
|
||||
This will also call the noteReleased listener callback for all of them.
|
||||
*/
|
||||
void releaseAllNotes();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of MPE notes currently played by the instrument. */
|
||||
int getNumPlayingNotes() const noexcept;
|
||||
|
||||
/** Returns the note at the given index.
|
||||
|
||||
If there is no such note, returns an invalid MPENote. The notes are sorted
|
||||
such that the most recently added note is the last element.
|
||||
*/
|
||||
MPENote getNote (int index) const noexcept;
|
||||
|
||||
/** Returns the note currently playing on the given midiChannel with the
|
||||
specified initial MIDI note number, if there is such a note. Otherwise,
|
||||
this returns an invalid MPENote (check with note.isValid() before use!)
|
||||
*/
|
||||
MPENote getNote (int midiChannel, int midiNoteNumber) const noexcept;
|
||||
|
||||
/** Returns the note with a given ID. */
|
||||
MPENote getNoteWithID (uint16 noteID) const noexcept;
|
||||
|
||||
/** Returns the most recent note that is playing on the given midiChannel
|
||||
(this will be the note which has received the most recent note-on without
|
||||
a corresponding note-off), if there is such a note. Otherwise, this returns an
|
||||
invalid MPENote (check with note.isValid() before use!)
|
||||
*/
|
||||
MPENote getMostRecentNote (int midiChannel) const noexcept;
|
||||
|
||||
/** Returns the most recent note that is not the note passed in. If there is no
|
||||
such note, this returns an invalid MPENote (check with note.isValid() before use!).
|
||||
|
||||
This helper method might be useful for some custom voice handling algorithms.
|
||||
*/
|
||||
MPENote getMostRecentNoteOtherThan (MPENote otherThanThisNote) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Derive from this class to be informed about any changes in the MPE notes played
|
||||
by this instrument, and any changes to its zone layout.
|
||||
|
||||
Note: This listener type receives its callbacks immediately, and not
|
||||
via the message thread (so you might be for example in the MIDI thread).
|
||||
Therefore you should never do heavy work such as graphics rendering etc.
|
||||
inside those callbacks.
|
||||
*/
|
||||
class JUCE_API Listener
|
||||
{
|
||||
public:
|
||||
/** Destructor. */
|
||||
virtual ~Listener() = default;
|
||||
|
||||
/** Implement this callback to be informed whenever a new expressive MIDI
|
||||
note is triggered.
|
||||
*/
|
||||
virtual void noteAdded (MPENote newNote);
|
||||
|
||||
/** Implement this callback to be informed whenever a currently playing
|
||||
MPE note's pressure value changes.
|
||||
*/
|
||||
virtual void notePressureChanged (MPENote changedNote);
|
||||
|
||||
/** Implement this callback to be informed whenever a currently playing
|
||||
MPE note's pitchbend value changes.
|
||||
|
||||
Note: This can happen if the note itself is bent, if there is a
|
||||
master channel pitchbend event, or if both occur simultaneously.
|
||||
Call MPENote::getFrequencyInHertz to get the effective note frequency.
|
||||
*/
|
||||
virtual void notePitchbendChanged (MPENote changedNote);
|
||||
|
||||
/** Implement this callback to be informed whenever a currently playing
|
||||
MPE note's timbre value changes.
|
||||
*/
|
||||
virtual void noteTimbreChanged (MPENote changedNote);
|
||||
|
||||
/** Implement this callback to be informed whether a currently playing
|
||||
MPE note's key state (whether the key is down and/or the note is
|
||||
sustained) has changed.
|
||||
|
||||
Note: If the key state changes to MPENote::off, noteReleased is
|
||||
called instead.
|
||||
*/
|
||||
virtual void noteKeyStateChanged (MPENote changedNote);
|
||||
|
||||
/** Implement this callback to be informed whenever an MPE note
|
||||
is released (either by a note-off message, or by a sustain/sostenuto
|
||||
pedal release for a note that already received a note-off),
|
||||
and should therefore stop playing.
|
||||
*/
|
||||
virtual void noteReleased (MPENote finishedNote);
|
||||
|
||||
/** Implement this callback to be informed whenever the MPE zone layout
|
||||
or legacy mode settings of this instrument have been changed.
|
||||
*/
|
||||
virtual void zoneLayoutChanged();
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a listener. */
|
||||
void addListener (Listener* listenerToAdd);
|
||||
|
||||
/** Removes a listener. */
|
||||
void removeListener (Listener* listenerToRemove);
|
||||
|
||||
//==============================================================================
|
||||
/** Puts the instrument into legacy mode. If legacy mode is already enabled this method
|
||||
does nothing.
|
||||
|
||||
As a side effect, this will discard all currently playing notes,
|
||||
and call noteReleased for all of them.
|
||||
|
||||
This special zone layout mode is for backwards compatibility with
|
||||
non-MPE MIDI devices. In this mode, the instrument will ignore the
|
||||
current MPE zone layout. It will instead take a range of MIDI channels
|
||||
(default: all channels 1-16) and treat them as note channels, with no
|
||||
master channel. MIDI channels outside of this range will be ignored.
|
||||
|
||||
@param pitchbendRange The note pitchbend range in semitones to use when in legacy mode.
|
||||
Must be between 0 and 96, otherwise behaviour is undefined.
|
||||
The default pitchbend range in legacy mode is +/- 2 semitones.
|
||||
|
||||
@param channelRange The range of MIDI channels to use for notes when in legacy mode.
|
||||
The default is to use all MIDI channels (1-16).
|
||||
|
||||
To get out of legacy mode, set a new MPE zone layout using setZoneLayout.
|
||||
*/
|
||||
void enableLegacyMode (int pitchbendRange = 2,
|
||||
Range<int> channelRange = Range<int> (1, 17));
|
||||
|
||||
/** Returns true if the instrument is in legacy mode, false otherwise. */
|
||||
bool isLegacyModeEnabled() const noexcept;
|
||||
|
||||
/** Returns the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
|
||||
Range<int> getLegacyModeChannelRange() const noexcept;
|
||||
|
||||
/** Re-sets the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
|
||||
void setLegacyModeChannelRange (Range<int> channelRange);
|
||||
|
||||
/** Returns the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
|
||||
int getLegacyModePitchbendRange() const noexcept;
|
||||
|
||||
/** Re-sets the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
|
||||
void setLegacyModePitchbendRange (int pitchbendRange);
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
CriticalSection lock;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
Array<MPENote> notes;
|
||||
MPEZoneLayout zoneLayout;
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
uint8 lastPressureLowerBitReceivedOnChannel[16];
|
||||
uint8 lastTimbreLowerBitReceivedOnChannel[16];
|
||||
bool isMemberChannelSustained[16];
|
||||
|
||||
struct LegacyMode
|
||||
{
|
||||
bool isEnabled = false;
|
||||
Range<int> channelRange;
|
||||
int pitchbendRange = 2;
|
||||
};
|
||||
|
||||
struct MPEDimension
|
||||
{
|
||||
TrackingMode trackingMode = lastNotePlayedOnChannel;
|
||||
MPEValue lastValueReceivedOnChannel[16];
|
||||
MPEValue MPENote::* value;
|
||||
MPEValue& getValue (MPENote& note) noexcept { return note.*(value); }
|
||||
};
|
||||
|
||||
LegacyMode legacyMode;
|
||||
MPEDimension pitchbendDimension, pressureDimension, timbreDimension;
|
||||
|
||||
void resetLastReceivedValues();
|
||||
|
||||
void updateDimension (int midiChannel, MPEDimension&, MPEValue);
|
||||
void updateDimensionMaster (bool, MPEDimension&, MPEValue);
|
||||
void updateDimensionForNote (MPENote&, MPEDimension&, MPEValue);
|
||||
void callListenersDimensionChanged (const MPENote&, const MPEDimension&);
|
||||
MPEValue getInitialValueForNewNote (int midiChannel, MPEDimension&) const;
|
||||
|
||||
void processMidiNoteOnMessage (const MidiMessage&);
|
||||
void processMidiNoteOffMessage (const MidiMessage&);
|
||||
void processMidiPitchWheelMessage (const MidiMessage&);
|
||||
void processMidiChannelPressureMessage (const MidiMessage&);
|
||||
void processMidiControllerMessage (const MidiMessage&);
|
||||
void processMidiResetAllControllersMessage (const MidiMessage&);
|
||||
void processMidiAfterTouchMessage (const MidiMessage&);
|
||||
void handlePressureMSB (int midiChannel, int value) noexcept;
|
||||
void handlePressureLSB (int midiChannel, int value) noexcept;
|
||||
void handleTimbreMSB (int midiChannel, int value) noexcept;
|
||||
void handleTimbreLSB (int midiChannel, int value) noexcept;
|
||||
void handleSustainOrSostenuto (int midiChannel, bool isDown, bool isSostenuto);
|
||||
|
||||
const MPENote* getNotePtr (int midiChannel, int midiNoteNumber) const noexcept;
|
||||
MPENote* getNotePtr (int midiChannel, int midiNoteNumber) noexcept;
|
||||
const MPENote* getNotePtr (int midiChannel, TrackingMode) const noexcept;
|
||||
MPENote* getNotePtr (int midiChannel, TrackingMode) noexcept;
|
||||
const MPENote* getLastNotePlayedPtr (int midiChannel) const noexcept;
|
||||
MPENote* getLastNotePlayedPtr (int midiChannel) noexcept;
|
||||
const MPENote* getHighestNotePtr (int midiChannel) const noexcept;
|
||||
MPENote* getHighestNotePtr (int midiChannel) noexcept;
|
||||
const MPENote* getLowestNotePtr (int midiChannel) const noexcept;
|
||||
MPENote* getLowestNotePtr (int midiChannel) noexcept;
|
||||
void updateNoteTotalPitchbend (MPENote&);
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEInstrument)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MidiBuffer MPEMessages::setLowerZone (int numMemberChannels, int perNotePitchbendRange, int masterPitchbendRange)
|
||||
{
|
||||
auto buffer = MidiRPNGenerator::generate (1, zoneLayoutMessagesRpnNumber, numMemberChannels, false, false);
|
||||
|
||||
buffer.addEvents (setLowerZonePerNotePitchbendRange (perNotePitchbendRange), 0, -1, 0);
|
||||
buffer.addEvents (setLowerZoneMasterPitchbendRange (masterPitchbendRange), 0, -1, 0);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setUpperZone (int numMemberChannels, int perNotePitchbendRange, int masterPitchbendRange)
|
||||
{
|
||||
auto buffer = MidiRPNGenerator::generate (16, zoneLayoutMessagesRpnNumber, numMemberChannels, false, false);
|
||||
|
||||
buffer.addEvents (setUpperZonePerNotePitchbendRange (perNotePitchbendRange), 0, -1, 0);
|
||||
buffer.addEvents (setUpperZoneMasterPitchbendRange (masterPitchbendRange), 0, -1, 0);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setLowerZonePerNotePitchbendRange (int perNotePitchbendRange)
|
||||
{
|
||||
return MidiRPNGenerator::generate (2, 0, perNotePitchbendRange, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setUpperZonePerNotePitchbendRange (int perNotePitchbendRange)
|
||||
{
|
||||
return MidiRPNGenerator::generate (15, 0, perNotePitchbendRange, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setLowerZoneMasterPitchbendRange (int masterPitchbendRange)
|
||||
{
|
||||
return MidiRPNGenerator::generate (1, 0, masterPitchbendRange, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setUpperZoneMasterPitchbendRange (int masterPitchbendRange)
|
||||
{
|
||||
return MidiRPNGenerator::generate (16, 0, masterPitchbendRange, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::clearLowerZone()
|
||||
{
|
||||
return MidiRPNGenerator::generate (1, zoneLayoutMessagesRpnNumber, 0, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::clearUpperZone()
|
||||
{
|
||||
return MidiRPNGenerator::generate (16, zoneLayoutMessagesRpnNumber, 0, false, false);
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::clearAllZones()
|
||||
{
|
||||
MidiBuffer buffer;
|
||||
|
||||
buffer.addEvents (clearLowerZone(), 0, -1, 0);
|
||||
buffer.addEvents (clearUpperZone(), 0, -1, 0);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
MidiBuffer MPEMessages::setZoneLayout (MPEZoneLayout layout)
|
||||
{
|
||||
MidiBuffer buffer;
|
||||
|
||||
buffer.addEvents (clearAllZones(), 0, -1, 0);
|
||||
|
||||
auto lowerZone = layout.getLowerZone();
|
||||
if (lowerZone.isActive())
|
||||
buffer.addEvents (setLowerZone (lowerZone.numMemberChannels,
|
||||
lowerZone.perNotePitchbendRange,
|
||||
lowerZone.masterPitchbendRange),
|
||||
0, -1, 0);
|
||||
|
||||
auto upperZone = layout.getUpperZone();
|
||||
if (upperZone.isActive())
|
||||
buffer.addEvents (setUpperZone (upperZone.numMemberChannels,
|
||||
upperZone.perNotePitchbendRange,
|
||||
upperZone.masterPitchbendRange),
|
||||
0, -1, 0);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class MPEMessagesTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MPEMessagesTests()
|
||||
: UnitTest ("MPEMessages class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("add zone");
|
||||
{
|
||||
{
|
||||
MidiBuffer buffer = MPEMessages::setLowerZone (7);
|
||||
|
||||
const uint8 expectedBytes[] =
|
||||
{
|
||||
0xb0, 0x64, 0x06, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x07, // set up zone
|
||||
0xb1, 0x64, 0x00, 0xb1, 0x65, 0x00, 0xb1, 0x06, 0x30, // per-note pbrange (default = 48)
|
||||
0xb0, 0x64, 0x00, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x02 // master pbrange (default = 2)
|
||||
};
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
{
|
||||
MidiBuffer buffer = MPEMessages::setUpperZone (5, 96, 0);
|
||||
|
||||
const uint8 expectedBytes[] =
|
||||
{
|
||||
0xbf, 0x64, 0x06, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x05, // set up zone
|
||||
0xbe, 0x64, 0x00, 0xbe, 0x65, 0x00, 0xbe, 0x06, 0x60, // per-note pbrange (custom)
|
||||
0xbf, 0x64, 0x00, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x00 // master pbrange (custom)
|
||||
};
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("set per-note pitchbend range");
|
||||
{
|
||||
MidiBuffer buffer = MPEMessages::setLowerZonePerNotePitchbendRange (96);
|
||||
|
||||
const uint8 expectedBytes[] = { 0xb1, 0x64, 0x00, 0xb1, 0x65, 0x00, 0xb1, 0x06, 0x60 };
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
|
||||
|
||||
beginTest ("set master pitchbend range");
|
||||
{
|
||||
MidiBuffer buffer = MPEMessages::setUpperZoneMasterPitchbendRange (60);
|
||||
|
||||
const uint8 expectedBytes[] = { 0xbf, 0x64, 0x00, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x3c };
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
|
||||
beginTest ("clear all zones");
|
||||
{
|
||||
MidiBuffer buffer = MPEMessages::clearAllZones();
|
||||
|
||||
const uint8 expectedBytes[] = { 0xb0, 0x64, 0x06, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x00, // clear lower zone
|
||||
0xbf, 0x64, 0x06, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x00 // clear upper zone
|
||||
};
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
|
||||
beginTest ("set complete state");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
|
||||
layout.setLowerZone (7, 96, 0);
|
||||
layout.setUpperZone (7);
|
||||
|
||||
MidiBuffer buffer = MPEMessages::setZoneLayout (layout);
|
||||
|
||||
const uint8 expectedBytes[] = {
|
||||
0xb0, 0x64, 0x06, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x00, // clear lower zone
|
||||
0xbf, 0x64, 0x06, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x00, // clear upper zone
|
||||
0xb0, 0x64, 0x06, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x07, // set lower zone
|
||||
0xb1, 0x64, 0x00, 0xb1, 0x65, 0x00, 0xb1, 0x06, 0x60, // per-note pbrange (custom)
|
||||
0xb0, 0x64, 0x00, 0xb0, 0x65, 0x00, 0xb0, 0x06, 0x00, // master pbrange (custom)
|
||||
0xbf, 0x64, 0x06, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x07, // set upper zone
|
||||
0xbe, 0x64, 0x00, 0xbe, 0x65, 0x00, 0xbe, 0x06, 0x30, // per-note pbrange (default = 48)
|
||||
0xbf, 0x64, 0x00, 0xbf, 0x65, 0x00, 0xbf, 0x06, 0x02 // master pbrange (default = 2)
|
||||
};
|
||||
|
||||
testMidiBuffer (buffer, expectedBytes, sizeof (expectedBytes));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void testMidiBuffer (MidiBuffer& buffer, const uint8* expectedBytes, int expectedBytesSize)
|
||||
{
|
||||
uint8 actualBytes[128] = { 0 };
|
||||
extractRawBinaryData (buffer, actualBytes, sizeof (actualBytes));
|
||||
|
||||
expectEquals (std::memcmp (actualBytes, expectedBytes, (std::size_t) expectedBytesSize), 0);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void extractRawBinaryData (const MidiBuffer& midiBuffer, const uint8* bufferToCopyTo, std::size_t maxBytes)
|
||||
{
|
||||
std::size_t pos = 0;
|
||||
|
||||
for (const auto metadata : midiBuffer)
|
||||
{
|
||||
const uint8* data = metadata.data;
|
||||
std::size_t dataSize = (std::size_t) metadata.numBytes;
|
||||
|
||||
if (pos + dataSize > maxBytes)
|
||||
return;
|
||||
|
||||
std::memcpy ((void*) (bufferToCopyTo + pos), data, dataSize);
|
||||
pos += dataSize;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MPEMessagesTests MPEMessagesUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This helper class contains the necessary helper functions to generate
|
||||
MIDI messages that are exclusive to MPE, such as defining the upper and lower
|
||||
MPE zones and setting per-note and master pitchbend ranges.
|
||||
You can then send them to your MPE device using MidiOutput::sendBlockOfMessagesNow.
|
||||
|
||||
All other MPE messages like per-note pitchbend, pressure, and third
|
||||
dimension, are ordinary MIDI messages that should be created using the MidiMessage
|
||||
class instead. You just need to take care to send them to the appropriate
|
||||
per-note MIDI channel.
|
||||
|
||||
Note: If you are working with an MPEZoneLayout object inside your app,
|
||||
you should not use the message sequences provided here. Instead, you should
|
||||
change the zone layout programmatically with the member functions provided in the
|
||||
MPEZoneLayout class itself. You should also make sure that the Expressive
|
||||
MIDI zone layout of your C++ code and of the MPE device are kept in sync.
|
||||
|
||||
@see MidiMessage, MPEZoneLayout
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPEMessages
|
||||
{
|
||||
public:
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the lower MPE zone.
|
||||
*/
|
||||
static MidiBuffer setLowerZone (int numMemberChannels = 0,
|
||||
int perNotePitchbendRange = 48,
|
||||
int masterPitchbendRange = 2);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the upper MPE zone.
|
||||
*/
|
||||
static MidiBuffer setUpperZone (int numMemberChannels = 0,
|
||||
int perNotePitchbendRange = 48,
|
||||
int masterPitchbendRange = 2);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the per-note pitchbend range of the lower MPE zone.
|
||||
*/
|
||||
static MidiBuffer setLowerZonePerNotePitchbendRange (int perNotePitchbendRange = 48);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the per-note pitchbend range of the upper MPE zone.
|
||||
*/
|
||||
static MidiBuffer setUpperZonePerNotePitchbendRange (int perNotePitchbendRange = 48);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the master pitchbend range of the lower MPE zone.
|
||||
*/
|
||||
static MidiBuffer setLowerZoneMasterPitchbendRange (int masterPitchbendRange = 2);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will set the master pitchbend range of the upper MPE zone.
|
||||
*/
|
||||
static MidiBuffer setUpperZoneMasterPitchbendRange (int masterPitchbendRange = 2);
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will clear the lower zone.
|
||||
*/
|
||||
static MidiBuffer clearLowerZone();
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will clear the upper zone.
|
||||
*/
|
||||
static MidiBuffer clearUpperZone();
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will clear the lower and upper zones.
|
||||
*/
|
||||
static MidiBuffer clearAllZones();
|
||||
|
||||
/** Returns the sequence of MIDI messages that, if sent to an Expressive
|
||||
MIDI device, will reset the whole MPE zone layout of the
|
||||
device to the layout passed in. This will first clear the current lower and upper
|
||||
zones, then then set the zones contained in the passed-in zone layout, and set their
|
||||
per-note and master pitchbend ranges to their current values.
|
||||
*/
|
||||
static MidiBuffer setZoneLayout (MPEZoneLayout layout);
|
||||
|
||||
/** The RPN number used for MPE zone layout messages.
|
||||
|
||||
Pitchbend range messages (both per-note and master) are instead sent
|
||||
on RPN 0 as in standard MIDI 1.0.
|
||||
*/
|
||||
static const int zoneLayoutMessagesRpnNumber = 6;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
uint16 generateNoteID (int midiChannel, int midiNoteNumber) noexcept
|
||||
{
|
||||
jassert (midiChannel > 0 && midiChannel <= 16);
|
||||
jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
|
||||
|
||||
return uint16 ((midiChannel << 7) + midiNoteNumber);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MPENote::MPENote (int midiChannel_,
|
||||
int initialNote_,
|
||||
MPEValue noteOnVelocity_,
|
||||
MPEValue pitchbend_,
|
||||
MPEValue pressure_,
|
||||
MPEValue timbre_,
|
||||
KeyState keyState_) noexcept
|
||||
: noteID (generateNoteID (midiChannel_, initialNote_)),
|
||||
midiChannel (uint8 (midiChannel_)),
|
||||
initialNote (uint8 (initialNote_)),
|
||||
noteOnVelocity (noteOnVelocity_),
|
||||
pitchbend (pitchbend_),
|
||||
pressure (pressure_),
|
||||
initialTimbre (timbre_),
|
||||
timbre (timbre_),
|
||||
keyState (keyState_)
|
||||
{
|
||||
jassert (keyState != MPENote::off);
|
||||
jassert (isValid());
|
||||
}
|
||||
|
||||
MPENote::MPENote() noexcept {}
|
||||
|
||||
//==============================================================================
|
||||
bool MPENote::isValid() const noexcept
|
||||
{
|
||||
return midiChannel > 0 && midiChannel <= 16 && initialNote < 128;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
double MPENote::getFrequencyInHertz (double frequencyOfA) const noexcept
|
||||
{
|
||||
auto pitchInSemitones = double (initialNote) + totalPitchbendInSemitones;
|
||||
return frequencyOfA * std::pow (2.0, (pitchInSemitones - 69.0) / 12.0);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MPENote::operator== (const MPENote& other) const noexcept
|
||||
{
|
||||
jassert (isValid() && other.isValid());
|
||||
return noteID == other.noteID;
|
||||
}
|
||||
|
||||
bool MPENote::operator!= (const MPENote& other) const noexcept
|
||||
{
|
||||
jassert (isValid() && other.isValid());
|
||||
return noteID != other.noteID;
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class MPENoteTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MPENoteTests()
|
||||
: UnitTest ("MPENote class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
//==============================================================================
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("getFrequencyInHertz");
|
||||
{
|
||||
MPENote note;
|
||||
note.initialNote = 60;
|
||||
note.totalPitchbendInSemitones = -0.5;
|
||||
expectEqualsWithinOneCent (note.getFrequencyInHertz(), 254.178);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void expectEqualsWithinOneCent (double frequencyInHertzActual,
|
||||
double frequencyInHertzExpected)
|
||||
{
|
||||
double ratio = frequencyInHertzActual / frequencyInHertzExpected;
|
||||
double oneCent = 1.0005946;
|
||||
expect (ratio < oneCent);
|
||||
expect (ratio > 1.0 / oneCent);
|
||||
}
|
||||
};
|
||||
|
||||
static MPENoteTests MPENoteUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // 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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This struct represents a playing MPE note.
|
||||
|
||||
A note is identified by a unique ID, or alternatively, by a MIDI channel
|
||||
and an initial note. It is characterised by five dimensions of continuous
|
||||
expressive control. Their current values are represented as
|
||||
MPEValue objects.
|
||||
|
||||
@see MPEValue
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct JUCE_API MPENote
|
||||
{
|
||||
//==============================================================================
|
||||
/** Possible values for the note key state. */
|
||||
enum KeyState
|
||||
{
|
||||
off = 0, /**< The key is up (off). */
|
||||
keyDown = 1, /**< The note key is currently down (pressed). */
|
||||
sustained = 2, /**< The note is sustained (by a sustain or sostenuto pedal). */
|
||||
keyDownAndSustained = 3 /**< The note key is down and sustained (by a sustain or sostenuto pedal). */
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Constructor.
|
||||
|
||||
@param midiChannel The MIDI channel of the note, between 2 and 15.
|
||||
(Channel 1 and channel 16 can never be note channels in MPE).
|
||||
|
||||
@param initialNote The MIDI note number, between 0 and 127.
|
||||
|
||||
@param velocity The note-on velocity of the note.
|
||||
|
||||
@param pitchbend The initial per-note pitchbend of the note.
|
||||
|
||||
@param pressure The initial pressure of the note.
|
||||
|
||||
@param timbre The timbre value of the note.
|
||||
|
||||
@param keyState The key state of the note (whether the key is down
|
||||
and/or the note is sustained). This value must not
|
||||
be MPENote::off, since you are triggering a new note.
|
||||
(If not specified, the default value will be MPENote::keyDown.)
|
||||
*/
|
||||
MPENote (int midiChannel,
|
||||
int initialNote,
|
||||
MPEValue velocity,
|
||||
MPEValue pitchbend,
|
||||
MPEValue pressure,
|
||||
MPEValue timbre,
|
||||
KeyState keyState = MPENote::keyDown) noexcept;
|
||||
|
||||
/** Default constructor.
|
||||
|
||||
Constructs an invalid MPE note (a note with the key state MPENote::off
|
||||
and an invalid MIDI channel. The only allowed use for such a note is to
|
||||
call isValid() on it; everything else is undefined behaviour.
|
||||
*/
|
||||
MPENote() noexcept;
|
||||
|
||||
/** Checks whether the MPE note is valid. */
|
||||
bool isValid() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
// Invariants that define the note.
|
||||
|
||||
/** A unique ID. Useful to distinguish the note from other simultaneously
|
||||
sounding notes that may use the same note number or MIDI channel.
|
||||
This should never change during the lifetime of a note object.
|
||||
*/
|
||||
uint16 noteID = 0;
|
||||
|
||||
/** The MIDI channel which this note uses.
|
||||
This should never change during the lifetime of an MPENote object.
|
||||
*/
|
||||
uint8 midiChannel = 0;
|
||||
|
||||
/** The MIDI note number that was sent when the note was triggered.
|
||||
This should never change during the lifetime of an MPENote object.
|
||||
*/
|
||||
uint8 initialNote = 0;
|
||||
|
||||
//==============================================================================
|
||||
// The five dimensions of continuous expressive control
|
||||
|
||||
/** The velocity ("strike") of the note-on.
|
||||
This dimension will stay constant after the note has been turned on.
|
||||
*/
|
||||
MPEValue noteOnVelocity { MPEValue::minValue() };
|
||||
|
||||
/** Current per-note pitchbend of the note (in units of MIDI pitchwheel
|
||||
position). This dimension can be modulated while the note sounds.
|
||||
|
||||
Note: This value is not aware of the currently used pitchbend range,
|
||||
or an additional master pitchbend that may be simultaneously applied.
|
||||
To compute the actual effective pitchbend of an MPENote, you should
|
||||
probably use the member totalPitchbendInSemitones instead.
|
||||
|
||||
@see totalPitchbendInSemitones, getFrequencyInHertz
|
||||
*/
|
||||
MPEValue pitchbend { MPEValue::centreValue() };
|
||||
|
||||
/** Current pressure with which the note is held down.
|
||||
This dimension can be modulated while the note sounds.
|
||||
*/
|
||||
MPEValue pressure { MPEValue::centreValue() };
|
||||
|
||||
/** Initial value of timbre when the note was triggered.
|
||||
This should never change during the lifetime of an MPENote object.
|
||||
*/
|
||||
MPEValue initialTimbre { MPEValue::centreValue() };
|
||||
|
||||
/** Current value of the note's third expressive dimension, typically
|
||||
encoding some kind of timbre parameter.
|
||||
This dimension can be modulated while the note sounds.
|
||||
*/
|
||||
MPEValue timbre { MPEValue::centreValue() };
|
||||
|
||||
/** The release velocity ("lift") of the note after a note-off has been
|
||||
received.
|
||||
This dimension will only have a meaningful value after a note-off has
|
||||
been received for the note (and keyState is set to MPENote::off or
|
||||
MPENote::sustained). Initially, the value is undefined.
|
||||
*/
|
||||
MPEValue noteOffVelocity { MPEValue::minValue() };
|
||||
|
||||
//==============================================================================
|
||||
/** Current effective pitchbend of the note in units of semitones, relative
|
||||
to initialNote. You should use this to compute the actual effective pitch
|
||||
of the note. This value is computed and set by an MPEInstrument to the
|
||||
sum of the per-note pitchbend value (stored in MPEValue::pitchbend)
|
||||
and the master pitchbend of the MPE zone, weighted with the per-note
|
||||
pitchbend range and master pitchbend range of the zone, respectively.
|
||||
|
||||
@see getFrequencyInHertz
|
||||
*/
|
||||
double totalPitchbendInSemitones;
|
||||
|
||||
/** Current key state. Indicates whether the note key is currently down (pressed)
|
||||
and/or the note is sustained (by a sustain or sostenuto pedal).
|
||||
*/
|
||||
KeyState keyState { MPENote::off };
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the current frequency of the note in Hertz. This is the sum of
|
||||
the initialNote and the totalPitchbendInSemitones, converted to Hertz.
|
||||
*/
|
||||
double getFrequencyInHertz (double frequencyOfA = 440.0) const noexcept;
|
||||
|
||||
/** Returns true if two notes are the same, determined by their unique ID. */
|
||||
bool operator== (const MPENote& other) const noexcept;
|
||||
|
||||
/** Returns true if two notes are different notes, determined by their unique ID. */
|
||||
bool operator!= (const MPENote& other) const noexcept;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -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
|
||||
{
|
||||
|
||||
MPESynthesiser::MPESynthesiser()
|
||||
{
|
||||
}
|
||||
|
||||
MPESynthesiser::MPESynthesiser (MPEInstrument& mpeInstrument)
|
||||
: MPESynthesiserBase (mpeInstrument)
|
||||
{
|
||||
}
|
||||
|
||||
MPESynthesiser::~MPESynthesiser()
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiser::startVoice (MPESynthesiserVoice* voice, MPENote noteToStart)
|
||||
{
|
||||
jassert (voice != nullptr);
|
||||
|
||||
voice->currentlyPlayingNote = noteToStart;
|
||||
voice->noteOnTime = lastNoteOnCounter++;
|
||||
voice->noteStarted();
|
||||
}
|
||||
|
||||
void MPESynthesiser::stopVoice (MPESynthesiserVoice* voice, MPENote noteToStop, bool allowTailOff)
|
||||
{
|
||||
jassert (voice != nullptr);
|
||||
|
||||
voice->currentlyPlayingNote = noteToStop;
|
||||
voice->noteStopped (allowTailOff);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiser::noteAdded (MPENote newNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
if (auto* voice = findFreeVoice (newNote, shouldStealVoices))
|
||||
startVoice (voice, newNote);
|
||||
}
|
||||
|
||||
void MPESynthesiser::notePressureChanged (MPENote changedNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isCurrentlyPlayingNote (changedNote))
|
||||
{
|
||||
voice->currentlyPlayingNote = changedNote;
|
||||
voice->notePressureChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::notePitchbendChanged (MPENote changedNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isCurrentlyPlayingNote (changedNote))
|
||||
{
|
||||
voice->currentlyPlayingNote = changedNote;
|
||||
voice->notePitchbendChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::noteTimbreChanged (MPENote changedNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isCurrentlyPlayingNote (changedNote))
|
||||
{
|
||||
voice->currentlyPlayingNote = changedNote;
|
||||
voice->noteTimbreChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::noteKeyStateChanged (MPENote changedNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isCurrentlyPlayingNote (changedNote))
|
||||
{
|
||||
voice->currentlyPlayingNote = changedNote;
|
||||
voice->noteKeyStateChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::noteReleased (MPENote finishedNote)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto i = voices.size(); --i >= 0;)
|
||||
{
|
||||
auto* voice = voices.getUnchecked (i);
|
||||
|
||||
if (voice->isCurrentlyPlayingNote (finishedNote))
|
||||
stopVoice (voice, finishedNote, true);
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::setCurrentPlaybackSampleRate (const double newRate)
|
||||
{
|
||||
MPESynthesiserBase::setCurrentPlaybackSampleRate (newRate);
|
||||
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
turnOffAllVoices (false);
|
||||
|
||||
for (auto i = voices.size(); --i >= 0;)
|
||||
voices.getUnchecked (i)->setCurrentSampleRate (newRate);
|
||||
}
|
||||
|
||||
void MPESynthesiser::handleMidiEvent (const MidiMessage& m)
|
||||
{
|
||||
if (m.isController())
|
||||
handleController (m.getChannel(), m.getControllerNumber(), m.getControllerValue());
|
||||
else if (m.isProgramChange())
|
||||
handleProgramChange (m.getChannel(), m.getProgramChangeNumber());
|
||||
|
||||
MPESynthesiserBase::handleMidiEvent (m);
|
||||
}
|
||||
|
||||
MPESynthesiserVoice* MPESynthesiser::findFreeVoice (MPENote noteToFindVoiceFor, bool stealIfNoneAvailable) const
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (! voice->isActive())
|
||||
return voice;
|
||||
}
|
||||
|
||||
if (stealIfNoneAvailable)
|
||||
return findVoiceToSteal (noteToFindVoiceFor);
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
MPESynthesiserVoice* MPESynthesiser::findVoiceToSteal (MPENote noteToStealVoiceFor) const
|
||||
{
|
||||
// This voice-stealing algorithm applies the following heuristics:
|
||||
// - Re-use the oldest notes first
|
||||
// - Protect the lowest & topmost notes, even if sustained, but not if they've been released.
|
||||
|
||||
|
||||
// apparently you are trying to render audio without having any voices...
|
||||
jassert (voices.size() > 0);
|
||||
|
||||
// These are the voices we want to protect (ie: only steal if unavoidable)
|
||||
MPESynthesiserVoice* low = nullptr; // Lowest sounding note, might be sustained, but NOT in release phase
|
||||
MPESynthesiserVoice* top = nullptr; // Highest sounding note, might be sustained, but NOT in release phase
|
||||
|
||||
// All major OSes use double-locking so this will be lock- and wait-free as long as stealLock is not
|
||||
// contended. This is always the case if you do not call findVoiceToSteal on multiple threads at
|
||||
// the same time.
|
||||
const ScopedLock sl (stealLock);
|
||||
|
||||
// this is a list of voices we can steal, sorted by how long they've been running
|
||||
usableVoicesToStealArray.clear();
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
jassert (voice->isActive()); // We wouldn't be here otherwise
|
||||
|
||||
usableVoicesToStealArray.add (voice);
|
||||
|
||||
// NB: Using a functor rather than a lambda here due to scare-stories about
|
||||
// compilers generating code containing heap allocations.
|
||||
struct Sorter
|
||||
{
|
||||
bool operator() (const MPESynthesiserVoice* a, const MPESynthesiserVoice* b) const noexcept { return a->noteOnTime < b->noteOnTime; }
|
||||
};
|
||||
|
||||
std::sort (usableVoicesToStealArray.begin(), usableVoicesToStealArray.end(), Sorter());
|
||||
|
||||
if (! voice->isPlayingButReleased()) // Don't protect released notes
|
||||
{
|
||||
auto noteNumber = voice->getCurrentlyPlayingNote().initialNote;
|
||||
|
||||
if (low == nullptr || noteNumber < low->getCurrentlyPlayingNote().initialNote)
|
||||
low = voice;
|
||||
|
||||
if (top == nullptr || noteNumber > top->getCurrentlyPlayingNote().initialNote)
|
||||
top = voice;
|
||||
}
|
||||
}
|
||||
|
||||
// Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s)
|
||||
if (top == low)
|
||||
top = nullptr;
|
||||
|
||||
// If we want to re-use the voice to trigger a new note,
|
||||
// then The oldest note that's playing the same note number is ideal.
|
||||
if (noteToStealVoiceFor.isValid())
|
||||
for (auto* voice : usableVoicesToStealArray)
|
||||
if (voice->getCurrentlyPlayingNote().initialNote == noteToStealVoiceFor.initialNote)
|
||||
return voice;
|
||||
|
||||
// Oldest voice that has been released (no finger on it and not held by sustain pedal)
|
||||
for (auto* voice : usableVoicesToStealArray)
|
||||
if (voice != low && voice != top && voice->isPlayingButReleased())
|
||||
return voice;
|
||||
|
||||
// Oldest voice that doesn't have a finger on it:
|
||||
for (auto* voice : usableVoicesToStealArray)
|
||||
if (voice != low && voice != top
|
||||
&& voice->getCurrentlyPlayingNote().keyState != MPENote::keyDown
|
||||
&& voice->getCurrentlyPlayingNote().keyState != MPENote::keyDownAndSustained)
|
||||
return voice;
|
||||
|
||||
// Oldest voice that isn't protected
|
||||
for (auto* voice : usableVoicesToStealArray)
|
||||
if (voice != low && voice != top)
|
||||
return voice;
|
||||
|
||||
// We've only got "protected" voices now: lowest note takes priority
|
||||
jassert (low != nullptr);
|
||||
|
||||
// Duophonic synth: give priority to the bass note:
|
||||
if (top != nullptr)
|
||||
return top;
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiser::addVoice (MPESynthesiserVoice* const newVoice)
|
||||
{
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
newVoice->setCurrentSampleRate (getSampleRate());
|
||||
voices.add (newVoice);
|
||||
}
|
||||
|
||||
{
|
||||
const ScopedLock sl (stealLock);
|
||||
usableVoicesToStealArray.ensureStorageAllocated (voices.size() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::clearVoices()
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
voices.clear();
|
||||
}
|
||||
|
||||
MPESynthesiserVoice* MPESynthesiser::getVoice (const int index) const
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
return voices [index];
|
||||
}
|
||||
|
||||
void MPESynthesiser::removeVoice (const int index)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
voices.remove (index);
|
||||
}
|
||||
|
||||
void MPESynthesiser::reduceNumVoices (const int newNumVoices)
|
||||
{
|
||||
// we can't possibly get to a negative number of voices...
|
||||
jassert (newNumVoices >= 0);
|
||||
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
while (voices.size() > newNumVoices)
|
||||
{
|
||||
if (auto* voice = findFreeVoice ({}, true))
|
||||
voices.removeObject (voice);
|
||||
else
|
||||
voices.remove (0); // if there's no voice to steal, kill the oldest voice
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::turnOffAllVoices (bool allowTailOff)
|
||||
{
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
// first turn off all voices (it's more efficient to do this immediately
|
||||
// rather than to go through the MPEInstrument for this).
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
voice->currentlyPlayingNote.noteOffVelocity = MPEValue::from7BitInt (64); // some reasonable number
|
||||
voice->currentlyPlayingNote.keyState = MPENote::off;
|
||||
|
||||
voice->noteStopped (allowTailOff);
|
||||
}
|
||||
}
|
||||
|
||||
// finally make sure the MPE Instrument also doesn't have any notes anymore
|
||||
instrument.releaseAllNotes();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiser::renderNextSubBlock (AudioBuffer<float>& buffer, int startSample, int numSamples)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isActive())
|
||||
voice->renderNextBlock (buffer, startSample, numSamples);
|
||||
}
|
||||
}
|
||||
|
||||
void MPESynthesiser::renderNextSubBlock (AudioBuffer<double>& buffer, int startSample, int numSamples)
|
||||
{
|
||||
const ScopedLock sl (voicesLock);
|
||||
|
||||
for (auto* voice : voices)
|
||||
{
|
||||
if (voice->isActive())
|
||||
voice->renderNextBlock (buffer, startSample, numSamples);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,325 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Base class for an MPE-compatible musical device that can play sounds.
|
||||
|
||||
This class extends MPESynthesiserBase by adding the concept of voices,
|
||||
each of which can play a sound triggered by a MPENote that can be modulated
|
||||
by MPE dimensions like pressure, pitchbend, and timbre, while the note is
|
||||
sounding.
|
||||
|
||||
To create a synthesiser, you'll need to create a subclass of MPESynthesiserVoice
|
||||
which can play back one of these sounds at a time.
|
||||
|
||||
Then you can use the addVoice() methods to give the synthesiser a set of voices
|
||||
it can use to play notes. If you only give it one voice it will be monophonic -
|
||||
the more voices it has, the more polyphony it'll have available.
|
||||
|
||||
Then repeatedly call the renderNextBlock() method to produce the audio (inherited
|
||||
from MPESynthesiserBase). The voices will be started, stopped, and modulated
|
||||
automatically, based on the MPE/MIDI messages that the synthesiser receives.
|
||||
|
||||
Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
|
||||
what the target playback rate is. This value is passed on to the voices so that
|
||||
they can pitch their output correctly.
|
||||
|
||||
@see MPESynthesiserBase, MPESynthesiserVoice, MPENote, MPEInstrument
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPESynthesiser : public MPESynthesiserBase
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Constructor.
|
||||
You'll need to add some voices before it'll make any sound.
|
||||
|
||||
@see addVoice
|
||||
*/
|
||||
MPESynthesiser();
|
||||
|
||||
/** Constructor to pass to the synthesiser a custom MPEInstrument object
|
||||
to handle the MPE note state, MIDI channel assignment etc.
|
||||
(in case you need custom logic for this that goes beyond MIDI and MPE).
|
||||
|
||||
@see MPESynthesiserBase, MPEInstrument
|
||||
*/
|
||||
MPESynthesiser (MPEInstrument& instrumentToUse);
|
||||
|
||||
/** Destructor. */
|
||||
~MPESynthesiser() override;
|
||||
|
||||
//==============================================================================
|
||||
/** Deletes all voices. */
|
||||
void clearVoices();
|
||||
|
||||
/** Returns the number of voices that have been added. */
|
||||
int getNumVoices() const noexcept { return voices.size(); }
|
||||
|
||||
/** Returns one of the voices that have been added. */
|
||||
MPESynthesiserVoice* getVoice (int index) const;
|
||||
|
||||
/** Adds a new voice to the synth.
|
||||
|
||||
All the voices should be the same class of object and are treated equally.
|
||||
|
||||
The object passed in will be managed by the synthesiser, which will delete
|
||||
it later on when no longer needed. The caller should not retain a pointer to the
|
||||
voice.
|
||||
*/
|
||||
void addVoice (MPESynthesiserVoice* newVoice);
|
||||
|
||||
/** Deletes one of the voices. */
|
||||
void removeVoice (int index);
|
||||
|
||||
/** Reduces the number of voices to newNumVoices.
|
||||
|
||||
This will repeatedly call findVoiceToSteal() and remove that voice, until
|
||||
the total number of voices equals newNumVoices. If newNumVoices is greater than
|
||||
or equal to the current number of voices, this method does nothing.
|
||||
*/
|
||||
void reduceNumVoices (int newNumVoices);
|
||||
|
||||
/** Release all MPE notes and turn off all voices.
|
||||
|
||||
If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
|
||||
(if they can do). If this is false, the notes will all be cut off immediately.
|
||||
|
||||
This method is meant to be called by the user, for example to implement
|
||||
a MIDI panic button in a synth.
|
||||
*/
|
||||
virtual void turnOffAllVoices (bool allowTailOff);
|
||||
|
||||
//==============================================================================
|
||||
/** If set to true, then the synth will try to take over an existing voice if
|
||||
it runs out and needs to play another note.
|
||||
|
||||
The value of this boolean is passed into findFreeVoice(), so the result will
|
||||
depend on the implementation of this method.
|
||||
*/
|
||||
void setVoiceStealingEnabled (bool shouldSteal) noexcept { shouldStealVoices = shouldSteal; }
|
||||
|
||||
/** Returns true if note-stealing is enabled. */
|
||||
bool isVoiceStealingEnabled() const noexcept { return shouldStealVoices; }
|
||||
|
||||
//==============================================================================
|
||||
/** Tells the synthesiser what the sample rate is for the audio it's being used to render.
|
||||
|
||||
This overrides the implementation in MPESynthesiserBase, to additionally
|
||||
propagate the new value to the voices so that they can use it to render the correct
|
||||
pitches.
|
||||
*/
|
||||
void setCurrentPlaybackSampleRate (double newRate) override;
|
||||
|
||||
//==============================================================================
|
||||
/** Handle incoming MIDI events.
|
||||
|
||||
This method will be called automatically according to the MIDI data passed
|
||||
into renderNextBlock(), but you can also call it yourself to manually
|
||||
inject MIDI events.
|
||||
|
||||
This implementation forwards program change messages and non-MPE-related
|
||||
controller messages to handleProgramChange and handleController, respectively,
|
||||
and then simply calls through to MPESynthesiserBase::handleMidiEvent to deal
|
||||
with MPE-related MIDI messages used for MPE notes, zones etc.
|
||||
|
||||
This method can be overridden further if you need to do custom MIDI
|
||||
handling on top of what is provided here.
|
||||
*/
|
||||
void handleMidiEvent (const MidiMessage&) override;
|
||||
|
||||
/** Callback for MIDI controller messages. The default implementation
|
||||
provided here does nothing; override this method if you need custom
|
||||
MIDI controller handling on top of MPE.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock().
|
||||
*/
|
||||
virtual void handleController (int /*midiChannel*/,
|
||||
int /*controllerNumber*/,
|
||||
int /*controllerValue*/) {}
|
||||
|
||||
/** Callback for MIDI program change messages. The default implementation
|
||||
provided here does nothing; override this method if you need to handle
|
||||
those messages.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock().
|
||||
*/
|
||||
virtual void handleProgramChange (int /*midiChannel*/,
|
||||
int /*programNumber*/) {}
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/** Attempts to start playing a new note.
|
||||
|
||||
The default method here will find a free voice that is appropriate for
|
||||
playing the given MPENote, and use that voice to start playing the sound.
|
||||
If isNoteStealingEnabled returns true (set this by calling setNoteStealingEnabled),
|
||||
the synthesiser will use the voice stealing algorithm to find a free voice for
|
||||
the note (if no voices are free otherwise).
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself, otherwise the internal MPE note state
|
||||
will become inconsistent.
|
||||
*/
|
||||
void noteAdded (MPENote newNote) override;
|
||||
|
||||
/** Stops playing a note.
|
||||
|
||||
This will be called whenever an MPE note is released (either by a note-off message,
|
||||
or by a sustain/sostenuto pedal release for a note that already received a note-off),
|
||||
and should therefore stop playing.
|
||||
|
||||
This will find any voice that is currently playing finishedNote,
|
||||
turn its currently playing note off, and call its noteStopped callback.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself, otherwise the internal MPE note state
|
||||
will become inconsistent.
|
||||
*/
|
||||
void noteReleased (MPENote finishedNote) override;
|
||||
|
||||
/** Will find any voice that is currently playing changedNote, update its
|
||||
currently playing note, and call its notePressureChanged method.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself.
|
||||
*/
|
||||
void notePressureChanged (MPENote changedNote) override;
|
||||
|
||||
/** Will find any voice that is currently playing changedNote, update its
|
||||
currently playing note, and call its notePitchbendChanged method.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself.
|
||||
*/
|
||||
void notePitchbendChanged (MPENote changedNote) override;
|
||||
|
||||
/** Will find any voice that is currently playing changedNote, update its
|
||||
currently playing note, and call its noteTimbreChanged method.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself.
|
||||
*/
|
||||
void noteTimbreChanged (MPENote changedNote) override;
|
||||
|
||||
/** Will find any voice that is currently playing changedNote, update its
|
||||
currently playing note, and call its noteKeyStateChanged method.
|
||||
|
||||
This method will be called automatically according to the midi data passed into
|
||||
renderNextBlock(). Do not call it yourself.
|
||||
*/
|
||||
void noteKeyStateChanged (MPENote changedNote) override;
|
||||
|
||||
//==============================================================================
|
||||
/** This will simply call renderNextBlock for each currently active
|
||||
voice and fill the buffer with the sum.
|
||||
Override this method if you need to do more work to render your audio.
|
||||
*/
|
||||
void renderNextSubBlock (AudioBuffer<float>& outputAudio,
|
||||
int startSample,
|
||||
int numSamples) override;
|
||||
|
||||
/** This will simply call renderNextBlock for each currently active
|
||||
voice and fill the buffer with the sum. (double-precision version)
|
||||
Override this method if you need to do more work to render your audio.
|
||||
*/
|
||||
void renderNextSubBlock (AudioBuffer<double>& outputAudio,
|
||||
int startSample,
|
||||
int numSamples) override;
|
||||
|
||||
//==============================================================================
|
||||
/** Searches through the voices to find one that's not currently playing, and
|
||||
which can play the given MPE note.
|
||||
|
||||
If all voices are active and stealIfNoneAvailable is false, this returns
|
||||
a nullptr. If all voices are active and stealIfNoneAvailable is true,
|
||||
this will call findVoiceToSteal() to find a voice.
|
||||
|
||||
If you need to find a free voice for something else than playing a note
|
||||
(e.g. for deleting it), you can pass an invalid (default-constructed) MPENote.
|
||||
*/
|
||||
virtual MPESynthesiserVoice* findFreeVoice (MPENote noteToFindVoiceFor,
|
||||
bool stealIfNoneAvailable) const;
|
||||
|
||||
/** Chooses a voice that is most suitable for being re-used to play a new
|
||||
note, or for being deleted by reduceNumVoices.
|
||||
|
||||
The default method will attempt to find the oldest voice that isn't the
|
||||
bottom or top note being played. If that's not suitable for your synth,
|
||||
you can override this method and do something more cunning instead.
|
||||
|
||||
If you pass a valid MPENote for the optional argument, then the note number
|
||||
of that note will be taken into account for finding the ideal voice to steal.
|
||||
If you pass an invalid (default-constructed) MPENote instead, this part of
|
||||
the algorithm will be ignored.
|
||||
*/
|
||||
virtual MPESynthesiserVoice* findVoiceToSteal (MPENote noteToStealVoiceFor = MPENote()) const;
|
||||
|
||||
/** Starts a specified voice and tells it to play a particular MPENote.
|
||||
You should never need to call this, it's called internally by
|
||||
MPESynthesiserBase::instrument via the noteStarted callback,
|
||||
but is protected in case it's useful for some custom subclasses.
|
||||
*/
|
||||
void startVoice (MPESynthesiserVoice* voice, MPENote noteToStart);
|
||||
|
||||
/** Stops a given voice and tells it to stop playing a particular MPENote
|
||||
(which should be the same note it is actually playing).
|
||||
You should never need to call this, it's called internally by
|
||||
MPESynthesiserBase::instrument via the noteReleased callback,
|
||||
but is protected in case it's useful for some custom subclasses.
|
||||
*/
|
||||
void stopVoice (MPESynthesiserVoice* voice, MPENote noteToStop, bool allowTailOff);
|
||||
|
||||
//==============================================================================
|
||||
OwnedArray<MPESynthesiserVoice> voices;
|
||||
CriticalSection voicesLock;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
std::atomic<bool> shouldStealVoices { false };
|
||||
uint32 lastNoteOnCounter = 0;
|
||||
mutable CriticalSection stealLock;
|
||||
mutable Array<MPESynthesiserVoice*> usableVoicesToStealArray;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESynthesiser)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,387 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MPESynthesiserBase::MPESynthesiserBase()
|
||||
: instrument (defaultInstrument)
|
||||
{
|
||||
instrument.addListener (this);
|
||||
}
|
||||
|
||||
MPESynthesiserBase::MPESynthesiserBase (MPEInstrument& inst)
|
||||
: instrument (inst)
|
||||
{
|
||||
instrument.addListener (this);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MPEZoneLayout MPESynthesiserBase::getZoneLayout() const noexcept
|
||||
{
|
||||
return instrument.getZoneLayout();
|
||||
}
|
||||
|
||||
void MPESynthesiserBase::setZoneLayout (MPEZoneLayout newLayout)
|
||||
{
|
||||
instrument.setZoneLayout (newLayout);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiserBase::enableLegacyMode (int pitchbendRange, Range<int> channelRange)
|
||||
{
|
||||
instrument.enableLegacyMode (pitchbendRange, channelRange);
|
||||
}
|
||||
|
||||
bool MPESynthesiserBase::isLegacyModeEnabled() const noexcept
|
||||
{
|
||||
return instrument.isLegacyModeEnabled();
|
||||
}
|
||||
|
||||
Range<int> MPESynthesiserBase::getLegacyModeChannelRange() const noexcept
|
||||
{
|
||||
return instrument.getLegacyModeChannelRange();
|
||||
}
|
||||
|
||||
void MPESynthesiserBase::setLegacyModeChannelRange (Range<int> channelRange)
|
||||
{
|
||||
instrument.setLegacyModeChannelRange (channelRange);
|
||||
}
|
||||
|
||||
int MPESynthesiserBase::getLegacyModePitchbendRange() const noexcept
|
||||
{
|
||||
return instrument.getLegacyModePitchbendRange();
|
||||
}
|
||||
|
||||
void MPESynthesiserBase::setLegacyModePitchbendRange (int pitchbendRange)
|
||||
{
|
||||
instrument.setLegacyModePitchbendRange (pitchbendRange);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiserBase::setPressureTrackingMode (TrackingMode modeToUse)
|
||||
{
|
||||
instrument.setPressureTrackingMode (modeToUse);
|
||||
}
|
||||
|
||||
void MPESynthesiserBase::setPitchbendTrackingMode (TrackingMode modeToUse)
|
||||
{
|
||||
instrument.setPitchbendTrackingMode (modeToUse);
|
||||
}
|
||||
|
||||
void MPESynthesiserBase::setTimbreTrackingMode (TrackingMode modeToUse)
|
||||
{
|
||||
instrument.setTimbreTrackingMode (modeToUse);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiserBase::handleMidiEvent (const MidiMessage& m)
|
||||
{
|
||||
instrument.processNextMidiEvent (m);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename floatType>
|
||||
void MPESynthesiserBase::renderNextBlock (AudioBuffer<floatType>& outputAudio,
|
||||
const MidiBuffer& inputMidi,
|
||||
int startSample,
|
||||
int numSamples)
|
||||
{
|
||||
// you must set the sample rate before using this!
|
||||
jassert (! approximatelyEqual (sampleRate, 0.0));
|
||||
|
||||
const ScopedLock sl (noteStateLock);
|
||||
|
||||
auto prevSample = startSample;
|
||||
const auto endSample = startSample + numSamples;
|
||||
|
||||
for (auto it = inputMidi.findNextSamplePosition (startSample); it != inputMidi.cend(); ++it)
|
||||
{
|
||||
const auto metadata = *it;
|
||||
|
||||
if (metadata.samplePosition >= endSample)
|
||||
break;
|
||||
|
||||
const auto smallBlockAllowed = (prevSample == startSample && ! subBlockSubdivisionIsStrict);
|
||||
const auto thisBlockSize = smallBlockAllowed ? 1 : minimumSubBlockSize;
|
||||
|
||||
if (metadata.samplePosition >= prevSample + thisBlockSize)
|
||||
{
|
||||
renderNextSubBlock (outputAudio, prevSample, metadata.samplePosition - prevSample);
|
||||
prevSample = metadata.samplePosition;
|
||||
}
|
||||
|
||||
handleMidiEvent (metadata.getMessage());
|
||||
}
|
||||
|
||||
if (prevSample < endSample)
|
||||
renderNextSubBlock (outputAudio, prevSample, endSample - prevSample);
|
||||
}
|
||||
|
||||
// explicit instantiation for supported float types:
|
||||
template void MPESynthesiserBase::renderNextBlock<float> (AudioBuffer<float>&, const MidiBuffer&, int, int);
|
||||
template void MPESynthesiserBase::renderNextBlock<double> (AudioBuffer<double>&, const MidiBuffer&, int, int);
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiserBase::setCurrentPlaybackSampleRate (const double newRate)
|
||||
{
|
||||
if (! approximatelyEqual (sampleRate, newRate))
|
||||
{
|
||||
const ScopedLock sl (noteStateLock);
|
||||
instrument.releaseAllNotes();
|
||||
sampleRate = newRate;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPESynthesiserBase::setMinimumRenderingSubdivisionSize (int numSamples, bool shouldBeStrict) noexcept
|
||||
{
|
||||
jassert (numSamples > 0); // it wouldn't make much sense for this to be less than 1
|
||||
minimumSubBlockSize = numSamples;
|
||||
subBlockSubdivisionIsStrict = shouldBeStrict;
|
||||
}
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
namespace
|
||||
{
|
||||
class MpeSynthesiserBaseTests final : public UnitTest
|
||||
{
|
||||
enum class CallbackKind { process, midi };
|
||||
|
||||
struct StartAndLength
|
||||
{
|
||||
StartAndLength (int s, int l) : start (s), length (l) {}
|
||||
|
||||
int start = 0;
|
||||
int length = 0;
|
||||
|
||||
std::tuple<const int&, const int&> tie() const noexcept { return std::tie (start, length); }
|
||||
|
||||
bool operator== (const StartAndLength& other) const noexcept { return tie() == other.tie(); }
|
||||
bool operator!= (const StartAndLength& other) const noexcept { return tie() != other.tie(); }
|
||||
|
||||
bool operator< (const StartAndLength& other) const noexcept { return tie() < other.tie(); }
|
||||
};
|
||||
|
||||
struct Events
|
||||
{
|
||||
std::vector<StartAndLength> blocks;
|
||||
std::vector<MidiMessage> messages;
|
||||
std::vector<CallbackKind> order;
|
||||
};
|
||||
|
||||
class MockSynthesiser final : public MPESynthesiserBase
|
||||
{
|
||||
public:
|
||||
Events events;
|
||||
|
||||
void handleMidiEvent (const MidiMessage& m) override
|
||||
{
|
||||
events.messages.emplace_back (m);
|
||||
events.order.emplace_back (CallbackKind::midi);
|
||||
}
|
||||
|
||||
private:
|
||||
using MPESynthesiserBase::renderNextSubBlock;
|
||||
|
||||
void renderNextSubBlock (AudioBuffer<float>&,
|
||||
int startSample,
|
||||
int numSamples) override
|
||||
{
|
||||
events.blocks.push_back ({ startSample, numSamples });
|
||||
events.order.emplace_back (CallbackKind::process);
|
||||
}
|
||||
};
|
||||
|
||||
static MidiBuffer makeTestBuffer (const int bufferLength)
|
||||
{
|
||||
MidiBuffer result;
|
||||
|
||||
for (int i = 0; i != bufferLength; ++i)
|
||||
result.addEvent ({}, i);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public:
|
||||
MpeSynthesiserBaseTests()
|
||||
: UnitTest ("MPE Synthesiser Base", UnitTestCategories::midi) {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
const auto sumBlockLengths = [] (const std::vector<StartAndLength>& b)
|
||||
{
|
||||
const auto addBlock = [] (int acc, const StartAndLength& info) { return acc + info.length; };
|
||||
return std::accumulate (b.begin(), b.end(), 0, addBlock);
|
||||
};
|
||||
|
||||
beginTest ("Rendering sparse subblocks works");
|
||||
{
|
||||
const int blockSize = 512;
|
||||
const auto midi = [&] { MidiBuffer b; b.addEvent ({}, blockSize / 2); return b; }();
|
||||
AudioBuffer<float> audio (1, blockSize);
|
||||
|
||||
const auto processEvents = [&] (int start, int length)
|
||||
{
|
||||
MockSynthesiser synth;
|
||||
synth.setMinimumRenderingSubdivisionSize (1, false);
|
||||
synth.setCurrentPlaybackSampleRate (44100);
|
||||
synth.renderNextBlock (audio, midi, start, length);
|
||||
return synth.events;
|
||||
};
|
||||
|
||||
{
|
||||
const auto e = processEvents (0, blockSize);
|
||||
expect (e.blocks.size() == 2);
|
||||
expect (e.messages.size() == 1);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == blockSize);
|
||||
expect (e.order == std::vector<CallbackKind> { CallbackKind::process,
|
||||
CallbackKind::midi,
|
||||
CallbackKind::process });
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Rendering subblocks processes only contained midi events");
|
||||
{
|
||||
const int blockSize = 512;
|
||||
const auto midi = makeTestBuffer (blockSize);
|
||||
AudioBuffer<float> audio (1, blockSize);
|
||||
|
||||
const auto processEvents = [&] (int start, int length)
|
||||
{
|
||||
MockSynthesiser synth;
|
||||
synth.setMinimumRenderingSubdivisionSize (1, false);
|
||||
synth.setCurrentPlaybackSampleRate (44100);
|
||||
synth.renderNextBlock (audio, midi, start, length);
|
||||
return synth.events;
|
||||
};
|
||||
|
||||
{
|
||||
const int subBlockLength = 0;
|
||||
const auto e = processEvents (0, subBlockLength);
|
||||
expect (e.blocks.size() == 0);
|
||||
expect (e.messages.size() == 0);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == subBlockLength);
|
||||
}
|
||||
|
||||
{
|
||||
const int subBlockLength = 0;
|
||||
const auto e = processEvents (1, subBlockLength);
|
||||
expect (e.blocks.size() == 0);
|
||||
expect (e.messages.size() == 0);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == subBlockLength);
|
||||
}
|
||||
|
||||
{
|
||||
const int subBlockLength = 1;
|
||||
const auto e = processEvents (1, subBlockLength);
|
||||
expect (e.blocks.size() == 1);
|
||||
expect (e.messages.size() == 1);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == subBlockLength);
|
||||
expect (e.order == std::vector<CallbackKind> { CallbackKind::midi,
|
||||
CallbackKind::process });
|
||||
}
|
||||
|
||||
{
|
||||
const auto e = processEvents (0, blockSize);
|
||||
expect (e.blocks.size() == blockSize);
|
||||
expect (e.messages.size() == blockSize);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == blockSize);
|
||||
expect (e.order.front() == CallbackKind::midi);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Subblocks respect their minimum size");
|
||||
{
|
||||
const int blockSize = 512;
|
||||
const auto midi = makeTestBuffer (blockSize);
|
||||
AudioBuffer<float> audio (1, blockSize);
|
||||
|
||||
const auto blockLengthsAreValid = [] (const std::vector<StartAndLength>& info, int minLength, bool strict)
|
||||
{
|
||||
if (info.size() <= 1)
|
||||
return true;
|
||||
|
||||
const auto lengthIsValid = [&] (const StartAndLength& s) { return minLength <= s.length; };
|
||||
const auto begin = strict ? info.begin() : std::next (info.begin());
|
||||
// The final block is allowed to be shorter than the minLength
|
||||
return std::all_of (begin, std::prev (info.end()), lengthIsValid);
|
||||
};
|
||||
|
||||
for (auto strict : { false, true })
|
||||
{
|
||||
for (auto subblockSize : { 1, 16, 32, 64, 1024 })
|
||||
{
|
||||
MockSynthesiser synth;
|
||||
synth.setMinimumRenderingSubdivisionSize (subblockSize, strict);
|
||||
synth.setCurrentPlaybackSampleRate (44100);
|
||||
synth.renderNextBlock (audio, midi, 0, blockSize);
|
||||
|
||||
const auto& e = synth.events;
|
||||
expectWithinAbsoluteError (float (e.blocks.size()),
|
||||
std::ceil ((float) blockSize / (float) subblockSize),
|
||||
1.0f);
|
||||
expect (e.messages.size() == blockSize);
|
||||
expect (std::is_sorted (e.blocks.begin(), e.blocks.end()));
|
||||
expect (sumBlockLengths (e.blocks) == blockSize);
|
||||
expect (blockLengthsAreValid (e.blocks, subblockSize, strict));
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
MockSynthesiser synth;
|
||||
synth.setMinimumRenderingSubdivisionSize (32, true);
|
||||
synth.setCurrentPlaybackSampleRate (44100);
|
||||
synth.renderNextBlock (audio, MidiBuffer{}, 0, 16);
|
||||
|
||||
expect (synth.events.blocks == std::vector<StartAndLength> { { 0, 16 } });
|
||||
expect (synth.events.order == std::vector<CallbackKind> { CallbackKind::process });
|
||||
expect (synth.events.messages.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
MpeSynthesiserBaseTests mpeSynthesiserBaseTests;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Derive from this class to create a basic audio generator capable of MPE.
|
||||
Implement the callbacks of MPEInstrument::Listener (noteAdded, notePressureChanged
|
||||
etc.) to let your audio generator know that MPE notes were triggered, modulated,
|
||||
or released. What to do inside them, and how that influences your audio generator,
|
||||
is up to you!
|
||||
|
||||
This class uses an instance of MPEInstrument internally to handle the MPE
|
||||
note state logic.
|
||||
|
||||
This class is a very low-level base class for an MPE instrument. If you need
|
||||
something more sophisticated, have a look at MPESynthesiser. This class extends
|
||||
MPESynthesiserBase by adding the concept of voices that can play notes,
|
||||
a voice stealing algorithm, and much more.
|
||||
|
||||
@see MPESynthesiser, MPEInstrument
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct JUCE_API MPESynthesiserBase : public MPEInstrument::Listener
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Constructor. */
|
||||
MPESynthesiserBase();
|
||||
|
||||
/** Constructor.
|
||||
|
||||
If you use this constructor, the synthesiser will use the provided instrument
|
||||
object to handle the MPE note state logic.
|
||||
This is useful if you want to use an instance of your own class derived
|
||||
from MPEInstrument for the MPE logic.
|
||||
*/
|
||||
MPESynthesiserBase (MPEInstrument& instrument);
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the synthesiser's internal MPE zone layout.
|
||||
This happens by value, to enforce thread-safety and class invariants.
|
||||
*/
|
||||
MPEZoneLayout getZoneLayout() const noexcept;
|
||||
|
||||
/** Re-sets the synthesiser's internal MPE zone layout to the one passed in.
|
||||
As a side effect, this will discard all currently playing notes,
|
||||
call noteReleased for all of them, and disable legacy mode (if previously enabled).
|
||||
*/
|
||||
void setZoneLayout (MPEZoneLayout newLayout);
|
||||
|
||||
//==============================================================================
|
||||
/** Tells the synthesiser what the sample rate is for the audio it's being
|
||||
used to render.
|
||||
*/
|
||||
virtual void setCurrentPlaybackSampleRate (double sampleRate);
|
||||
|
||||
/** Returns the current target sample rate at which rendering is being done.
|
||||
Subclasses may need to know this so that they can pitch things correctly.
|
||||
*/
|
||||
double getSampleRate() const noexcept { return sampleRate; }
|
||||
|
||||
//==============================================================================
|
||||
/** Creates the next block of audio output.
|
||||
|
||||
Call this to make sound. This will chop up the AudioBuffer into subBlock
|
||||
pieces separated by events in the MIDI buffer, and then call
|
||||
renderNextSubBlock on each one of them. In between you will get calls
|
||||
to noteAdded/Changed/Finished, where you can update parameters that
|
||||
depend on those notes to use for your audio rendering.
|
||||
|
||||
@param outputAudio Buffer into which audio will be rendered
|
||||
@param inputMidi MIDI events to process
|
||||
@param startSample The first sample to process in both buffers
|
||||
@param numSamples The number of samples to process
|
||||
*/
|
||||
template <typename floatType>
|
||||
void renderNextBlock (AudioBuffer<floatType>& outputAudio,
|
||||
const MidiBuffer& inputMidi,
|
||||
int startSample,
|
||||
int numSamples);
|
||||
|
||||
//==============================================================================
|
||||
/** Handle incoming MIDI events (called from renderNextBlock).
|
||||
|
||||
The default implementation provided here simply forwards everything
|
||||
to MPEInstrument::processNextMidiEvent, where it is used to update the
|
||||
MPE notes, zones etc. MIDI messages not relevant for MPE are ignored.
|
||||
|
||||
This method can be overridden if you need to do custom MIDI handling
|
||||
on top of MPE. The MPESynthesiser class overrides this to implement
|
||||
callbacks for MIDI program changes and non-MPE-related MIDI controller
|
||||
messages.
|
||||
*/
|
||||
virtual void handleMidiEvent (const MidiMessage&);
|
||||
|
||||
//==============================================================================
|
||||
/** Sets a minimum limit on the size to which audio sub-blocks will be divided when rendering.
|
||||
|
||||
When rendering, the audio blocks that are passed into renderNextBlock() will be split up
|
||||
into smaller blocks that lie between all the incoming midi messages, and it is these smaller
|
||||
sub-blocks that are rendered with multiple calls to renderVoices().
|
||||
|
||||
Obviously in a pathological case where there are midi messages on every sample, then
|
||||
renderVoices() could be called once per sample and lead to poor performance, so this
|
||||
setting allows you to set a lower limit on the block size.
|
||||
|
||||
The default setting is 32, which means that midi messages are accurate to about < 1ms
|
||||
accuracy, which is probably fine for most purposes, but you may want to increase or
|
||||
decrease this value for your synth.
|
||||
|
||||
If shouldBeStrict is true, the audio sub-blocks will strictly never be smaller than numSamples.
|
||||
|
||||
If shouldBeStrict is false (default), the first audio sub-block in the buffer is allowed
|
||||
to be smaller, to make sure that the first MIDI event in a buffer will always be sample-accurate
|
||||
(this can sometimes help to avoid quantisation or phasing issues).
|
||||
*/
|
||||
void setMinimumRenderingSubdivisionSize (int numSamples, bool shouldBeStrict = false) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Puts the synthesiser into legacy mode.
|
||||
|
||||
@param pitchbendRange The note pitchbend range in semitones to use when in legacy mode.
|
||||
Must be between 0 and 96, otherwise behaviour is undefined.
|
||||
The default pitchbend range in legacy mode is +/- 2 semitones.
|
||||
@param channelRange The range of MIDI channels to use for notes when in legacy mode.
|
||||
The default is to use all MIDI channels (1-16).
|
||||
|
||||
To get out of legacy mode, set a new MPE zone layout using setZoneLayout.
|
||||
*/
|
||||
void enableLegacyMode (int pitchbendRange = 2,
|
||||
Range<int> channelRange = Range<int> (1, 17));
|
||||
|
||||
/** Returns true if the instrument is in legacy mode, false otherwise. */
|
||||
bool isLegacyModeEnabled() const noexcept;
|
||||
|
||||
/** Returns the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
|
||||
Range<int> getLegacyModeChannelRange() const noexcept;
|
||||
|
||||
/** Re-sets the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
|
||||
void setLegacyModeChannelRange (Range<int> channelRange);
|
||||
|
||||
/** Returns the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
|
||||
int getLegacyModePitchbendRange() const noexcept;
|
||||
|
||||
/** Re-sets the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
|
||||
void setLegacyModePitchbendRange (int pitchbendRange);
|
||||
|
||||
//==============================================================================
|
||||
using TrackingMode = MPEInstrument::TrackingMode;
|
||||
|
||||
/** Set the MPE tracking mode for the pressure dimension. */
|
||||
void setPressureTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
/** Set the MPE tracking mode for the pitchbend dimension. */
|
||||
void setPitchbendTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
/** Set the MPE tracking mode for the timbre dimension. */
|
||||
void setTimbreTrackingMode (TrackingMode modeToUse);
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/** Implement this method to render your audio inside.
|
||||
@see renderNextBlock
|
||||
*/
|
||||
virtual void renderNextSubBlock (AudioBuffer<float>& outputAudio,
|
||||
int startSample,
|
||||
int numSamples) = 0;
|
||||
|
||||
/** Implement this method if you want to render 64-bit audio as well;
|
||||
otherwise leave blank.
|
||||
*/
|
||||
virtual void renderNextSubBlock (AudioBuffer<double>& /*outputAudio*/,
|
||||
int /*startSample*/,
|
||||
int /*numSamples*/) {}
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/** @internal */
|
||||
MPEInstrument& instrument;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
MPEInstrument defaultInstrument { MPEZone (MPEZone::Type::lower, 15) };
|
||||
|
||||
CriticalSection noteStateLock;
|
||||
double sampleRate = 0.0;
|
||||
int minimumSubBlockSize = 32;
|
||||
bool subBlockSubdivisionIsStrict = false;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESynthesiserBase)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MPESynthesiserVoice::MPESynthesiserVoice()
|
||||
{
|
||||
}
|
||||
|
||||
MPESynthesiserVoice::~MPESynthesiserVoice()
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MPESynthesiserVoice::isCurrentlyPlayingNote (MPENote note) const noexcept
|
||||
{
|
||||
return isActive() && currentlyPlayingNote.noteID == note.noteID;
|
||||
}
|
||||
|
||||
bool MPESynthesiserVoice::isPlayingButReleased() const noexcept
|
||||
{
|
||||
return isActive() && currentlyPlayingNote.keyState == MPENote::off;
|
||||
}
|
||||
|
||||
void MPESynthesiserVoice::clearCurrentNote() noexcept
|
||||
{
|
||||
currentlyPlayingNote = MPENote();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents an MPE voice that an MPESynthesiser can use to play a sound.
|
||||
|
||||
A voice plays a single sound at a time, and a synthesiser holds an array of
|
||||
voices so that it can play polyphonically.
|
||||
|
||||
@see MPESynthesiser, MPENote
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPESynthesiserVoice
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Constructor. */
|
||||
MPESynthesiserVoice();
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~MPESynthesiserVoice();
|
||||
|
||||
/** Returns the MPENote that this voice is currently playing.
|
||||
Returns an invalid MPENote if no note is playing
|
||||
(you can check this using MPENote::isValid() or MPEVoice::isActive()).
|
||||
*/
|
||||
MPENote getCurrentlyPlayingNote() const noexcept { return currentlyPlayingNote; }
|
||||
|
||||
/** Returns true if the voice is currently playing the given MPENote
|
||||
(as identified by the note's initial note number and MIDI channel).
|
||||
*/
|
||||
bool isCurrentlyPlayingNote (MPENote note) const noexcept;
|
||||
|
||||
/** Returns true if this voice is currently busy playing a sound.
|
||||
By default this just checks whether getCurrentlyPlayingNote()
|
||||
returns a valid MPE note, but can be overridden for more advanced checking.
|
||||
*/
|
||||
virtual bool isActive() const { return currentlyPlayingNote.isValid(); }
|
||||
|
||||
/** Returns true if a voice is sounding in its release phase. **/
|
||||
bool isPlayingButReleased() const noexcept;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that a new note has started on it.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
*/
|
||||
virtual void noteStarted() = 0;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that its currently playing note has stopped.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
|
||||
If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
|
||||
sound immediately, and must call clearCurrentNote() to reset the state of this voice
|
||||
and allow the synth to reassign it another sound.
|
||||
|
||||
If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
|
||||
begin fading out its sound, and it can stop playing until it's finished. As soon as it
|
||||
finishes playing (during the rendering callback), it must make sure that it calls
|
||||
clearCurrentNote().
|
||||
*/
|
||||
virtual void noteStopped (bool allowTailOff) = 0;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that its currently playing note
|
||||
has changed its pressure value.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
*/
|
||||
virtual void notePressureChanged() = 0;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that its currently playing note
|
||||
has changed its pitchbend value.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
|
||||
Note: You can call currentlyPlayingNote.getFrequencyInHertz() to find out the effective frequency
|
||||
of the note, as a sum of the initial note number, the per-note pitchbend and the master pitchbend.
|
||||
*/
|
||||
virtual void notePitchbendChanged() = 0;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that its currently playing note
|
||||
has changed its timbre value.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
*/
|
||||
virtual void noteTimbreChanged() = 0;
|
||||
|
||||
/** Called by the MPESynthesiser to let the voice know that its currently playing note
|
||||
has changed its key state.
|
||||
This typically happens when a sustain or sostenuto pedal is pressed or released (on
|
||||
an MPE channel relevant for this note), or if the note key is lifted while the sustained
|
||||
or sostenuto pedal is still held down.
|
||||
This will be called during the rendering callback, so must be fast and thread-safe.
|
||||
*/
|
||||
virtual void noteKeyStateChanged() = 0;
|
||||
|
||||
/** Renders the next block of data for this voice.
|
||||
|
||||
The output audio data must be added to the current contents of the buffer provided.
|
||||
Only the region of the buffer between startSample and (startSample + numSamples)
|
||||
should be altered by this method.
|
||||
|
||||
If the voice is currently silent, it should just return without doing anything.
|
||||
|
||||
If the sound that the voice is playing finishes during the course of this rendered
|
||||
block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
|
||||
|
||||
The size of the blocks that are rendered can change each time it is called, and may
|
||||
involve rendering as little as 1 sample at a time. In between rendering callbacks,
|
||||
the voice's methods will be called to tell it about note and controller events.
|
||||
*/
|
||||
virtual void renderNextBlock (AudioBuffer<float>& outputBuffer,
|
||||
int startSample,
|
||||
int numSamples) = 0;
|
||||
|
||||
/** Renders the next block of 64-bit data for this voice.
|
||||
|
||||
Support for 64-bit audio is optional. You can choose to not override this method if
|
||||
you don't need it (the default implementation simply does nothing).
|
||||
*/
|
||||
virtual void renderNextBlock (AudioBuffer<double>& /*outputBuffer*/,
|
||||
int /*startSample*/,
|
||||
int /*numSamples*/) {}
|
||||
|
||||
/** Changes the voice's reference sample rate.
|
||||
|
||||
The rate is set so that subclasses know the output rate and can set their pitch
|
||||
accordingly.
|
||||
|
||||
This method is called by the synth, and subclasses can access the current rate with
|
||||
the currentSampleRate member.
|
||||
*/
|
||||
virtual void setCurrentSampleRate (double newRate) { currentSampleRate = newRate; }
|
||||
|
||||
/** Returns the current target sample rate at which rendering is being done.
|
||||
Subclasses may need to know this so that they can pitch things correctly.
|
||||
*/
|
||||
double getSampleRate() const noexcept { return currentSampleRate; }
|
||||
|
||||
/** This will be set to an incrementing counter value in MPESynthesiser::startVoice()
|
||||
and can be used to determine the order in which voices started.
|
||||
*/
|
||||
uint32 noteOnTime = 0;
|
||||
|
||||
protected:
|
||||
//==============================================================================
|
||||
/** Resets the state of this voice after a sound has finished playing.
|
||||
|
||||
The subclass must call this when it finishes playing a note and becomes available
|
||||
to play new ones.
|
||||
|
||||
It must either call it in the stopNote() method, or if the voice is tailing off,
|
||||
then it should call it later during the renderNextBlock method, as soon as it
|
||||
finishes its tail-off.
|
||||
|
||||
It can also be called at any time during the render callback if the sound happens
|
||||
to have finished, e.g. if it's playing a sample and the sample finishes.
|
||||
*/
|
||||
void clearCurrentNote() noexcept;
|
||||
|
||||
//==============================================================================
|
||||
double currentSampleRate = 0.0;
|
||||
MPENote currentlyPlayingNote;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
friend class MPESynthesiser;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESynthesiserVoice)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,575 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MPEChannelAssigner::MPEChannelAssigner (MPEZoneLayout::Zone zoneToUse)
|
||||
: zone (new MPEZoneLayout::Zone (zoneToUse)),
|
||||
channelIncrement (zone->isLowerZone() ? 1 : -1),
|
||||
numChannels (zone->numMemberChannels),
|
||||
firstChannel (zone->getFirstMemberChannel()),
|
||||
lastChannel (zone->getLastMemberChannel()),
|
||||
midiChannelLastAssigned (firstChannel - channelIncrement)
|
||||
{
|
||||
// must be an active MPE zone!
|
||||
jassert (numChannels > 0);
|
||||
}
|
||||
|
||||
MPEChannelAssigner::MPEChannelAssigner (Range<int> channelRange)
|
||||
: isLegacy (true),
|
||||
channelIncrement (1),
|
||||
numChannels (channelRange.getLength()),
|
||||
firstChannel (channelRange.getStart()),
|
||||
lastChannel (channelRange.getEnd() - 1),
|
||||
midiChannelLastAssigned (firstChannel - channelIncrement)
|
||||
{
|
||||
// must have at least one channel!
|
||||
jassert (! channelRange.isEmpty());
|
||||
}
|
||||
|
||||
int MPEChannelAssigner::findMidiChannelForNewNote (int noteNumber) noexcept
|
||||
{
|
||||
for (int ch = firstChannel; (isLegacy || zone->isLowerZone() ? ch <= lastChannel : ch >= lastChannel); ch += channelIncrement)
|
||||
{
|
||||
if (midiChannels[(size_t) ch].isFree() && midiChannels[(size_t) ch].lastNotePlayed == noteNumber)
|
||||
{
|
||||
midiChannelLastAssigned = ch;
|
||||
midiChannels[(size_t) ch].notes.add (noteNumber);
|
||||
return ch;
|
||||
}
|
||||
}
|
||||
|
||||
for (int ch = midiChannelLastAssigned + channelIncrement; ; ch += channelIncrement)
|
||||
{
|
||||
if (ch == lastChannel + channelIncrement) // loop wrap-around
|
||||
ch = firstChannel;
|
||||
|
||||
if (midiChannels[(size_t) ch].isFree())
|
||||
{
|
||||
midiChannelLastAssigned = ch;
|
||||
midiChannels[(size_t) ch].notes.add (noteNumber);
|
||||
return ch;
|
||||
}
|
||||
|
||||
if (ch == midiChannelLastAssigned)
|
||||
break; // no free channels!
|
||||
}
|
||||
|
||||
midiChannelLastAssigned = findMidiChannelPlayingClosestNonequalNote (noteNumber);
|
||||
midiChannels[(size_t) midiChannelLastAssigned].notes.add (noteNumber);
|
||||
|
||||
return midiChannelLastAssigned;
|
||||
}
|
||||
|
||||
int MPEChannelAssigner::findMidiChannelForExistingNote (int noteNumber) noexcept
|
||||
{
|
||||
const auto iter = std::find_if (midiChannels.cbegin(), midiChannels.cend(), [&] (auto& ch)
|
||||
{
|
||||
return std::find (ch.notes.begin(), ch.notes.end(), noteNumber) != ch.notes.end();
|
||||
});
|
||||
|
||||
return iter != midiChannels.cend() ? (int) std::distance (midiChannels.cbegin(), iter) : -1;
|
||||
}
|
||||
|
||||
void MPEChannelAssigner::noteOff (int noteNumber, int midiChannel)
|
||||
{
|
||||
const auto removeNote = [] (MidiChannel& ch, int noteNum)
|
||||
{
|
||||
if (ch.notes.removeAllInstancesOf (noteNum) > 0)
|
||||
{
|
||||
ch.lastNotePlayed = noteNum;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
if (midiChannel >= 0 && midiChannel <= 16)
|
||||
{
|
||||
removeNote (midiChannels[(size_t) midiChannel], noteNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto& ch : midiChannels)
|
||||
{
|
||||
if (removeNote (ch, noteNumber))
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void MPEChannelAssigner::allNotesOff()
|
||||
{
|
||||
for (auto& ch : midiChannels)
|
||||
{
|
||||
if (ch.notes.size() > 0)
|
||||
ch.lastNotePlayed = ch.notes.getLast();
|
||||
|
||||
ch.notes.clear();
|
||||
}
|
||||
}
|
||||
|
||||
int MPEChannelAssigner::findMidiChannelPlayingClosestNonequalNote (int noteNumber) noexcept
|
||||
{
|
||||
auto channelWithClosestNote = firstChannel;
|
||||
int closestNoteDistance = 127;
|
||||
|
||||
for (int ch = firstChannel; (isLegacy || zone->isLowerZone() ? ch <= lastChannel : ch >= lastChannel); ch += channelIncrement)
|
||||
{
|
||||
for (auto note : midiChannels[(size_t) ch].notes)
|
||||
{
|
||||
auto noteDistance = std::abs (note - noteNumber);
|
||||
|
||||
if (noteDistance > 0 && noteDistance < closestNoteDistance)
|
||||
{
|
||||
closestNoteDistance = noteDistance;
|
||||
channelWithClosestNote = ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return channelWithClosestNote;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MPEChannelRemapper::MPEChannelRemapper (MPEZoneLayout::Zone zoneToRemap)
|
||||
: zone (zoneToRemap),
|
||||
channelIncrement (zone.isLowerZone() ? 1 : -1),
|
||||
firstChannel (zone.getFirstMemberChannel()),
|
||||
lastChannel (zone.getLastMemberChannel())
|
||||
{
|
||||
// must be an active MPE zone!
|
||||
jassert (zone.numMemberChannels > 0);
|
||||
zeroArrays();
|
||||
}
|
||||
|
||||
void MPEChannelRemapper::remapMidiChannelIfNeeded (MidiMessage& message, uint32 mpeSourceID) noexcept
|
||||
{
|
||||
auto channel = message.getChannel();
|
||||
|
||||
if (! zone.isUsingChannelAsMemberChannel (channel))
|
||||
return;
|
||||
|
||||
if (channel == zone.getMasterChannel() && (message.isResetAllControllers() || message.isAllNotesOff()))
|
||||
{
|
||||
clearSource (mpeSourceID);
|
||||
return;
|
||||
}
|
||||
|
||||
auto sourceAndChannelID = (((uint32) mpeSourceID << 5) | (uint32) (channel));
|
||||
|
||||
if (messageIsNoteData (message))
|
||||
{
|
||||
++counter;
|
||||
|
||||
// fast path - no remap
|
||||
if (applyRemapIfExisting (channel, sourceAndChannelID, message))
|
||||
return;
|
||||
|
||||
// find existing remap
|
||||
for (int chan = firstChannel; (zone.isLowerZone() ? chan <= lastChannel : chan >= lastChannel); chan += channelIncrement)
|
||||
if (applyRemapIfExisting (chan, sourceAndChannelID, message))
|
||||
return;
|
||||
|
||||
// no remap necessary
|
||||
if (sourceAndChannel[channel] == notMPE)
|
||||
{
|
||||
lastUsed[channel] = counter;
|
||||
sourceAndChannel[channel] = sourceAndChannelID;
|
||||
return;
|
||||
}
|
||||
|
||||
// remap source & channel to new channel
|
||||
auto chan = getBestChanToReuse();
|
||||
|
||||
sourceAndChannel[chan] = sourceAndChannelID;
|
||||
lastUsed[chan] = counter;
|
||||
message.setChannel (chan);
|
||||
}
|
||||
}
|
||||
|
||||
void MPEChannelRemapper::reset() noexcept
|
||||
{
|
||||
for (auto& s : sourceAndChannel)
|
||||
s = notMPE;
|
||||
}
|
||||
|
||||
void MPEChannelRemapper::clearChannel (int channel) noexcept
|
||||
{
|
||||
sourceAndChannel[channel] = notMPE;
|
||||
}
|
||||
|
||||
void MPEChannelRemapper::clearSource (uint32 mpeSourceID)
|
||||
{
|
||||
for (auto& s : sourceAndChannel)
|
||||
{
|
||||
if (uint32 (s >> 5) == mpeSourceID)
|
||||
{
|
||||
s = notMPE;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool MPEChannelRemapper::applyRemapIfExisting (int channel, uint32 sourceAndChannelID, MidiMessage& m) noexcept
|
||||
{
|
||||
if (sourceAndChannel[channel] == sourceAndChannelID)
|
||||
{
|
||||
if (m.isNoteOff())
|
||||
sourceAndChannel[channel] = notMPE;
|
||||
else
|
||||
lastUsed[channel] = counter;
|
||||
|
||||
m.setChannel (channel);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
int MPEChannelRemapper::getBestChanToReuse() const noexcept
|
||||
{
|
||||
for (int chan = firstChannel; (zone.isLowerZone() ? chan <= lastChannel : chan >= lastChannel); chan += channelIncrement)
|
||||
if (sourceAndChannel[chan] == notMPE)
|
||||
return chan;
|
||||
|
||||
auto bestChan = firstChannel;
|
||||
auto bestLastUse = counter;
|
||||
|
||||
for (int chan = firstChannel; (zone.isLowerZone() ? chan <= lastChannel : chan >= lastChannel); chan += channelIncrement)
|
||||
{
|
||||
if (lastUsed[chan] < bestLastUse)
|
||||
{
|
||||
bestLastUse = lastUsed[chan];
|
||||
bestChan = chan;
|
||||
}
|
||||
}
|
||||
|
||||
return bestChan;
|
||||
}
|
||||
|
||||
void MPEChannelRemapper::zeroArrays()
|
||||
{
|
||||
for (int i = 0; i < 17; ++i)
|
||||
{
|
||||
sourceAndChannel[i] = 0;
|
||||
lastUsed[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
struct MPEUtilsUnitTests final : public UnitTest
|
||||
{
|
||||
MPEUtilsUnitTests()
|
||||
: UnitTest ("MPE Utilities", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("MPEChannelAssigner");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
|
||||
// lower
|
||||
{
|
||||
layout.setLowerZone (15);
|
||||
|
||||
// lower zone
|
||||
MPEChannelAssigner channelAssigner (layout.getLowerZone());
|
||||
|
||||
// check that channels are assigned in correct order
|
||||
int noteNum = 60;
|
||||
for (int ch = 2; ch <= 16; ++ch)
|
||||
{
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (noteNum), ch);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (noteNum), ch);
|
||||
|
||||
++noteNum;
|
||||
}
|
||||
|
||||
// check that note-offs are processed
|
||||
channelAssigner.noteOff (60);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (60), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (60), 2);
|
||||
|
||||
channelAssigner.noteOff (61);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (61), 3);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (61), 3);
|
||||
|
||||
// check that assigned channel was last to play note
|
||||
channelAssigner.noteOff (65);
|
||||
channelAssigner.noteOff (66);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 8);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 8);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 7);
|
||||
|
||||
// find closest channel playing nonequal note
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 2);
|
||||
|
||||
// all notes off
|
||||
channelAssigner.allNotesOff();
|
||||
|
||||
// last note played
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 8);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 8);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 2);
|
||||
|
||||
// normal assignment
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (101), 3);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (20), 4);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (101), 3);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (20), 4);
|
||||
}
|
||||
|
||||
// upper
|
||||
{
|
||||
layout.setUpperZone (15);
|
||||
|
||||
// upper zone
|
||||
MPEChannelAssigner channelAssigner (layout.getUpperZone());
|
||||
|
||||
// check that channels are assigned in correct order
|
||||
int noteNum = 60;
|
||||
for (int ch = 15; ch >= 1; --ch)
|
||||
{
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (noteNum), ch);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (noteNum), ch);
|
||||
|
||||
++noteNum;
|
||||
}
|
||||
|
||||
// check that note-offs are processed
|
||||
channelAssigner.noteOff (60);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (60), 15);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (60), 15);
|
||||
|
||||
channelAssigner.noteOff (61);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (61), 14);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (61), 14);
|
||||
|
||||
// check that assigned channel was last to play note
|
||||
channelAssigner.noteOff (65);
|
||||
channelAssigner.noteOff (66);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 9);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 10);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 9);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 10);
|
||||
|
||||
// find closest channel playing nonequal note
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 15);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 15);
|
||||
|
||||
// all notes off
|
||||
channelAssigner.allNotesOff();
|
||||
|
||||
// last note played
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 9);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 10);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 15);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 9);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 10);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 15);
|
||||
|
||||
// normal assignment
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (101), 14);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (20), 13);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (101), 14);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (20), 13);
|
||||
}
|
||||
|
||||
// legacy
|
||||
{
|
||||
MPEChannelAssigner channelAssigner;
|
||||
|
||||
// check that channels are assigned in correct order
|
||||
int noteNum = 60;
|
||||
for (int ch = 1; ch <= 16; ++ch)
|
||||
{
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (noteNum), ch);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (noteNum), ch);
|
||||
|
||||
++noteNum;
|
||||
}
|
||||
|
||||
// check that note-offs are processed
|
||||
channelAssigner.noteOff (60);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (60), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (60), 1);
|
||||
|
||||
channelAssigner.noteOff (61);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (61), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (61), 2);
|
||||
|
||||
// check that assigned channel was last to play note
|
||||
channelAssigner.noteOff (65);
|
||||
channelAssigner.noteOff (66);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 6);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 6);
|
||||
|
||||
// find closest channel playing nonequal note
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 1);
|
||||
|
||||
// all notes off
|
||||
channelAssigner.allNotesOff();
|
||||
|
||||
// last note played
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (66), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (65), 6);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (55), 1);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (66), 7);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (65), 6);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (80), 16);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (55), 1);
|
||||
|
||||
// normal assignment
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (101), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForNewNote (20), 3);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (101), 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (20), 3);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("MPEChannelAssigner - One channel zone");
|
||||
{
|
||||
MPEZone zone { MPEZone::Type::lower, 1 };
|
||||
MPEChannelAssigner channelAssigner { zone };
|
||||
|
||||
const auto channel = channelAssigner.findMidiChannelForNewNote (42);
|
||||
|
||||
expectEquals (channel, 2);
|
||||
expectEquals (channelAssigner.findMidiChannelForExistingNote (42), channel);
|
||||
}
|
||||
|
||||
beginTest ("MPEChannelRemapper");
|
||||
{
|
||||
// 3 different MPE 'sources', constant IDs
|
||||
const int sourceID1 = 0;
|
||||
const int sourceID2 = 1;
|
||||
const int sourceID3 = 2;
|
||||
|
||||
MPEZoneLayout layout;
|
||||
|
||||
{
|
||||
layout.setLowerZone (15);
|
||||
|
||||
// lower zone
|
||||
MPEChannelRemapper channelRemapper (layout.getLowerZone());
|
||||
|
||||
// first source, shouldn't remap
|
||||
for (int ch = 2; ch <= 16; ++ch)
|
||||
{
|
||||
auto noteOn = MidiMessage::noteOn (ch, 60, 1.0f);
|
||||
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID1);
|
||||
expectEquals (noteOn.getChannel(), ch);
|
||||
}
|
||||
|
||||
auto noteOn = MidiMessage::noteOn (2, 60, 1.0f);
|
||||
|
||||
// remap onto oldest last-used channel
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID2);
|
||||
expectEquals (noteOn.getChannel(), 2);
|
||||
|
||||
// remap onto oldest last-used channel
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID3);
|
||||
expectEquals (noteOn.getChannel(), 3);
|
||||
|
||||
// remap to correct channel for source ID
|
||||
auto noteOff = MidiMessage::noteOff (2, 60, 1.0f);
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOff, sourceID3);
|
||||
expectEquals (noteOff.getChannel(), 3);
|
||||
}
|
||||
|
||||
{
|
||||
layout.setUpperZone (15);
|
||||
|
||||
// upper zone
|
||||
MPEChannelRemapper channelRemapper (layout.getUpperZone());
|
||||
|
||||
// first source, shouldn't remap
|
||||
for (int ch = 15; ch >= 1; --ch)
|
||||
{
|
||||
auto noteOn = MidiMessage::noteOn (ch, 60, 1.0f);
|
||||
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID1);
|
||||
expectEquals (noteOn.getChannel(), ch);
|
||||
}
|
||||
|
||||
auto noteOn = MidiMessage::noteOn (15, 60, 1.0f);
|
||||
|
||||
// remap onto oldest last-used channel
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID2);
|
||||
expectEquals (noteOn.getChannel(), 15);
|
||||
|
||||
// remap onto oldest last-used channel
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOn, sourceID3);
|
||||
expectEquals (noteOn.getChannel(), 14);
|
||||
|
||||
// remap to correct channel for source ID
|
||||
auto noteOff = MidiMessage::noteOff (15, 60, 1.0f);
|
||||
channelRemapper.remapMidiChannelIfNeeded (noteOff, sourceID3);
|
||||
expectEquals (noteOff.getChannel(), 14);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MPEUtilsUnitTests MPEUtilsUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // 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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class handles the assignment of new MIDI notes to member channels of an active
|
||||
MPE zone.
|
||||
|
||||
To use it, create an instance passing in the MPE zone that it should operate on
|
||||
and then call use the findMidiChannelForNewNote() method for all note-on messages
|
||||
and the noteOff() method for all note-off messages.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class MPEChannelAssigner
|
||||
{
|
||||
public:
|
||||
/** Constructor.
|
||||
|
||||
This will assign channels within the range of the specified MPE zone.
|
||||
*/
|
||||
MPEChannelAssigner (MPEZoneLayout::Zone zoneToUse);
|
||||
|
||||
/** Legacy mode constructor.
|
||||
|
||||
This will assign channels within the specified range.
|
||||
*/
|
||||
MPEChannelAssigner (Range<int> channelRange = Range<int> (1, 17));
|
||||
|
||||
/** This method will use a set of rules recommended in the MPE specification to
|
||||
determine which member channel the specified MIDI note should be assigned to
|
||||
and will return this channel number.
|
||||
|
||||
The rules have the following precedence:
|
||||
- find a free channel on which the last note played was the same as the one specified
|
||||
- find the next free channel in round-robin assignment
|
||||
- find the channel number that is currently playing the closest note (but not the same)
|
||||
|
||||
@param noteNumber the MIDI note number to be assigned to a channel
|
||||
@returns the zone's member channel that this note should be assigned to
|
||||
*/
|
||||
int findMidiChannelForNewNote (int noteNumber) noexcept;
|
||||
|
||||
/** If a note has been added using findMidiChannelForNewNote() this will return the channel
|
||||
to which it was assigned, otherwise it will return -1.
|
||||
*/
|
||||
int findMidiChannelForExistingNote (int initialNoteOnNumber) noexcept;
|
||||
|
||||
/** You must call this method for all note-offs that you receive so that this class
|
||||
can keep track of the currently playing notes internally.
|
||||
|
||||
You can specify the channel number the note off happened on. If you don't, it will
|
||||
look through all channels to find the registered midi note matching the given note number.
|
||||
*/
|
||||
void noteOff (int noteNumber, int midiChannel = -1);
|
||||
|
||||
/** Call this to clear all currently playing notes. */
|
||||
void allNotesOff();
|
||||
|
||||
private:
|
||||
bool isLegacy = false;
|
||||
std::unique_ptr<MPEZoneLayout::Zone> zone;
|
||||
int channelIncrement, numChannels, firstChannel, lastChannel, midiChannelLastAssigned;
|
||||
|
||||
//==============================================================================
|
||||
struct MidiChannel
|
||||
{
|
||||
Array<int> notes;
|
||||
int lastNotePlayed = -1;
|
||||
bool isFree() const noexcept { return notes.isEmpty(); }
|
||||
};
|
||||
std::array<MidiChannel, 17> midiChannels;
|
||||
|
||||
//==============================================================================
|
||||
int findMidiChannelPlayingClosestNonequalNote (int noteNumber) noexcept;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class handles the logic for remapping MIDI note messages from multiple MPE
|
||||
sources onto a specified MPE zone.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class MPEChannelRemapper
|
||||
{
|
||||
public:
|
||||
/** Used to indicate that a particular source & channel combination is not currently using MPE. */
|
||||
static const uint32 notMPE = 0;
|
||||
|
||||
/** Constructor */
|
||||
MPEChannelRemapper (MPEZoneLayout::Zone zoneToRemap);
|
||||
|
||||
//==============================================================================
|
||||
/** Remaps the MIDI channel of the specified MIDI message (if necessary).
|
||||
|
||||
Note that the MidiMessage object passed in will have it's channel changed if it
|
||||
needs to be remapped.
|
||||
|
||||
@param message the message to be remapped
|
||||
@param mpeSourceID the ID of the MPE source of the message. This is up to the
|
||||
user to define and keep constant
|
||||
*/
|
||||
void remapMidiChannelIfNeeded (MidiMessage& message, uint32 mpeSourceID) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Resets all the source & channel combinations. */
|
||||
void reset() noexcept;
|
||||
|
||||
/** Clears a specified channel of this MPE zone. */
|
||||
void clearChannel (int channel) noexcept;
|
||||
|
||||
/** Clears all channels in use by a specified source. */
|
||||
void clearSource (uint32 mpeSourceID);
|
||||
|
||||
private:
|
||||
MPEZoneLayout::Zone zone;
|
||||
|
||||
int channelIncrement;
|
||||
int firstChannel, lastChannel;
|
||||
|
||||
uint32 sourceAndChannel[17];
|
||||
uint32 lastUsed[17];
|
||||
uint32 counter = 0;
|
||||
|
||||
//==============================================================================
|
||||
bool applyRemapIfExisting (int channel, uint32 sourceAndChannelID, MidiMessage& m) noexcept;
|
||||
int getBestChanToReuse() const noexcept;
|
||||
|
||||
void zeroArrays();
|
||||
|
||||
//==============================================================================
|
||||
bool messageIsNoteData (const MidiMessage& m) { return (*m.getRawData() & 0xf0) != 0xf0; }
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MPEValue::MPEValue() noexcept {}
|
||||
MPEValue::MPEValue (int value) : normalisedValue (value) {}
|
||||
|
||||
//==============================================================================
|
||||
MPEValue MPEValue::from7BitInt (int value) noexcept
|
||||
{
|
||||
jassert (value >= 0 && value <= 127);
|
||||
|
||||
auto valueAs14Bit = value <= 64 ? value << 7
|
||||
: int (jmap<float> (float (value - 64), 0.0f, 63.0f, 0.0f, 8191.0f)) + 8192;
|
||||
|
||||
return { valueAs14Bit };
|
||||
}
|
||||
|
||||
MPEValue MPEValue::from14BitInt (int value) noexcept
|
||||
{
|
||||
jassert (value >= 0 && value <= 16383);
|
||||
return { value };
|
||||
}
|
||||
|
||||
MPEValue MPEValue::fromUnsignedFloat (float value) noexcept
|
||||
{
|
||||
jassert (0.0f <= value && value <= 1.0f);
|
||||
return { roundToInt (value * 16383.0f) };
|
||||
}
|
||||
|
||||
MPEValue MPEValue::fromSignedFloat (float value) noexcept
|
||||
{
|
||||
jassert (-1.0f <= value && value <= 1.0f);
|
||||
return { roundToInt (((value + 1.0f) * 16383.0f) / 2.0f) };
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
MPEValue MPEValue::minValue() noexcept { return MPEValue::from7BitInt (0); }
|
||||
MPEValue MPEValue::centreValue() noexcept { return MPEValue::from7BitInt (64); }
|
||||
MPEValue MPEValue::maxValue() noexcept { return MPEValue::from7BitInt (127); }
|
||||
|
||||
int MPEValue::as7BitInt() const noexcept
|
||||
{
|
||||
return normalisedValue >> 7;
|
||||
}
|
||||
|
||||
int MPEValue::as14BitInt() const noexcept
|
||||
{
|
||||
return normalisedValue;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
float MPEValue::asSignedFloat() const noexcept
|
||||
{
|
||||
return (normalisedValue < 8192)
|
||||
? jmap<float> (float (normalisedValue), 0.0f, 8192.0f, -1.0f, 0.0f)
|
||||
: jmap<float> (float (normalisedValue), 8192.0f, 16383.0f, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
float MPEValue::asUnsignedFloat() const noexcept
|
||||
{
|
||||
return jmap<float> (float (normalisedValue), 0.0f, 16383.0f, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MPEValue::operator== (const MPEValue& other) const noexcept
|
||||
{
|
||||
return normalisedValue == other.normalisedValue;
|
||||
}
|
||||
|
||||
bool MPEValue::operator!= (const MPEValue& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class MPEValueTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MPEValueTests()
|
||||
: UnitTest ("MPEValue class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("comparison operator");
|
||||
{
|
||||
MPEValue value1 = MPEValue::from7BitInt (7);
|
||||
MPEValue value2 = MPEValue::from7BitInt (7);
|
||||
MPEValue value3 = MPEValue::from7BitInt (8);
|
||||
|
||||
expect (value1 == value1);
|
||||
expect (value1 == value2);
|
||||
expect (value1 != value3);
|
||||
}
|
||||
|
||||
beginTest ("special values");
|
||||
{
|
||||
expectEquals (MPEValue::minValue().as7BitInt(), 0);
|
||||
expectEquals (MPEValue::minValue().as14BitInt(), 0);
|
||||
|
||||
expectEquals (MPEValue::centreValue().as7BitInt(), 64);
|
||||
expectEquals (MPEValue::centreValue().as14BitInt(), 8192);
|
||||
|
||||
expectEquals (MPEValue::maxValue().as7BitInt(), 127);
|
||||
expectEquals (MPEValue::maxValue().as14BitInt(), 16383);
|
||||
}
|
||||
|
||||
beginTest ("zero/minimum value");
|
||||
{
|
||||
expectValuesConsistent (MPEValue::from7BitInt (0), 0, 0, -1.0f, 0.0f);
|
||||
expectValuesConsistent (MPEValue::from14BitInt (0), 0, 0, -1.0f, 0.0f);
|
||||
expectValuesConsistent (MPEValue::fromUnsignedFloat (0.0f), 0, 0, -1.0f, 0.0f);
|
||||
expectValuesConsistent (MPEValue::fromSignedFloat (-1.0f), 0, 0, -1.0f, 0.0f);
|
||||
}
|
||||
|
||||
beginTest ("maximum value");
|
||||
{
|
||||
expectValuesConsistent (MPEValue::from7BitInt (127), 127, 16383, 1.0f, 1.0f);
|
||||
expectValuesConsistent (MPEValue::from14BitInt (16383), 127, 16383, 1.0f, 1.0f);
|
||||
expectValuesConsistent (MPEValue::fromUnsignedFloat (1.0f), 127, 16383, 1.0f, 1.0f);
|
||||
expectValuesConsistent (MPEValue::fromSignedFloat (1.0f), 127, 16383, 1.0f, 1.0f);
|
||||
}
|
||||
|
||||
beginTest ("centre value");
|
||||
{
|
||||
expectValuesConsistent (MPEValue::from7BitInt (64), 64, 8192, 0.0f, 0.5f);
|
||||
expectValuesConsistent (MPEValue::from14BitInt (8192), 64, 8192, 0.0f, 0.5f);
|
||||
expectValuesConsistent (MPEValue::fromUnsignedFloat (0.5f), 64, 8192, 0.0f, 0.5f);
|
||||
expectValuesConsistent (MPEValue::fromSignedFloat (0.0f), 64, 8192, 0.0f, 0.5f);
|
||||
}
|
||||
|
||||
beginTest ("value halfway between min and centre");
|
||||
{
|
||||
expectValuesConsistent (MPEValue::from7BitInt (32), 32, 4096, -0.5f, 0.25f);
|
||||
expectValuesConsistent (MPEValue::from14BitInt (4096), 32, 4096, -0.5f, 0.25f);
|
||||
expectValuesConsistent (MPEValue::fromUnsignedFloat (0.25f), 32, 4096, -0.5f, 0.25f);
|
||||
expectValuesConsistent (MPEValue::fromSignedFloat (-0.5f), 32, 4096, -0.5f, 0.25f);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void expectValuesConsistent (MPEValue value,
|
||||
int expectedValueAs7BitInt,
|
||||
int expectedValueAs14BitInt,
|
||||
float expectedValueAsSignedFloat,
|
||||
float expectedValueAsUnsignedFloat)
|
||||
{
|
||||
expectEquals (value.as7BitInt(), expectedValueAs7BitInt);
|
||||
expectEquals (value.as14BitInt(), expectedValueAs14BitInt);
|
||||
expectFloatWithinRelativeError (value.asSignedFloat(), expectedValueAsSignedFloat, 0.0001f);
|
||||
expectFloatWithinRelativeError (value.asUnsignedFloat(), expectedValueAsUnsignedFloat, 0.0001f);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void expectFloatWithinRelativeError (float actualValue, float expectedValue, float maxRelativeError)
|
||||
{
|
||||
const float maxAbsoluteError = jmax (1.0f, std::abs (expectedValue)) * maxRelativeError;
|
||||
expect (std::abs (expectedValue - actualValue) < maxAbsoluteError);
|
||||
}
|
||||
};
|
||||
|
||||
static MPEValueTests MPEValueUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class represents a single value for any of the MPE
|
||||
dimensions of control. It supports values with 7-bit or 14-bit resolutions
|
||||
(corresponding to 1 or 2 MIDI bytes, respectively). It also offers helper
|
||||
functions to query the value in a variety of representations that can be
|
||||
useful in an audio or MIDI context.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPEValue
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Default constructor.
|
||||
|
||||
Constructs an MPEValue corresponding to the centre value.
|
||||
*/
|
||||
MPEValue() noexcept;
|
||||
|
||||
/** Constructs an MPEValue from an integer between 0 and 127
|
||||
(using 7-bit precision).
|
||||
*/
|
||||
static MPEValue from7BitInt (int value) noexcept;
|
||||
|
||||
/** Constructs an MPEValue from an integer between 0 and 16383
|
||||
(using 14-bit precision).
|
||||
*/
|
||||
static MPEValue from14BitInt (int value) noexcept;
|
||||
|
||||
/** Constructs an MPEValue from a float between 0.0f and 1.0f. */
|
||||
static MPEValue fromUnsignedFloat (float value) noexcept;
|
||||
|
||||
/** Constructs an MPEValue from a float between -1.0f and 1.0f. */
|
||||
static MPEValue fromSignedFloat (float value) noexcept;
|
||||
|
||||
/** Constructs an MPEValue corresponding to the centre value. */
|
||||
static MPEValue centreValue() noexcept;
|
||||
|
||||
/** Constructs an MPEValue corresponding to the minimum value. */
|
||||
static MPEValue minValue() noexcept;
|
||||
|
||||
/** Constructs an MPEValue corresponding to the maximum value. */
|
||||
static MPEValue maxValue() noexcept;
|
||||
|
||||
/** Retrieves the current value as an integer between 0 and 127.
|
||||
|
||||
Information will be lost if the value was initialised with a precision
|
||||
higher than 7-bit.
|
||||
*/
|
||||
int as7BitInt() const noexcept;
|
||||
|
||||
/** Retrieves the current value as an integer between 0 and 16383.
|
||||
|
||||
Resolution will be lost if the value was initialised with a precision
|
||||
higher than 14-bit.
|
||||
*/
|
||||
int as14BitInt() const noexcept;
|
||||
|
||||
/** Retrieves the current value mapped to a float between -1.0f and 1.0f. */
|
||||
float asSignedFloat() const noexcept;
|
||||
|
||||
/** Retrieves the current value mapped to a float between 0.0f and 1.0f. */
|
||||
float asUnsignedFloat() const noexcept;
|
||||
|
||||
/** Returns true if two values are equal. */
|
||||
bool operator== (const MPEValue& other) const noexcept;
|
||||
|
||||
/** Returns true if two values are not equal. */
|
||||
bool operator!= (const MPEValue& other) const noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
MPEValue (int normalisedValue);
|
||||
int normalisedValue = 8192;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,473 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
MPEZoneLayout::MPEZoneLayout (MPEZone lower, MPEZone upper)
|
||||
: lowerZone (lower), upperZone (upper)
|
||||
{
|
||||
}
|
||||
|
||||
MPEZoneLayout::MPEZoneLayout (MPEZone zone)
|
||||
: lowerZone (zone.isLowerZone() ? zone : MPEZone()),
|
||||
upperZone (! zone.isLowerZone() ? zone : MPEZone())
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
MPEZoneLayout::MPEZoneLayout (const MPEZoneLayout& other)
|
||||
: lowerZone (other.lowerZone),
|
||||
upperZone (other.upperZone)
|
||||
{
|
||||
}
|
||||
|
||||
MPEZoneLayout& MPEZoneLayout::operator= (const MPEZoneLayout& other)
|
||||
{
|
||||
lowerZone = other.lowerZone;
|
||||
upperZone = other.upperZone;
|
||||
|
||||
sendLayoutChangeMessage();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void MPEZoneLayout::sendLayoutChangeMessage()
|
||||
{
|
||||
listeners.call ([this] (Listener& l) { l.zoneLayoutChanged (*this); });
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEZoneLayout::setZone (bool isLower, int numMemberChannels, int perNotePitchbendRange, int masterPitchbendRange) noexcept
|
||||
{
|
||||
checkAndLimitZoneParameters (0, 15, numMemberChannels);
|
||||
checkAndLimitZoneParameters (0, 96, perNotePitchbendRange);
|
||||
checkAndLimitZoneParameters (0, 96, masterPitchbendRange);
|
||||
|
||||
if (isLower)
|
||||
lowerZone = { MPEZone::Type::lower, numMemberChannels, perNotePitchbendRange, masterPitchbendRange };
|
||||
else
|
||||
upperZone = { MPEZone::Type::upper, numMemberChannels, perNotePitchbendRange, masterPitchbendRange };
|
||||
|
||||
if (numMemberChannels > 0)
|
||||
{
|
||||
auto totalChannels = lowerZone.numMemberChannels + upperZone.numMemberChannels;
|
||||
|
||||
if (totalChannels >= 15)
|
||||
{
|
||||
if (isLower)
|
||||
upperZone.numMemberChannels = 14 - numMemberChannels;
|
||||
else
|
||||
lowerZone.numMemberChannels = 14 - numMemberChannels;
|
||||
}
|
||||
}
|
||||
|
||||
sendLayoutChangeMessage();
|
||||
}
|
||||
|
||||
void MPEZoneLayout::setLowerZone (int numMemberChannels, int perNotePitchbendRange, int masterPitchbendRange) noexcept
|
||||
{
|
||||
setZone (true, numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
|
||||
}
|
||||
|
||||
void MPEZoneLayout::setUpperZone (int numMemberChannels, int perNotePitchbendRange, int masterPitchbendRange) noexcept
|
||||
{
|
||||
setZone (false, numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
|
||||
}
|
||||
|
||||
void MPEZoneLayout::clearAllZones()
|
||||
{
|
||||
lowerZone = { MPEZone::Type::lower, 0 };
|
||||
upperZone = { MPEZone::Type::upper, 0 };
|
||||
|
||||
sendLayoutChangeMessage();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEZoneLayout::processNextMidiEvent (const MidiMessage& message)
|
||||
{
|
||||
if (! message.isController())
|
||||
return;
|
||||
|
||||
if (auto parsed = rpnDetector.tryParse (message.getChannel(),
|
||||
message.getControllerNumber(),
|
||||
message.getControllerValue()))
|
||||
{
|
||||
processRpnMessage (*parsed);
|
||||
}
|
||||
}
|
||||
|
||||
void MPEZoneLayout::processRpnMessage (MidiRPNMessage rpn)
|
||||
{
|
||||
if (rpn.parameterNumber == MPEMessages::zoneLayoutMessagesRpnNumber)
|
||||
processZoneLayoutRpnMessage (rpn);
|
||||
else if (rpn.parameterNumber == 0)
|
||||
processPitchbendRangeRpnMessage (rpn);
|
||||
}
|
||||
|
||||
void MPEZoneLayout::processZoneLayoutRpnMessage (MidiRPNMessage rpn)
|
||||
{
|
||||
if (rpn.value < 16)
|
||||
{
|
||||
if (rpn.channel == 1)
|
||||
setLowerZone (rpn.value);
|
||||
else if (rpn.channel == 16)
|
||||
setUpperZone (rpn.value);
|
||||
}
|
||||
}
|
||||
|
||||
void MPEZoneLayout::updateMasterPitchbend (MPEZone& zone, int value)
|
||||
{
|
||||
if (zone.masterPitchbendRange != value)
|
||||
{
|
||||
checkAndLimitZoneParameters (0, 96, zone.masterPitchbendRange);
|
||||
zone.masterPitchbendRange = value;
|
||||
sendLayoutChangeMessage();
|
||||
}
|
||||
}
|
||||
|
||||
void MPEZoneLayout::updatePerNotePitchbendRange (MPEZone& zone, int value)
|
||||
{
|
||||
if (zone.perNotePitchbendRange != value)
|
||||
{
|
||||
checkAndLimitZoneParameters (0, 96, zone.perNotePitchbendRange);
|
||||
zone.perNotePitchbendRange = value;
|
||||
sendLayoutChangeMessage();
|
||||
}
|
||||
}
|
||||
|
||||
void MPEZoneLayout::processPitchbendRangeRpnMessage (MidiRPNMessage rpn)
|
||||
{
|
||||
// When the range is specified using both MSB and LSB, then MSB corresponds to whole semitones
|
||||
// and LSB corresponds to cents.
|
||||
const auto range = rpn.is14BitValue
|
||||
? std::div (rpn.value, 128)
|
||||
: div_t { rpn.value, 0 };
|
||||
|
||||
// If this is hit, the requested pitchbend range is not a whole number of semitones.
|
||||
// This isn't currently supported by JUCE - adding support would require
|
||||
// public API updates.
|
||||
jassert (range.rem == 0);
|
||||
|
||||
if (rpn.channel == 1)
|
||||
{
|
||||
updateMasterPitchbend (lowerZone, range.quot);
|
||||
}
|
||||
else if (rpn.channel == 16)
|
||||
{
|
||||
updateMasterPitchbend (upperZone, range.quot);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (lowerZone.isUsingChannelAsMemberChannel (rpn.channel))
|
||||
updatePerNotePitchbendRange (lowerZone, range.quot);
|
||||
else if (upperZone.isUsingChannelAsMemberChannel (rpn.channel))
|
||||
updatePerNotePitchbendRange (upperZone, range.quot);
|
||||
}
|
||||
}
|
||||
|
||||
void MPEZoneLayout::processNextMidiBuffer (const MidiBuffer& buffer)
|
||||
{
|
||||
for (const auto metadata : buffer)
|
||||
processNextMidiEvent (metadata.getMessage());
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEZoneLayout::addListener (Listener* const listenerToAdd) noexcept
|
||||
{
|
||||
listeners.add (listenerToAdd);
|
||||
}
|
||||
|
||||
void MPEZoneLayout::removeListener (Listener* const listenerToRemove) noexcept
|
||||
{
|
||||
listeners.remove (listenerToRemove);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void MPEZoneLayout::checkAndLimitZoneParameters (int minValue, int maxValue,
|
||||
int& valueToCheckAndLimit) noexcept
|
||||
{
|
||||
if (valueToCheckAndLimit < minValue || valueToCheckAndLimit > maxValue)
|
||||
{
|
||||
// if you hit this, one of the parameters you supplied for this zone
|
||||
// was not within the allowed range!
|
||||
// we fit this back into the allowed range here to maintain a valid
|
||||
// state for the zone, but probably the resulting zone is not what you
|
||||
// wanted it to be!
|
||||
jassertfalse;
|
||||
|
||||
valueToCheckAndLimit = jlimit (minValue, maxValue, valueToCheckAndLimit);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool MPEZone::operator== (const MPEZone& other) const
|
||||
{
|
||||
const auto tie = [] (auto& x)
|
||||
{
|
||||
return std::tie (x.zoneType,
|
||||
x.numMemberChannels,
|
||||
x.perNotePitchbendRange,
|
||||
x.masterPitchbendRange);
|
||||
};
|
||||
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool MPEZone::operator!= (const MPEZone& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class MPEZoneLayoutTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
MPEZoneLayoutTests()
|
||||
: UnitTest ("MPEZoneLayout class", UnitTestCategories::midi)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("initialisation");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
expect (! layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
}
|
||||
|
||||
beginTest ("adding zones");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
|
||||
layout.setLowerZone (7);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 7);
|
||||
|
||||
layout.setUpperZone (7);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 7);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 7);
|
||||
|
||||
layout.setLowerZone (3);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 3);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 7);
|
||||
|
||||
layout.setUpperZone (3);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 3);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 3);
|
||||
|
||||
layout.setLowerZone (15);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 15);
|
||||
}
|
||||
|
||||
beginTest ("clear all zones");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
|
||||
expect (! layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
|
||||
layout.setLowerZone (7);
|
||||
layout.setUpperZone (2);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
|
||||
layout.clearAllZones();
|
||||
|
||||
expect (! layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
}
|
||||
|
||||
beginTest ("process MIDI buffers");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
MidiBuffer buffer;
|
||||
|
||||
buffer = MPEMessages::setLowerZone (7);
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 7);
|
||||
|
||||
buffer = MPEMessages::setUpperZone (7);
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 7);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 7);
|
||||
|
||||
{
|
||||
buffer = MPEMessages::setLowerZone (10);
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 10);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 4);
|
||||
|
||||
|
||||
buffer = MPEMessages::setLowerZone (10, 33, 44);
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 10);
|
||||
expectEquals (layout.getLowerZone().perNotePitchbendRange, 33);
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, 44);
|
||||
}
|
||||
|
||||
{
|
||||
buffer = MPEMessages::setUpperZone (10);
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 4);
|
||||
expectEquals (layout.getUpperZone().getMasterChannel(), 16);
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 10);
|
||||
|
||||
buffer = MPEMessages::setUpperZone (10, 33, 44);
|
||||
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expectEquals (layout.getUpperZone().numMemberChannels, 10);
|
||||
expectEquals (layout.getUpperZone().perNotePitchbendRange, 33);
|
||||
expectEquals (layout.getUpperZone().masterPitchbendRange, 44);
|
||||
}
|
||||
|
||||
buffer = MPEMessages::clearAllZones();
|
||||
layout.processNextMidiBuffer (buffer);
|
||||
|
||||
expect (! layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
}
|
||||
|
||||
beginTest ("process individual MIDI messages");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
|
||||
layout.processNextMidiEvent ({ 0x80, 0x59, 0xd0 }); // unrelated note-off msg
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x64, 0x06 }); // RPN part 1
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x65, 0x00 }); // RPN part 2
|
||||
layout.processNextMidiEvent ({ 0xb8, 0x0b, 0x66 }); // unrelated CC msg
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x06, 0x03 }); // RPN part 3
|
||||
layout.processNextMidiEvent ({ 0x90, 0x60, 0x00 }); // unrelated note-on msg
|
||||
|
||||
expect (layout.getLowerZone().isActive());
|
||||
expect (! layout.getUpperZone().isActive());
|
||||
expectEquals (layout.getLowerZone().getMasterChannel(), 1);
|
||||
expectEquals (layout.getLowerZone().numMemberChannels, 3);
|
||||
expectEquals (layout.getLowerZone().perNotePitchbendRange, 48);
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, 2);
|
||||
|
||||
const auto masterPitchBend = 0x0c;
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x64, 0x00 });
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x06, masterPitchBend });
|
||||
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, masterPitchBend);
|
||||
|
||||
const auto newPitchBend = 0x0d;
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x06, newPitchBend });
|
||||
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, newPitchBend);
|
||||
}
|
||||
|
||||
beginTest ("process 14-bit pitch bend sensitivity");
|
||||
{
|
||||
MPEZoneLayout layout;
|
||||
layout.setLowerZone (15);
|
||||
expect (layout.getLowerZone().isActive());
|
||||
|
||||
constexpr auto masterPitchBendA = 0x60;
|
||||
|
||||
// LSB first
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x64, 0x00 }); // RPN part 1
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x65, 0x00 }); // PRN part 2
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x26, 0x00 }); // pitch bend cents
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x06, masterPitchBendA }); // pitch bend semis
|
||||
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, masterPitchBendA);
|
||||
|
||||
constexpr auto masterPitchBendB = 0x50;
|
||||
|
||||
// MSB first
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x64, 0x00 }); // RPN part 1
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x65, 0x00 }); // PRN part 2
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x06, masterPitchBendB }); // pitch bend semis
|
||||
layout.processNextMidiEvent ({ 0xb0, 0x26, 0x00 }); // pitch bend cents
|
||||
|
||||
expectEquals (layout.getLowerZone().masterPitchbendRange, masterPitchBendB);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static MPEZoneLayoutTests MPEZoneLayoutUnitTests;
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
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
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This struct represents an MPE zone.
|
||||
|
||||
It can either be a lower or an upper zone, where:
|
||||
- A lower zone encompasses master channel 1 and an arbitrary number of ascending
|
||||
MIDI channels, increasing from channel 2.
|
||||
- An upper zone encompasses master channel 16 and an arbitrary number of descending
|
||||
MIDI channels, decreasing from channel 15.
|
||||
|
||||
It also defines a pitchbend range (in semitones) to be applied for per-note pitchbends and
|
||||
master pitchbends, respectively.
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
struct MPEZone
|
||||
{
|
||||
enum class Type { lower, upper };
|
||||
|
||||
MPEZone() = default;
|
||||
|
||||
MPEZone (Type type, int memberChannels = 0, int perNotePitchbend = 48, int masterPitchbend = 2)
|
||||
: zoneType (type),
|
||||
numMemberChannels (memberChannels),
|
||||
perNotePitchbendRange (perNotePitchbend),
|
||||
masterPitchbendRange (masterPitchbend)
|
||||
{}
|
||||
|
||||
bool isLowerZone() const noexcept { return zoneType == Type::lower; }
|
||||
bool isUpperZone() const noexcept { return zoneType == Type::upper; }
|
||||
|
||||
bool isActive() const noexcept { return numMemberChannels > 0; }
|
||||
|
||||
int getMasterChannel() const noexcept { return isLowerZone() ? lowerZoneMasterChannel : upperZoneMasterChannel; }
|
||||
int getFirstMemberChannel() const noexcept { return isLowerZone() ? lowerZoneMasterChannel + 1 : upperZoneMasterChannel - 1; }
|
||||
int getLastMemberChannel() const noexcept { return isLowerZone() ? (lowerZoneMasterChannel + numMemberChannels)
|
||||
: (upperZoneMasterChannel - numMemberChannels); }
|
||||
|
||||
bool isUsingChannelAsMemberChannel (int channel) const noexcept
|
||||
{
|
||||
return isLowerZone() ? (lowerZoneMasterChannel < channel && channel <= getLastMemberChannel())
|
||||
: (channel < upperZoneMasterChannel && getLastMemberChannel() <= channel);
|
||||
}
|
||||
|
||||
bool isUsing (int channel) const noexcept
|
||||
{
|
||||
return isActive()
|
||||
&& (channel == getMasterChannel() || isUsingChannelAsMemberChannel (channel));
|
||||
}
|
||||
|
||||
bool operator== (const MPEZone& other) const;
|
||||
bool operator!= (const MPEZone& other) const;
|
||||
|
||||
//==============================================================================
|
||||
static constexpr int lowerZoneMasterChannel = 1,
|
||||
upperZoneMasterChannel = 16;
|
||||
|
||||
Type zoneType = Type::lower;
|
||||
|
||||
int numMemberChannels = 0;
|
||||
int perNotePitchbendRange = 48;
|
||||
int masterPitchbendRange = 2;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
This class represents the current MPE zone layout of a device capable of handling MPE.
|
||||
|
||||
An MPE device can have up to two zones: a lower zone with master channel 1 and
|
||||
allocated MIDI channels increasing from channel 2, and an upper zone with master
|
||||
channel 16 and allocated MIDI channels decreasing from channel 15. MPE mode is
|
||||
enabled on a device when one of these zones is active and disabled when both
|
||||
are inactive.
|
||||
|
||||
Use the MPEMessages helper class to convert the zone layout represented
|
||||
by this object to MIDI message sequences that you can send to an Expressive
|
||||
MIDI device to set its zone layout, add zones etc.
|
||||
|
||||
@see MPEInstrument
|
||||
|
||||
@tags{Audio}
|
||||
*/
|
||||
class JUCE_API MPEZoneLayout
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a layout with inactive upper and lower zones. */
|
||||
MPEZoneLayout() = default;
|
||||
|
||||
/** Creates a layout with the given upper and lower zones. */
|
||||
MPEZoneLayout (MPEZone lower, MPEZone upper);
|
||||
|
||||
/** Creates a layout with a single upper or lower zone, leaving the other zone uninitialised. */
|
||||
MPEZoneLayout (MPEZone singleZone);
|
||||
|
||||
MPEZoneLayout (const MPEZoneLayout& other);
|
||||
MPEZoneLayout& operator= (const MPEZoneLayout& other);
|
||||
|
||||
bool operator== (const MPEZoneLayout& other) const { return lowerZone == other.lowerZone && upperZone == other.upperZone; }
|
||||
bool operator!= (const MPEZoneLayout& other) const { return ! operator== (other); }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a struct representing the lower MPE zone. */
|
||||
MPEZone getLowerZone() const noexcept { return lowerZone; }
|
||||
|
||||
/** Returns a struct representing the upper MPE zone. */
|
||||
MPEZone getUpperZone() const noexcept { return upperZone; }
|
||||
|
||||
/** Sets the lower zone of this layout. */
|
||||
void setLowerZone (int numMemberChannels = 0,
|
||||
int perNotePitchbendRange = 48,
|
||||
int masterPitchbendRange = 2) noexcept;
|
||||
|
||||
/** Sets the upper zone of this layout. */
|
||||
void setUpperZone (int numMemberChannels = 0,
|
||||
int perNotePitchbendRange = 48,
|
||||
int masterPitchbendRange = 2) noexcept;
|
||||
|
||||
/** Clears the lower and upper zones of this layout, making them both inactive
|
||||
and disabling MPE mode.
|
||||
*/
|
||||
void clearAllZones();
|
||||
|
||||
/** Returns true if either of the zones are active. */
|
||||
bool isActive() const { return lowerZone.isActive() || upperZone.isActive(); }
|
||||
|
||||
//==============================================================================
|
||||
/** Pass incoming MIDI messages to an object of this class if you want the
|
||||
zone layout to properly react to MPE RPN messages like an
|
||||
MPE device.
|
||||
|
||||
MPEMessages::rpnNumber will add or remove zones; RPN 0 will
|
||||
set the per-note or master pitchbend ranges.
|
||||
|
||||
Any other MIDI messages will be ignored by this class.
|
||||
|
||||
@see MPEMessages
|
||||
*/
|
||||
void processNextMidiEvent (const MidiMessage& message);
|
||||
|
||||
/** Pass incoming MIDI buffers to an object of this class if you want the
|
||||
zone layout to properly react to MPE RPN messages like an
|
||||
MPE device.
|
||||
|
||||
MPEMessages::rpnNumber will add or remove zones; RPN 0 will
|
||||
set the per-note or master pitchbend ranges.
|
||||
|
||||
Any other MIDI messages will be ignored by this class.
|
||||
|
||||
@see MPEMessages
|
||||
*/
|
||||
void processNextMidiBuffer (const MidiBuffer& buffer);
|
||||
|
||||
//==============================================================================
|
||||
/** Listener class. Derive from this class to allow your class to be
|
||||
notified about changes to the zone layout.
|
||||
*/
|
||||
class Listener
|
||||
{
|
||||
public:
|
||||
/** Destructor. */
|
||||
virtual ~Listener() = default;
|
||||
|
||||
/** Implement this callback to be notified about any changes to this
|
||||
MPEZoneLayout. Will be called whenever a zone is added, zones are
|
||||
removed, or any zone's master or note pitchbend ranges change.
|
||||
*/
|
||||
virtual void zoneLayoutChanged (const MPEZoneLayout& layout) = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a listener. */
|
||||
void addListener (Listener* const listenerToAdd) noexcept;
|
||||
|
||||
/** Removes a listener. */
|
||||
void removeListener (Listener* const listenerToRemove) noexcept;
|
||||
|
||||
/** @cond */
|
||||
using Zone = MPEZone;
|
||||
/** @endcond */
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
MPEZone lowerZone { MPEZone::Type::lower, 0 };
|
||||
MPEZone upperZone { MPEZone::Type::upper, 0 };
|
||||
|
||||
MidiRPNDetector rpnDetector;
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
//==============================================================================
|
||||
void setZone (bool, int, int, int) noexcept;
|
||||
|
||||
void processRpnMessage (MidiRPNMessage);
|
||||
void processZoneLayoutRpnMessage (MidiRPNMessage);
|
||||
void processPitchbendRangeRpnMessage (MidiRPNMessage);
|
||||
|
||||
void updateMasterPitchbend (MPEZone&, int);
|
||||
void updatePerNotePitchbendRange (MPEZone&, int);
|
||||
|
||||
void sendLayoutChangeMessage();
|
||||
void checkAndLimitZoneParameters (int, int, int&) noexcept;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user