hydrogen 1.2.3
AudioEngine Class Reference

The audio engine deals with two distinct #TransportPosition. More...

#include <AudioEngine.h>

Inheritance diagram for AudioEngine:
Object< AudioEngine > Base

Data Structures

struct  _locker_struct
 
struct  compare_pNotes
 Song Note FIFO. More...
 

Public Types

enum class  State {
  Uninitialized = 1 , Initialized = 2 , Prepared = 3 , Ready = 4 ,
  Playing = 5 , Testing = 6
}
 

Public Member Functions

 AudioEngine ()
 
 ~AudioEngine ()
 
void assertLocked ()
 Assert that the calling thread is the current holder of the AudioEngine lock.
 
void clearNextPatterns ()
 
AudioOutputcreateAudioDriver (const QString &sDriver)
 Create an audio driver using audioEngine_process() as its argument based on the provided choice and calling their init() function to trigger their initialization.
 
void flushAndAddNextPattern (int nPatternNumber)
 Add pattern nPatternNumber to #m_pNextPatterns as well as the whole content of #m_pPlayingPatterns.
 
AudioOutputgetAudioDriver () const
 
float getElapsedTime () const
 
int getEnqueuedNotesNumber () const
 Returns the size of m_songNoteQueue.
 
long long getLeadLagInFrames (double fTick)
 Calculates lead lag factor (in frames) relative to the transport position fTick.
 
float getMasterPeak_L () const
 
float getMasterPeak_R () const
 
float getMaxProcessTime () const
 
std::shared_ptr< InstrumentgetMetronomeInstrument () const
 
MidiInputgetMidiDriver () const
 
MidiOutputgetMidiOutDriver () const
 
float getNextBpm () const
 
const PatternListgetNextPatterns () const
 
const PatternListgetPlayingPatterns () const
 
float getProcessTime () const
 
long long getRealtimeFrame () const
 
SamplergetSampler () const
 
double getSongSizeInTicks () const
 
State getState () const
 
const QStringList getSupportedAudioDrivers () const
 
SynthgetSynth () const
 
const std::shared_ptr< TransportPositiongetTransportPosition () const
 
void lock (const char *file, unsigned int line, const char *function)
 Mutex locking of the AudioEngine.
 
void noteOn (Note *note)
 
void play ()
 Marks the audio engine to be started during the next call of the audioEngine_process() callback function.
 
void raiseError (unsigned nErrorCode)
 
void removePlayingPattern (Pattern *pPattern)
 
void renameJackPorts (std::shared_ptr< Song > pSong)
 Hands the provided Song to JackAudioDriver::makeTrackOutputs() if pSong is not a null pointer and the audio driver m_pAudioDriver is an instance of the JackAudioDriver.
 
void restartAudioDrivers ()
 
void setMasterPeak_L (float value)
 
void setMasterPeak_R (float value)
 
void setNextBpm (float fNextBpm)
 Stores the new speed into a separate variable which will be adopted during the next processing cycle.
 
void setupLadspaFX ()
 
void startAudioDrivers ()
 Creation and initialization of all audio and MIDI drivers called in Hydrogen::Hydrogen().
 
void stop ()
 Marks the audio engine to be stopped during the next call of the audioEngine_process() callback function.
 
void stopAudioDrivers ()
 Stops all audio and MIDI drivers.
 
void toggleNextPattern (int nPatternNumber)
 Add pattern nPatternNumber to #m_pNextPatterns or deletes it in case it is already present.
 
QString toQString (const QString &sPrefix="", bool bShort=true) const override
 Formatted string version for debugging purposes.
 
bool tryLock (const char *file, unsigned int line, const char *function)
 Mutex locking of the AudioEngine.
 
bool tryLockFor (std::chrono::microseconds duration, const char *file, unsigned int line, const char *function)
 Mutex locking of the AudioEngine.
 
void unlock ()
 Mutex unlocking of the AudioEngine.
 
void updatePlayingPatterns ()
 Update the list of currently played patterns associated with m_pTransportPosition and m_pQueuingPosition.
 
void updateSongSize ()
 Function to be called every time the length of the current song does change, e.g.
 
void updateVirtualPatterns ()
 
- Public Member Functions inherited from Object< AudioEngine >
 Object ()
 
 Object (const Object< AudioEngine > &other)
 
- Public Member Functions inherited from Base
 Base ()
 
 Base (const Base &other)
 
virtual const char * class_name () const
 
void Print (bool bShort=true) const
 Prints content of toQString() via DEBUGLOG.
 

Static Public Member Functions

static int audioEngine_process (uint32_t nframes, void *arg)
 Main audio processing function called by the audio drivers whenever there is work to do.
 
static double computeDoubleTickSize (const int nSampleRate, const float fBpm, const int nResolution)
 
static float computeTickSize (const int nSampleRate, const float fBpm, const int nResolution)
 Calculates the number of frames that make up a tick.
 
static float getBpmAtColumn (int nColumn)
 
static double getLeadLagInTicks ()
 Maximum lead lag factor in ticks.
 
- Static Public Member Functions inherited from Base
static const char * _class_name ()
 return the class name
 
static QString base_clock (const QString &sMsg)
 Measures the current time and stores it in __last_clock.
 
static QString base_clock_in (const QString &sMsg)
 
static int bootstrap (Logger *logger, bool count=false)
 must be called before any Object instantiation !
 
static bool count_active ()
 
static int getAliveObjectCount ()
 
static object_map_t getObjectMap ()
 
static Loggerlogger ()
 return the logger instance
 
static int objects_count ()
 
static void printObjectMapDiff (object_map_t map)
 Creates the difference between a snapshot of the object map and its current state and prints it to std::cout.
 
static void set_count (bool flag)
 enable/disable class instances counting
 
static void write_objects_map_to (std::ostream &out, object_map_t *map=nullptr)
 output the full objects map to a given ostream
 
static void write_objects_map_to_cerr ()
 output objects map to stderr
 

Static Public Attributes

static constexpr float fHumanizePitchSD = 0.4
 Maximum value the standard deviation of the Gaussian distribution the random pitch contribution will be drawn from can take.
 
static constexpr float fHumanizeTimingSD = 0.3
 Maximum value the standard deviation of the Gaussian distribution the random pitch contribution will be drawn from can take.
 
static constexpr float fHumanizeVelocitySD = 0.2
 Maximum value the standard deviation of the Gaussian distribution the random velocity contribution will be drawn from can take.
 
static constexpr int nMaxTimeHumanize = 2000
 Maximum time (in frames) a note's position can be off due to the humanization (lead-lag).
 
- Static Public Attributes inherited from Base
static QString sPrintIndention = " "
 String used to format the debugging string output of some core classes.
 

Private Member Functions

void calculateTransportOffsetOnBpmChange (std::shared_ptr< TransportPosition > pTransportPosition)
 
void checkJackSupport ()
 Attempts to dynamically load the JACK 2 shared library and stores the result in m_bJackSupported.
 
void clearAudioBuffers (uint32_t nFrames)
 Clear all audio buffers.
 
void clearNoteQueues ()
 
double coarseGrainTick (double fTick)
 Ideally we just floor the provided tick.
 
long long computeTickInterval (double *fTickStart, double *fTickEnd, unsigned nIntervalLengthInFrames)
 
State getNextState () const
 
void handleDriverChange ()
 The audio driver was changed what possible changed the tick size - which depends on both the sample rate - too.
 
void handleLoopModeChanged ()
 In order to properly support H2Core::Song::LoopMode::Finishing - transport was already looped a couple of times and the user is pressing the loop button again to deactivate loop mode - we have to capture the number of loops already applied.
 
void handleSelectedPattern ()
 Keeps the selected pattern in line with the one the transport position resides in while in Song::Mode::Song.
 
void handleSongModeChanged ()
 Called whenever Hydrogen switches from Song::Mode::Song into Song::Mode::Pattern or the other way around.
 
void handleSongSizeChange ()
 Updates all notes in m_songNoteQueue to be still valid after a change in song size.
 
void handleTempoChange ()
 Updates all notes in m_songNoteQueue and m_midiNoteQueue to be still valid after a tempo change.
 
void handleTimelineChange ()
 Updates the transport states and all notes in m_songNoteQueue and m_midiNoteQueue after adding or deleting a TempoMarker or enabling/disabling the #Timeline.
 
void incrementTransportPosition (uint32_t nFrames)
 
bool isEndOfSongReached (std::shared_ptr< TransportPosition > pPos) const
 
void locate (const double fTick, bool bWithJackBroadcast=true)
 
void locateToFrame (const long long nFrame)
 Version of the locate() function intended to be directly used by frame-based audio drivers / servers.
 
void processAudio (uint32_t nFrames)
 
void processPlayNotes (unsigned long nframes)
 
void removeSong ()
 
void reset (bool bWithJackBroadcast=true)
 
void resetOffsets ()
 
void setNextState (State state)
 
void setRealtimeFrame (long long nFrame)
 
void setSong (std::shared_ptr< Song >pNewSong)
 
void setState (State state)
 
void startPlayback ()
 
void stopPlayback ()
 
void updateBpmAndTickSize (std::shared_ptr< TransportPosition > pTransportPosition)
 
void updateNoteQueue (unsigned nIntervalLengthInFrames)
 Takes all notes from the currently playing patterns, from the MIDI queue m_midiNoteQueue, and those triggered by the metronome and pushes them onto m_songNoteQueue for playback.
 
void updatePatternTransportPosition (double fTick, long long nFrame, std::shared_ptr< TransportPosition > pPos)
 
void updatePlayingPatternsPos (std::shared_ptr< TransportPosition > pPos)
 
void updateSongTransportPosition (double fTick, long long nFrame, std::shared_ptr< TransportPosition > pPos)
 
void updateTransportPosition (double fTick, long long nFrame, std::shared_ptr< TransportPosition > pPos)
 

Private Attributes

audioProcessCallback m_AudioProcessCallback
 
bool m_bJackSupported
 Whether or not the shared library of the JACK server could be found on the system at runtime.
 
bool m_bLookaheadApplied
 
std::timed_mutex m_EngineMutex
 Mutex for synchronizing the access to the Song object and the AudioEngine.
 
float m_fFXPeak_L [MAX_FX]
 
float m_fFXPeak_R [MAX_FX]
 
float m_fLadspaTime
 
double m_fLastTickEnd
 
float m_fMasterPeak_L
 
float m_fMasterPeak_R
 
float m_fMaxProcessTime
 
float m_fNextBpm
 
float m_fProcessTime
 
double m_fSongSizeInTicks
 Set to the total number of ticks in a Song.
 
std::thread::id m_LockingThread
 Thread ID of the current holder of the AudioEngine lock.
 
std::deque< Note * > m_midiNoteQueue
 Midi Note FIFO.
 
QMutex m_MutexOutputPointer
 Mutex for locking the pointer to the audio output buffer, allowing multiple readers.
 
State m_nextState
 State assigned during the next call to processTransport().
 
int m_nLoopsDone
 Indicates how many loops the transport already did when the user presses the Loop button again.
 
long long m_nRealtimeFrame
 Variable keeping track of the transport position in realtime.
 
AudioOutputm_pAudioDriver
 
EventQueuem_pEventQueue
 
struct H2Core::AudioEngine::_locker_struct m_pLocker
 
std::shared_ptr< Instrumentm_pMetronomeInstrument
 Pointer to the metronome.
 
MidiInputm_pMidiDriver
 
MidiOutputm_pMidiDriverOut
 
std::shared_ptr< TransportPositionm_pQueuingPosition
 
Samplerm_pSampler
 
Synthm_pSynth
 
std::shared_ptr< TransportPositionm_pTransportPosition
 
std::priority_queue< Note *, std::deque< Note * >, compare_pNotesm_songNoteQueue
 
State m_state
 Current state of the H2Core::AudioEngine.
 
QStringList m_supportedAudioDrivers
 

Friends

class AudioEngineTests
 
bool CoreActionController::activateLoopMode (bool)
 
bool CoreActionController::activateSongMode (bool)
 
bool CoreActionController::addTempoMarker (int, float)
 Uses handleTimelineChange()
 
bool CoreActionController::deleteTempoMarker (int)
 Uses handleTimelineChange()
 
bool CoreActionController::locateToTick (long nTick, bool)
 
int FakeDriver::connect ()
 Is allowed to set m_state to State::Ready via setState()
 
void Hydrogen::removeSong ()
 Is allowed to call removeSong().
 
void Hydrogen::setIsTimelineActivated (bool)
 Uses handleTimelineChange()
 
void Hydrogen::setSong (std::shared_ptr< Song > pSong, bool bRelinking)
 Is allowed to call setSong().
 
void Hydrogen::updateSelectedPattern (bool)
 Is allowed to use locate() to directly set the position in frames as well as to used setColumn and setPatternTickPos to move the arrow in the SongEditorPositionRuler even when playback is stopped.
 
void JackAudioDriver::relocateUsingBBT ()
 
void JackAudioDriver::updateTransportPosition ()
 

Additional Inherited Members

- Protected Member Functions inherited from Object< AudioEngine >
 ~Object ()
 
- Protected Member Functions inherited from Base
 ~Base ()
 
- Static Protected Member Functions inherited from Base
static void registerClass (const char *name, const atomic_obj_cpt_t *counters)
 
- Static Protected Attributes inherited from Base
static bool __count = false
 should we count class instances
 
static timeval __last_clock = { 0, 0 }
 
static Logger__logger = nullptr
 

Detailed Description

The audio engine deals with two distinct #TransportPosition.

The first (and most important one) is m_pTransportPosition which indicated the current position of the audio rendering and playhead as well as all patterns associated with it. This is also the one other parts of Hydrogen are concerned with.

The second one is m_pQueuingPosition which is only used internally. It is one lookahead ahead of m_pTransportPosition, used for inserting notes into the song queue, and required in order to supported lead and lag of notes. Formerly, this second transport state was trimmed to a couple of variables making its update less expensive. However, this showed to be quite error prone as things tend to went out of sync.

All tick information (apart from note handling in updateNoteQueue()) are handled as double internally. But due to historical reasons the GUI and the remainder of the core only access a version of the current tick rounded to integer.

Definition at line 96 of file AudioEngine.h.

Member Enumeration Documentation

◆ State

enum class State
strong
Enumerator
Uninitialized 

Not even the constructors have been called.

Initialized 

Not ready, but most pointers are now valid or NULL.

Prepared 

Drivers are set up, but not ready to process audio.

Ready 

Ready to process audio.

Playing 

Transport is rolling.

Testing 

State used during the unit tests of the AudioEngine.

Transport is not rolling but when calling a function of the process cycle it is ensured all its code and subsequent functions will be executed.

Definition at line 101 of file AudioEngine.h.

Constructor & Destructor Documentation

◆ AudioEngine()

Definition at line 82 of file AudioEngine.cpp.

◆ ~AudioEngine()

Definition at line 177 of file AudioEngine.cpp.

Member Function Documentation

◆ assertLocked()

void assertLocked ( )
inline

Assert that the calling thread is the current holder of the AudioEngine lock.

Definition at line 757 of file AudioEngine.h.

◆ audioEngine_process()

int audioEngine_process ( uint32_t nframes,
void * arg )
static

Main audio processing function called by the audio drivers whenever there is work to do.

Parameters
nframesBuffersize.
argUnused.
Returns
  • 2 : Failed to acquire the audio engine lock, no processing took place.
  • 1 : kill the audio driver thread.
  • 0 : else

Definition at line 1313 of file AudioEngine.cpp.

◆ calculateTransportOffsetOnBpmChange()

void calculateTransportOffsetOnBpmChange ( std::shared_ptr< TransportPosition > pTransportPosition)
private

Definition at line 740 of file AudioEngine.cpp.

◆ checkJackSupport()

void checkJackSupport ( )
private

Attempts to dynamically load the JACK 2 shared library and stores the result in m_bJackSupported.

Definition at line 2634 of file AudioEngine.cpp.

◆ clearAudioBuffers()

void clearAudioBuffers ( uint32_t nFrames)
private

Clear all audio buffers.

Definition at line 784 of file AudioEngine.cpp.

◆ clearNextPatterns()

void clearNextPatterns ( )

Definition at line 2026 of file AudioEngine.cpp.

◆ clearNoteQueues()

void clearNoteQueues ( )
private

Definition at line 1298 of file AudioEngine.cpp.

◆ coarseGrainTick()

double coarseGrainTick ( double fTick)
private

Ideally we just floor the provided tick.

When relocating to a specific tick, it's converted counterpart is stored as the transport position in frames, which is then used to calculate the tick start again. These conversions back and forth can introduce rounding error that get larger for larger tick numbers and could result in a computed start tick of 86753.999999934 when transport was relocated to 86754. As we do not want to cover notes prior to our current transport position, we have to account for such rounding errors.

Definition at line 2309 of file AudioEngine.cpp.

◆ computeDoubleTickSize()

double computeDoubleTickSize ( const int nSampleRate,
const float fBpm,
const int nResolution )
static

Definition at line 377 of file AudioEngine.cpp.

◆ computeTickInterval()

long long computeTickInterval ( double * fTickStart,
double * fTickEnd,
unsigned nIntervalLengthInFrames )
private

Definition at line 2214 of file AudioEngine.cpp.

◆ computeTickSize()

float computeTickSize ( const int nSampleRate,
const float fBpm,
const int nResolution )
static

Calculates the number of frames that make up a tick.

Definition at line 370 of file AudioEngine.cpp.

◆ createAudioDriver()

AudioOutput * createAudioDriver ( const QString & sDriver)

Create an audio driver using audioEngine_process() as its argument based on the provided choice and calling their init() function to trigger their initialization.

For a listing of all possible choices, please see Preferences::m_sAudioDriver.

Parameters
sDriverString specifying which audio driver should be created.
Returns
Pointer to the freshly created audio driver. If the creation resulted in a NullDriver, the corresponding object will be deleted and a null pointer returned instead.

Definition at line 828 of file AudioEngine.cpp.

◆ flushAndAddNextPattern()

void flushAndAddNextPattern ( int nPatternNumber)

Add pattern nPatternNumber to #m_pNextPatterns as well as the whole content of #m_pPlayingPatterns.

After the next call to updatePlayingPatterns() only nPatternNumber will be left playing.

Definition at line 2031 of file AudioEngine.cpp.

◆ getAudioDriver()

AudioOutput * getAudioDriver ( ) const
inline

Definition at line 798 of file AudioEngine.h.

◆ getBpmAtColumn()

float getBpmAtColumn ( int nColumn)
static

Definition at line 1091 of file AudioEngine.cpp.

◆ getElapsedTime()

float getElapsedTime ( ) const
Returns
Time passed since the beginning of the song

Definition at line 386 of file AudioEngine.cpp.

◆ getEnqueuedNotesNumber()

int getEnqueuedNotesNumber ( ) const
inline

Returns the size of m_songNoteQueue.

Required to not end unit tests prematurely.

Definition at line 830 of file AudioEngine.h.

◆ getLeadLagInFrames()

long long getLeadLagInFrames ( double fTick)

Calculates lead lag factor (in frames) relative to the transport position fTick.

During the humanization the onset of a Note will be moved Note::__lead_lag times the value calculated by this function.

Definition at line 2604 of file AudioEngine.cpp.

◆ getLeadLagInTicks()

double getLeadLagInTicks ( )
static

Maximum lead lag factor in ticks.

During humanization the onset of a Note will be moved Note::__lead_lag times the value calculated by this function.

Definition at line 2600 of file AudioEngine.cpp.

◆ getMasterPeak_L()

float getMasterPeak_L ( ) const
inline

Definition at line 767 of file AudioEngine.h.

◆ getMasterPeak_R()

float getMasterPeak_R ( ) const
inline

Definition at line 775 of file AudioEngine.h.

◆ getMaxProcessTime()

float getMaxProcessTime ( ) const
inline

Definition at line 783 of file AudioEngine.h.

◆ getMetronomeInstrument()

std::shared_ptr< Instrument > getMetronomeInstrument ( ) const
inline

Definition at line 827 of file AudioEngine.h.

◆ getMidiDriver()

MidiInput * getMidiDriver ( ) const
inline

Definition at line 802 of file AudioEngine.h.

◆ getMidiOutDriver()

MidiOutput * getMidiOutDriver ( ) const
inline

Definition at line 806 of file AudioEngine.h.

◆ getNextBpm()

float getNextBpm ( ) const
inline

Definition at line 818 of file AudioEngine.h.

◆ getNextPatterns()

const PatternList * getNextPatterns ( ) const

Definition at line 2627 of file AudioEngine.cpp.

◆ getNextState()

AudioEngine::State getNextState ( ) const
inlineprivate

Definition at line 791 of file AudioEngine.h.

◆ getPlayingPatterns()

const PatternList * getPlayingPatterns ( ) const

Definition at line 2620 of file AudioEngine.cpp.

◆ getProcessTime()

float getProcessTime ( ) const
inline

Definition at line 779 of file AudioEngine.h.

◆ getRealtimeFrame()

long long getRealtimeFrame ( ) const
inline

Definition at line 810 of file AudioEngine.h.

◆ getSampler()

Sampler * getSampler ( ) const

Definition at line 210 of file AudioEngine.cpp.

◆ getSongSizeInTicks()

double getSongSizeInTicks ( ) const
inline

Definition at line 824 of file AudioEngine.h.

◆ getState()

AudioEngine::State getState ( ) const
inline

Definition at line 787 of file AudioEngine.h.

◆ getSupportedAudioDrivers()

const QStringList getSupportedAudioDrivers ( ) const
inline

Definition at line 833 of file AudioEngine.h.

◆ getSynth()

Synth * getSynth ( ) const

Definition at line 216 of file AudioEngine.cpp.

◆ getTransportPosition()

const std::shared_ptr< TransportPosition > getTransportPosition ( ) const
inline

Definition at line 821 of file AudioEngine.h.

◆ handleDriverChange()

void handleDriverChange ( )
private

The audio driver was changed what possible changed the tick size - which depends on both the sample rate - too.

Thus, all frame-based variables might have become invalid.

Definition at line 1081 of file AudioEngine.cpp.

◆ handleLoopModeChanged()

void handleLoopModeChanged ( )
private

In order to properly support H2Core::Song::LoopMode::Finishing - transport was already looped a couple of times and the user is pressing the loop button again to deactivate loop mode - we have to capture the number of loops already applied.

Definition at line 1073 of file AudioEngine.cpp.

◆ handleSelectedPattern()

void handleSelectedPattern ( )
private

Keeps the selected pattern in line with the one the transport position resides in while in Song::Mode::Song.

If multiple patterns are present in the current column, the pattern recorded notes will be inserted in (bottom-most one) will be used.

Definition at line 1165 of file AudioEngine.cpp.

◆ handleSongModeChanged()

void handleSongModeChanged ( )
private

Called whenever Hydrogen switches from Song::Mode::Song into Song::Mode::Pattern or the other way around.

Definition at line 1199 of file AudioEngine.cpp.

◆ handleSongSizeChange()

void handleSongSizeChange ( )
private

Updates all notes in m_songNoteQueue to be still valid after a change in song size.

Definition at line 2157 of file AudioEngine.cpp.

◆ handleTempoChange()

void handleTempoChange ( )
private

Updates all notes in m_songNoteQueue and m_midiNoteQueue to be still valid after a tempo change.

Definition at line 2125 of file AudioEngine.cpp.

◆ handleTimelineChange()

void handleTimelineChange ( )
private

Updates the transport states and all notes in m_songNoteQueue and m_midiNoteQueue after adding or deleting a TempoMarker or enabling/disabling the #Timeline.

If the #Timeline is activated, adding or removing a TempoMarker does effectively has the same effects as a relocation with respect to the transport position in frames. It's tick counterpart, however, is not affected. This function ensures they are in sync again.

Definition at line 2092 of file AudioEngine.cpp.

◆ incrementTransportPosition()

void incrementTransportPosition ( uint32_t nFrames)
private

Definition at line 483 of file AudioEngine.cpp.

◆ isEndOfSongReached()

bool isEndOfSongReached ( std::shared_ptr< TransportPosition > pPos) const
private

Definition at line 508 of file AudioEngine.cpp.

◆ locate()

void locate ( const double fTick,
bool bWithJackBroadcast = true )
private

Definition at line 400 of file AudioEngine.cpp.

◆ locateToFrame()

void locateToFrame ( const long long nFrame)
private

Version of the locate() function intended to be directly used by frame-based audio drivers / servers.

Parameters
nFrameNext position in frames. If the provided number is larger than the song length and loop mode is enabled, computeTickFromFrame() will wrap it.

Definition at line 430 of file AudioEngine.cpp.

◆ lock()

void lock ( const char * file,
unsigned int line,
const char * function )

Mutex locking of the AudioEngine.

Lock the AudioEngine for exclusive access by this thread.

Easy usage: Use the RIGHT_HERE macro like this...

AudioEngine::get_instance()->lock( RIGHT_HERE );
#define RIGHT_HERE
Macro intended to be used for the logging of the locking of the H2Core::AudioEngine.
Definition AudioEngine.h:59

More complex usage: The parameters file and function need to be pointers to null-terminated strings that are persistent for the entire session. This does not include the return value of std::string::c_str(), or QString::toLocal8Bit().data().

Tracing the locks: Enable the Logger::AELockTracing logging level. When you do, there will be a performance penalty because the strings will be converted to a QString. At the moment, you'll have to do that with your debugger.

Notes: The order of the parameters match GCC's implementation of the assert() macros.

Parameters
fileFile the locking occurs in.
lineLine of the file the locking occurs in.
functionFunction the locking occurs in.

Definition at line 222 of file AudioEngine.cpp.

◆ noteOn()

void noteOn ( Note * note)

Definition at line 2547 of file AudioEngine.cpp.

◆ play()

void play ( )

Marks the audio engine to be started during the next call of the audioEngine_process() callback function.

If the JACK audio driver is used, a request to start transport is send to the JACK server instead.

Definition at line 2565 of file AudioEngine.cpp.

◆ processAudio()

void processAudio ( uint32_t nFrames)
private

Definition at line 1479 of file AudioEngine.cpp.

◆ processPlayNotes()

void processPlayNotes ( unsigned long nframes)
inlineprivate

Definition at line 1212 of file AudioEngine.cpp.

◆ raiseError()

void raiseError ( unsigned nErrorCode)

Definition at line 1160 of file AudioEngine.cpp.

◆ removePlayingPattern()

void removePlayingPattern ( Pattern * pPattern)

Definition at line 1886 of file AudioEngine.cpp.

◆ removeSong()

void removeSong ( )
private

Definition at line 1629 of file AudioEngine.cpp.

◆ renameJackPorts()

void renameJackPorts ( std::shared_ptr< Song > pSong)

Hands the provided Song to JackAudioDriver::makeTrackOutputs() if pSong is not a null pointer and the audio driver m_pAudioDriver is an instance of the JackAudioDriver.

Parameters
pSongSong for which per-track output ports should be generated.

◆ reset()

void reset ( bool bWithJackBroadcast = true)
private

Definition at line 331 of file AudioEngine.cpp.

◆ resetOffsets()

void resetOffsets ( )
private

Definition at line 466 of file AudioEngine.cpp.

◆ restartAudioDrivers()

void restartAudioDrivers ( )

Definition at line 1060 of file AudioEngine.cpp.

◆ setMasterPeak_L()

void setMasterPeak_L ( float value)
inline

Definition at line 763 of file AudioEngine.h.

◆ setMasterPeak_R()

void setMasterPeak_R ( float value)
inline

Definition at line 771 of file AudioEngine.h.

◆ setNextBpm()

void setNextBpm ( float fNextBpm)

Stores the new speed into a separate variable which will be adopted during the next processing cycle.

Setting this variable requires the audio engine to be locked! (Else, tempo handling within audioEngine_process() might be inconsistent and cause the playhead to glitch).

Definition at line 1577 of file AudioEngine.cpp.

◆ setNextState()

void setNextState ( AudioEngine::State state)
inlineprivate

Definition at line 794 of file AudioEngine.h.

◆ setRealtimeFrame()

void setRealtimeFrame ( long long nFrame)
inlineprivate

Definition at line 814 of file AudioEngine.h.

◆ setSong()

void setSong ( std::shared_ptr< Song > pNewSong)
private

Definition at line 1592 of file AudioEngine.cpp.

◆ setState()

void setState ( AudioEngine::State state)
private

Definition at line 1572 of file AudioEngine.cpp.

◆ setupLadspaFX()

void setupLadspaFX ( )

Definition at line 1136 of file AudioEngine.cpp.

◆ startAudioDrivers()

void startAudioDrivers ( )

Creation and initialization of all audio and MIDI drivers called in Hydrogen::Hydrogen().

Definition at line 942 of file AudioEngine.cpp.

◆ startPlayback()

void startPlayback ( )
private

Definition at line 304 of file AudioEngine.cpp.

◆ stop()

void stop ( )

Marks the audio engine to be stopped during the next call of the audioEngine_process() callback function.

If the JACK audio driver is used, a request to stop transport is send to the JACK server instead.

Definition at line 2585 of file AudioEngine.cpp.

◆ stopAudioDrivers()

void stopAudioDrivers ( )

Stops all audio and MIDI drivers.

Definition at line 1021 of file AudioEngine.cpp.

◆ stopPlayback()

void stopPlayback ( )
private

Definition at line 318 of file AudioEngine.cpp.

◆ toggleNextPattern()

void toggleNextPattern ( int nPatternNumber)

Add pattern nPatternNumber to #m_pNextPatterns or deletes it in case it is already present.

Definition at line 2009 of file AudioEngine.cpp.

◆ toQString()

QString toQString ( const QString & sPrefix = "",
bool bShort = true ) const
overridevirtual

Formatted string version for debugging purposes.

Parameters
sPrefixString prefix which will be added in front of every new line
bShortInstead of the whole content of all classes stored as members just a single unique identifier will be displayed without line breaks.
Returns
String presentation of current object.

Reimplemented from Base.

Definition at line 2665 of file AudioEngine.cpp.

◆ tryLock()

bool tryLock ( const char * file,
unsigned int line,
const char * function )

Mutex locking of the AudioEngine.

This function is equivalent to lock() but returns false immediaely if the lock cannot be obtained immediately.

Parameters
fileFile the locking occurs in.
lineLine of the file the locking occurs in.
functionFunction the locking occurs in.
Returns
  • true : On success
  • false : Else

Definition at line 238 of file AudioEngine.cpp.

◆ tryLockFor()

bool tryLockFor ( std::chrono::microseconds duration,
const char * file,
unsigned int line,
const char * function )

Mutex locking of the AudioEngine.

This function is equivalent to lock() but will only wait for a given period of time. If the lock cannot be acquired in this time, it will return false.

Parameters
durationTime (in microseconds) to wait for the lock.
fileFile the locking occurs in.
lineLine of the file the locking occurs in.
functionFunction the locking occurs in.
Returns
  • true : On successful acquisition of the lock
  • false : On failure

Definition at line 263 of file AudioEngine.cpp.

◆ unlock()

void unlock ( )

Mutex unlocking of the AudioEngine.

Unlocks the AudioEngine to allow other threads access, and leaves #__locker untouched.

Definition at line 292 of file AudioEngine.cpp.

◆ updateBpmAndTickSize()

void updateBpmAndTickSize ( std::shared_ptr< TransportPosition > pTransportPosition)
private

Definition at line 676 of file AudioEngine.cpp.

◆ updateNoteQueue()

void updateNoteQueue ( unsigned nIntervalLengthInFrames)
private

Takes all notes from the currently playing patterns, from the MIDI queue m_midiNoteQueue, and those triggered by the metronome and pushes them onto m_songNoteQueue for playback.

Definition at line 2319 of file AudioEngine.cpp.

◆ updatePatternTransportPosition()

void updatePatternTransportPosition ( double fTick,
long long nFrame,
std::shared_ptr< TransportPosition > pPos )
private

Definition at line 572 of file AudioEngine.cpp.

◆ updatePlayingPatterns()

void updatePlayingPatterns ( )

Update the list of currently played patterns associated with m_pTransportPosition and m_pQueuingPosition.

This works in three different ways.

  1. In case the song is in Song::Mode::Song when entering a new nColumn #m_pPlayingPatterns will be flushed and all patterns activated in the provided column will be added.
  2. While in Song::PatternMode::Selected the function ensures the currently selected pattern is the only pattern in #m_pPlayingPatterns.
  3. While in Song::PatterMode::Stacked all patterns in #m_pNextPatterns not already present in #m_pPlayingPatterns will be added in the latter and the ones already present will be removed.

Definition at line 1902 of file AudioEngine.cpp.

◆ updatePlayingPatternsPos()

void updatePlayingPatternsPos ( std::shared_ptr< TransportPosition > pPos)
private

Definition at line 1907 of file AudioEngine.cpp.

◆ updateSongSize()

void updateSongSize ( )

Function to be called every time the length of the current song does change, e.g.

by toggling a pattern or altering its length.

It will adjust both the current transport information as well as the note queues in order to prevent any glitches.

Definition at line 1652 of file AudioEngine.cpp.

◆ updateSongTransportPosition()

void updateSongTransportPosition ( double fTick,
long long nFrame,
std::shared_ptr< TransportPosition > pPos )
private

Definition at line 613 of file AudioEngine.cpp.

◆ updateTransportPosition()

void updateTransportPosition ( double fTick,
long long nFrame,
std::shared_ptr< TransportPosition > pPos )
private

Definition at line 522 of file AudioEngine.cpp.

◆ updateVirtualPatterns()

void updateVirtualPatterns ( )

Definition at line 2070 of file AudioEngine.cpp.

Friends And Related Symbol Documentation

◆ AudioEngineTests

friend class AudioEngineTests
friend

Definition at line 473 of file AudioEngine.h.

◆ CoreActionController::activateLoopMode

◆ CoreActionController::activateSongMode

◆ CoreActionController::addTempoMarker

◆ CoreActionController::deleteTempoMarker

◆ CoreActionController::locateToTick

bool CoreActionController::locateToTick ( long nTick,
bool  )
friend

◆ FakeDriver::connect

int FakeDriver::connect ( )
friend

Is allowed to set m_state to State::Ready via setState()

◆ Hydrogen::removeSong

void Hydrogen::removeSong ( )
friend

Is allowed to call removeSong().

◆ Hydrogen::setIsTimelineActivated

◆ Hydrogen::setSong

void Hydrogen::setSong ( std::shared_ptr< Song > pSong,
bool bRelinking )
friend

Is allowed to call setSong().

◆ Hydrogen::updateSelectedPattern

void Hydrogen::updateSelectedPattern ( bool )
friend

Is allowed to use locate() to directly set the position in frames as well as to used setColumn and setPatternTickPos to move the arrow in the SongEditorPositionRuler even when playback is stopped.

◆ JackAudioDriver::relocateUsingBBT

◆ JackAudioDriver::updateTransportPosition

Field Documentation

◆ fHumanizePitchSD

constexpr float fHumanizePitchSD = 0.4
staticconstexpr

Maximum value the standard deviation of the Gaussian distribution the random pitch contribution will be drawn from can take.

The actual standard deviation used during processing is this value multiplied with Instrument::__random_pitch_factor of the instrument associated with the particular #Note.

Definition at line 149 of file AudioEngine.h.

◆ fHumanizeTimingSD

constexpr float fHumanizeTimingSD = 0.3
staticconstexpr

Maximum value the standard deviation of the Gaussian distribution the random pitch contribution will be drawn from can take.

The actual standard deviation used during processing is this value multiplied with Instrument::__random_pitch_factor of the instrument associated with the particular #Note.

Definition at line 159 of file AudioEngine.h.

◆ fHumanizeVelocitySD

constexpr float fHumanizeVelocitySD = 0.2
staticconstexpr

Maximum value the standard deviation of the Gaussian distribution the random velocity contribution will be drawn from can take.

The actual standard deviation used during processing is this value multiplied with Song::m_fHumanizeVelocityValue.

Definition at line 139 of file AudioEngine.h.

◆ m_AudioProcessCallback

audioProcessCallback m_AudioProcessCallback
private

Definition at line 675 of file AudioEngine.h.

◆ m_bJackSupported

bool m_bJackSupported
private

Whether or not the shared library of the JACK server could be found on the system at runtime.

Definition at line 705 of file AudioEngine.h.

◆ m_bLookaheadApplied

bool m_bLookaheadApplied
private

Definition at line 693 of file AudioEngine.h.

◆ m_EngineMutex

std::timed_mutex m_EngineMutex
private

Mutex for synchronizing the access to the Song object and the AudioEngine.

It can be used lock the access using either lock() or try_lock() and to unlock it via unlock(). It is initialized in AudioEngine() and not explicitly exited.

Definition at line 621 of file AudioEngine.h.

◆ m_fFXPeak_L

float m_fFXPeak_L[MAX_FX]
private

Definition at line 603 of file AudioEngine.h.

◆ m_fFXPeak_R

float m_fFXPeak_R[MAX_FX]
private

Definition at line 604 of file AudioEngine.h.

◆ m_fLadspaTime

float m_fLadspaTime
private

Definition at line 647 of file AudioEngine.h.

◆ m_fLastTickEnd

double m_fLastTickEnd
private

Definition at line 692 of file AudioEngine.h.

◆ m_fMasterPeak_L

float m_fMasterPeak_L
private

Definition at line 608 of file AudioEngine.h.

◆ m_fMasterPeak_R

float m_fMasterPeak_R
private

Definition at line 611 of file AudioEngine.h.

◆ m_fMaxProcessTime

float m_fMaxProcessTime
private

Definition at line 646 of file AudioEngine.h.

◆ m_fNextBpm

float m_fNextBpm
private

Definition at line 691 of file AudioEngine.h.

◆ m_fProcessTime

float m_fProcessTime
private

Definition at line 645 of file AudioEngine.h.

◆ m_fSongSizeInTicks

double m_fSongSizeInTicks
private

Set to the total number of ticks in a Song.

Definition at line 653 of file AudioEngine.h.

◆ m_LockingThread

std::thread::id m_LockingThread
private

Thread ID of the current holder of the AudioEngine lock.

Definition at line 637 of file AudioEngine.h.

◆ m_midiNoteQueue

std::deque<Note*> m_midiNoteQueue
private

Midi Note FIFO.

Definition at line 684 of file AudioEngine.h.

◆ m_MutexOutputPointer

QMutex m_MutexOutputPointer
private

Mutex for locking the pointer to the audio output buffer, allowing multiple readers.

When locking this and the AudioEngine, always lock the AudioEngine first using AudioEngine::lock() or AudioEngine::try_lock(). Always use a QMutexLocker to lock this mutex.

Definition at line 632 of file AudioEngine.h.

◆ m_nextState

State m_nextState
private

State assigned during the next call to processTransport().

This is used to start and stop the audio engine.

Definition at line 673 of file AudioEngine.h.

◆ m_nLoopsDone

int m_nLoopsDone
private

Indicates how many loops the transport already did when the user presses the Loop button again.

Definition at line 711 of file AudioEngine.h.

◆ m_nRealtimeFrame

long long m_nRealtimeFrame
private

Variable keeping track of the transport position in realtime.

Even if the audio engine is stopped, the variable will be incremented (as audioEngine_process() would do at the beginning of each cycle) to support realtime keyboard and MIDI event timing.

Definition at line 663 of file AudioEngine.h.

◆ m_pAudioDriver

AudioOutput* m_pAudioDriver
private

Definition at line 597 of file AudioEngine.h.

◆ m_pEventQueue

EventQueue* m_pEventQueue
private

Definition at line 600 of file AudioEngine.h.

◆ m_pLocker

struct H2Core::AudioEngine::_locker_struct m_pLocker
private

◆ m_pMetronomeInstrument

std::shared_ptr<Instrument> m_pMetronomeInstrument
private

Pointer to the metronome.

Definition at line 689 of file AudioEngine.h.

◆ m_pMidiDriver

MidiInput* m_pMidiDriver
private

Definition at line 598 of file AudioEngine.h.

◆ m_pMidiDriverOut

MidiOutput* m_pMidiDriverOut
private

Definition at line 599 of file AudioEngine.h.

◆ m_pQueuingPosition

std::shared_ptr<TransportPosition> m_pQueuingPosition
private

Definition at line 650 of file AudioEngine.h.

◆ m_pSampler

Sampler* m_pSampler
private

Definition at line 595 of file AudioEngine.h.

◆ m_pSynth

Synth* m_pSynth
private

Definition at line 596 of file AudioEngine.h.

◆ m_pTransportPosition

std::shared_ptr<TransportPosition> m_pTransportPosition
private

Definition at line 649 of file AudioEngine.h.

◆ m_songNoteQueue

std::priority_queue<Note*, std::deque<Note*>, compare_pNotes > m_songNoteQueue
private

Definition at line 683 of file AudioEngine.h.

◆ m_state

State m_state
private

Current state of the H2Core::AudioEngine.

Definition at line 668 of file AudioEngine.h.

◆ m_supportedAudioDrivers

QStringList m_supportedAudioDrivers
private

Definition at line 707 of file AudioEngine.h.

◆ nMaxTimeHumanize

constexpr int nMaxTimeHumanize = 2000
staticconstexpr

Maximum time (in frames) a note's position can be off due to the humanization (lead-lag).

Definition at line 164 of file AudioEngine.h.